blob: 26ea2256d45f111000238a0e9dcad95a65126f80 [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
Richard Smith1e12c592011-10-16 21:26:27 +000049 /// EvalStatus - Contains information about the evaluation.
50 Expr::EvalStatus &EvalStatus;
Benjamin Kramerc54061a2011-03-04 13:12:48 +000051
52 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
53 MapTy OpaqueValues;
54 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
55 MapTy::const_iterator i = OpaqueValues.find(e);
56 if (i == OpaqueValues.end()) return 0;
57 return &i->second;
58 }
59
Richard Smith1e12c592011-10-16 21:26:27 +000060 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
61 : Ctx(C), EvalStatus(S) {}
Richard Smithf10d9172011-10-11 21:43:33 +000062
63 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
Benjamin Kramerc54061a2011-03-04 13:12:48 +000064 };
65
John McCallf4cf1a12010-05-07 17:22:02 +000066 struct ComplexValue {
67 private:
68 bool IsInt;
69
70 public:
71 APSInt IntReal, IntImag;
72 APFloat FloatReal, FloatImag;
73
74 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
75
76 void makeComplexFloat() { IsInt = false; }
77 bool isComplexFloat() const { return !IsInt; }
78 APFloat &getComplexFloatReal() { return FloatReal; }
79 APFloat &getComplexFloatImag() { return FloatImag; }
80
81 void makeComplexInt() { IsInt = true; }
82 bool isComplexInt() const { return IsInt; }
83 APSInt &getComplexIntReal() { return IntReal; }
84 APSInt &getComplexIntImag() { return IntImag; }
85
John McCall56ca35d2011-02-17 10:25:35 +000086 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +000087 if (isComplexFloat())
88 v = APValue(FloatReal, FloatImag);
89 else
90 v = APValue(IntReal, IntImag);
91 }
John McCall56ca35d2011-02-17 10:25:35 +000092 void setFrom(const APValue &v) {
93 assert(v.isComplexFloat() || v.isComplexInt());
94 if (v.isComplexFloat()) {
95 makeComplexFloat();
96 FloatReal = v.getComplexFloatReal();
97 FloatImag = v.getComplexFloatImag();
98 } else {
99 makeComplexInt();
100 IntReal = v.getComplexIntReal();
101 IntImag = v.getComplexIntImag();
102 }
103 }
John McCallf4cf1a12010-05-07 17:22:02 +0000104 };
John McCallefdb83e2010-05-07 21:00:08 +0000105
106 struct LValue {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000107 const Expr *Base;
John McCallefdb83e2010-05-07 21:00:08 +0000108 CharUnits Offset;
109
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000110 const Expr *getLValueBase() { return Base; }
John McCallefdb83e2010-05-07 21:00:08 +0000111 CharUnits getLValueOffset() { return Offset; }
112
John McCall56ca35d2011-02-17 10:25:35 +0000113 void moveInto(APValue &v) const {
John McCallefdb83e2010-05-07 21:00:08 +0000114 v = APValue(Base, Offset);
115 }
John McCall56ca35d2011-02-17 10:25:35 +0000116 void setFrom(const APValue &v) {
117 assert(v.isLValue());
118 Base = v.getLValueBase();
119 Offset = v.getLValueOffset();
120 }
John McCallefdb83e2010-05-07 21:00:08 +0000121 };
John McCallf4cf1a12010-05-07 17:22:02 +0000122}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000123
Richard Smith1e12c592011-10-16 21:26:27 +0000124static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
John McCallefdb83e2010-05-07 21:00:08 +0000125static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
126static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000127static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattnerd9becd12009-10-28 23:59:40 +0000128static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
129 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000130static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000131static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000132
133//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000134// Misc utilities
135//===----------------------------------------------------------------------===//
136
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000137static bool IsGlobalLValue(const Expr* E) {
John McCall42c8f872010-05-10 23:27:23 +0000138 if (!E) return true;
139
140 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
141 if (isa<FunctionDecl>(DRE->getDecl()))
142 return true;
143 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
144 return VD->hasGlobalStorage();
145 return false;
146 }
147
148 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
149 return CLE->isFileScope();
150
151 return true;
152}
153
Richard Smith436c8892011-10-24 23:14:33 +0000154static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
John McCallefdb83e2010-05-07 21:00:08 +0000155 const Expr* Base = Value.Base;
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000156
John McCall35542832010-05-07 21:34:32 +0000157 // A null base expression indicates a null pointer. These are always
158 // evaluatable, and they are false unless the offset is zero.
159 if (!Base) {
160 Result = !Value.Offset.isZero();
161 return true;
162 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000163
John McCall42c8f872010-05-10 23:27:23 +0000164 // Require the base expression to be a global l-value.
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000165 if (!IsGlobalLValue(Base)) return false;
John McCall42c8f872010-05-10 23:27:23 +0000166
John McCall35542832010-05-07 21:34:32 +0000167 // We have a non-null base expression. These are generally known to
168 // be true, but if it'a decl-ref to a weak symbol it can be null at
169 // runtime.
John McCall35542832010-05-07 21:34:32 +0000170 Result = true;
171
172 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000173 if (!DeclRef)
174 return true;
175
John McCall35542832010-05-07 21:34:32 +0000176 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000177 const ValueDecl* Decl = DeclRef->getDecl();
178 if (Decl->hasAttr<WeakAttr>() ||
179 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000180 Decl->isWeakImported())
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000181 return false;
182
Eli Friedman5bc86102009-06-14 02:17:33 +0000183 return true;
184}
185
Richard Smith436c8892011-10-24 23:14:33 +0000186static bool HandleConversionToBool(const Expr* E, bool& Result,
187 EvalInfo &Info) {
188 if (E->getType()->isIntegralOrEnumerationType()) {
189 APSInt IntResult;
190 if (!EvaluateInteger(E, IntResult, Info))
191 return false;
192 Result = IntResult != 0;
Eli Friedman4efaa272008-11-12 09:44:48 +0000193 return true;
Richard Smith436c8892011-10-24 23:14:33 +0000194 } else if (E->getType()->isRealFloatingType()) {
195 APFloat FloatResult(0.0);
196 if (!EvaluateFloat(E, FloatResult, Info))
197 return false;
198 Result = !FloatResult.isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +0000199 return true;
Richard Smith436c8892011-10-24 23:14:33 +0000200 } else if (E->getType()->hasPointerRepresentation()) {
201 LValue PointerResult;
202 if (!EvaluatePointer(E, PointerResult, Info))
203 return false;
204 return EvalPointerValueAsBool(PointerResult, Result);
205 } else if (E->getType()->isAnyComplexType()) {
206 ComplexValue ComplexResult;
207 if (!EvaluateComplex(E, ComplexResult, Info))
208 return false;
209 if (ComplexResult.isComplexFloat()) {
210 Result = !ComplexResult.getComplexFloatReal().isZero() ||
211 !ComplexResult.getComplexFloatImag().isZero();
212 } else {
213 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
214 ComplexResult.getComplexIntImag().getBoolValue();
Eli Friedmana1f47c42009-03-23 04:38:34 +0000215 }
Richard Smith436c8892011-10-24 23:14:33 +0000216 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000217 }
218
Richard Smith436c8892011-10-24 23:14:33 +0000219 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000220}
221
Mike Stump1eb44332009-09-09 15:08:12 +0000222static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000223 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000224 unsigned DestWidth = Ctx.getIntWidth(DestType);
225 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000226 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000228 // FIXME: Warning for overflow.
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000229 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000230 bool ignored;
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000231 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
232 return Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000233}
234
Mike Stump1eb44332009-09-09 15:08:12 +0000235static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000236 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000237 bool ignored;
238 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000239 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000240 APFloat::rmNearestTiesToEven, &ignored);
241 return Result;
242}
243
Mike Stump1eb44332009-09-09 15:08:12 +0000244static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000245 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000246 unsigned DestWidth = Ctx.getIntWidth(DestType);
247 APSInt Result = Value;
248 // Figure out if this is a truncate, extend or noop cast.
249 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000250 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000251 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000252 return Result;
253}
254
Mike Stump1eb44332009-09-09 15:08:12 +0000255static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000256 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000257
258 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
259 Result.convertFromAPInt(Value, Value.isSigned(),
260 APFloat::rmNearestTiesToEven);
261 return Result;
262}
263
Richard Smith03f96112011-10-24 17:54:18 +0000264/// Try to evaluate the initializer for a variable declaration.
265static APValue *EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD) {
266 if (isa<ParmVarDecl>(VD))
267 return 0;
268
269 const Expr *Init = VD->getAnyInitializer();
270 if (!Init)
271 return 0;
272
273 if (APValue *V = VD->getEvaluatedValue())
274 return V;
275
276 if (VD->isEvaluatingValue())
277 return 0;
278
279 VD->setEvaluatingValue();
280
Richard Smith436c8892011-10-24 23:14:33 +0000281 // FIXME: If the initializer isn't a constant expression, propagate up any
282 // diagnostic explaining why not.
Richard Smith03f96112011-10-24 17:54:18 +0000283 Expr::EvalResult EResult;
Richard Smith436c8892011-10-24 23:14:33 +0000284 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects)
Richard Smith03f96112011-10-24 17:54:18 +0000285 VD->setEvaluatedValue(EResult.Val);
286 else
287 VD->setEvaluatedValue(APValue());
288
289 return VD->getEvaluatedValue();
290}
291
292bool IsConstNonVolatile(QualType T) {
293 Qualifiers Quals = T.getQualifiers();
294 return Quals.hasConst() && !Quals.hasVolatile();
295}
296
Mike Stumpc4c90452009-10-27 22:09:17 +0000297namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000298class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000299 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +0000300 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +0000301public:
302
Richard Smith1e12c592011-10-16 21:26:27 +0000303 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +0000304
305 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000306 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +0000307 return true;
308 }
309
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000310 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
311 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +0000312 return Visit(E->getResultExpr());
313 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000314 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +0000315 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000316 return true;
317 return false;
318 }
John McCallf85e1932011-06-15 23:02:42 +0000319 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +0000320 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +0000321 return true;
322 return false;
323 }
324 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +0000325 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +0000326 return true;
327 return false;
328 }
329
Mike Stumpc4c90452009-10-27 22:09:17 +0000330 // We don't want to evaluate BlockExprs multiple times, as they generate
331 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000332 bool VisitBlockExpr(const BlockExpr *E) { return true; }
333 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
334 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +0000335 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000336 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
337 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
338 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
339 bool VisitStringLiteral(const StringLiteral *E) { return false; }
340 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
341 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000342 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000343 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000344 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000345 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +0000346 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000347 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
348 bool VisitBinAssign(const BinaryOperator *E) { return true; }
349 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
350 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +0000351 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000352 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
353 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
354 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
355 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
356 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +0000357 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000358 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000359 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000360 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000361 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000362
363 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000364 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +0000365 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
366 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000367 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000368 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +0000369 return false;
370 }
Douglas Gregoree8aff02011-01-04 17:33:58 +0000371
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000372 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000373};
374
John McCall56ca35d2011-02-17 10:25:35 +0000375class OpaqueValueEvaluation {
376 EvalInfo &info;
377 OpaqueValueExpr *opaqueValue;
378
379public:
380 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
381 Expr *value)
382 : info(info), opaqueValue(opaqueValue) {
383
384 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +0000385 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +0000386 this->opaqueValue = 0;
387 return;
388 }
John McCall56ca35d2011-02-17 10:25:35 +0000389 }
390
391 bool hasError() const { return opaqueValue == 0; }
392
393 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +0000394 // FIXME: This will not work for recursive constexpr functions using opaque
395 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +0000396 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
397 }
398};
399
Mike Stumpc4c90452009-10-27 22:09:17 +0000400} // end anonymous namespace
401
Eli Friedman4efaa272008-11-12 09:44:48 +0000402//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000403// Generic Evaluation
404//===----------------------------------------------------------------------===//
405namespace {
406
407template <class Derived, typename RetTy=void>
408class ExprEvaluatorBase
409 : public ConstStmtVisitor<Derived, RetTy> {
410private:
411 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
412 return static_cast<Derived*>(this)->Success(V, E);
413 }
414 RetTy DerivedError(const Expr *E) {
415 return static_cast<Derived*>(this)->Error(E);
416 }
Richard Smithf10d9172011-10-11 21:43:33 +0000417 RetTy DerivedValueInitialization(const Expr *E) {
418 return static_cast<Derived*>(this)->ValueInitialization(E);
419 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000420
421protected:
422 EvalInfo &Info;
423 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
424 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
425
Richard Smithf10d9172011-10-11 21:43:33 +0000426 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
427
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000428public:
429 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
430
431 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000432 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000433 }
434 RetTy VisitExpr(const Expr *E) {
435 return DerivedError(E);
436 }
437
438 RetTy VisitParenExpr(const ParenExpr *E)
439 { return StmtVisitorTy::Visit(E->getSubExpr()); }
440 RetTy VisitUnaryExtension(const UnaryOperator *E)
441 { return StmtVisitorTy::Visit(E->getSubExpr()); }
442 RetTy VisitUnaryPlus(const UnaryOperator *E)
443 { return StmtVisitorTy::Visit(E->getSubExpr()); }
444 RetTy VisitChooseExpr(const ChooseExpr *E)
445 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
446 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
447 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +0000448 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
449 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000450
451 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
452 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
453 if (opaque.hasError())
454 return DerivedError(E);
455
456 bool cond;
Richard Smith436c8892011-10-24 23:14:33 +0000457 if (!HandleConversionToBool(E->getCond(), cond, Info))
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000458 return DerivedError(E);
459
460 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
461 }
462
463 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
464 bool BoolResult;
Richard Smith436c8892011-10-24 23:14:33 +0000465 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000466 return DerivedError(E);
467
Richard Smith436c8892011-10-24 23:14:33 +0000468 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000469 return StmtVisitorTy::Visit(EvalExpr);
470 }
471
472 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
473 const APValue *value = Info.getOpaqueValue(E);
474 if (!value)
475 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
476 : DerivedError(E));
477 return DerivedSuccess(*value, E);
478 }
Richard Smithf10d9172011-10-11 21:43:33 +0000479
480 RetTy VisitInitListExpr(const InitListExpr *E) {
481 if (Info.getLangOpts().CPlusPlus0x) {
482 if (E->getNumInits() == 0)
483 return DerivedValueInitialization(E);
484 if (E->getNumInits() == 1)
485 return StmtVisitorTy::Visit(E->getInit(0));
486 }
487 return DerivedError(E);
488 }
489 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
490 return DerivedValueInitialization(E);
491 }
492 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
493 return DerivedValueInitialization(E);
494 }
495
Richard Smith8327fad2011-10-24 18:44:57 +0000496 /// Visit a value which is evaluated, but whose value is ignored.
497 void VisitIgnoredValue(const Expr *E) {
498 APValue Scratch;
499 if (!Evaluate(Scratch, Info, E))
500 Info.EvalStatus.HasSideEffects = true;
501 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000502};
503
504}
505
506//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000507// LValue Evaluation
508//===----------------------------------------------------------------------===//
509namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000510class LValueExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000511 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000512 LValue &Result;
Chandler Carruth01248392011-08-22 17:24:56 +0000513 const Decl *PrevDecl;
John McCallefdb83e2010-05-07 21:00:08 +0000514
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000515 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000516 Result.Base = E;
517 Result.Offset = CharUnits::Zero();
518 return true;
519 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000520public:
Mike Stump1eb44332009-09-09 15:08:12 +0000521
John McCallefdb83e2010-05-07 21:00:08 +0000522 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth01248392011-08-22 17:24:56 +0000523 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000524
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000525 bool Success(const APValue &V, const Expr *E) {
526 Result.setFrom(V);
527 return true;
528 }
529 bool Error(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000530 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000531 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000532
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000533 bool VisitDeclRefExpr(const DeclRefExpr *E);
534 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
535 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
536 bool VisitMemberExpr(const MemberExpr *E);
537 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
538 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
539 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
540 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +0000541
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000542 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000543 switch (E->getCastKind()) {
544 default:
Richard Smith436c8892011-10-24 23:14:33 +0000545 return false;
Anders Carlsson26bc2202009-10-03 16:30:22 +0000546
Richard Smith436c8892011-10-24 23:14:33 +0000547 case CK_NoOp:
Eli Friedmandb924222011-10-11 00:13:24 +0000548 case CK_LValueBitCast:
Anders Carlsson26bc2202009-10-03 16:30:22 +0000549 return Visit(E->getSubExpr());
Eli Friedmandb924222011-10-11 00:13:24 +0000550
Richard Smith436c8892011-10-24 23:14:33 +0000551 // FIXME: Support CK_DerivedToBase and friends.
Anders Carlsson26bc2202009-10-03 16:30:22 +0000552 }
553 }
Sebastian Redlcea8d962011-09-24 17:48:14 +0000554
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000555 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000556
Eli Friedman4efaa272008-11-12 09:44:48 +0000557};
558} // end anonymous namespace
559
John McCallefdb83e2010-05-07 21:00:08 +0000560static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000561 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000562}
563
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000564bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000565 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000566 return Success(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000567 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000568 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000569 return Success(E);
Chandler Carruth761c94e2010-05-16 09:32:51 +0000570 // Reference parameters can refer to anything even if they have an
571 // "initializer" in the form of a default argument.
Chandler Carruth01248392011-08-22 17:24:56 +0000572 if (!isa<ParmVarDecl>(VD)) {
Richard Smith436c8892011-10-24 23:14:33 +0000573 // FIXME: Check whether VD might be overridden!
574
575 // Check for recursive initializers of references.
576 if (PrevDecl == VD)
577 return Error(E);
578 PrevDecl = VD;
579 if (const Expr *Init = VD->getAnyInitializer())
580 return Visit(Init);
Chandler Carruth01248392011-08-22 17:24:56 +0000581 }
Eli Friedman50c39ea2009-05-27 06:04:58 +0000582 }
583
Richard Smith436c8892011-10-24 23:14:33 +0000584 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Anders Carlsson35873c42008-11-24 04:41:22 +0000585}
586
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000587bool
588LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000589 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000590}
591
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000592bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000593 QualType Ty;
594 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000595 if (!EvaluatePointer(E->getBase(), Result, Info))
596 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000597 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000598 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000599 if (!Visit(E->getBase()))
600 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000601 Ty = E->getBase()->getType();
602 }
603
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000604 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000605 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000606
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000607 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor86f19402008-12-20 23:49:58 +0000608 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000609 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000610
611 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000612 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000613
Eli Friedman82905742011-07-07 01:54:01 +0000614 unsigned i = FD->getFieldIndex();
Ken Dyckfb1e3bc2011-01-18 01:56:16 +0000615 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCallefdb83e2010-05-07 21:00:08 +0000616 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000617}
618
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000619bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000620 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000621 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Anders Carlsson3068d112008-11-16 19:01:22 +0000623 APSInt Index;
624 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000625 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000626
Ken Dyck199c3d62010-01-11 17:06:35 +0000627 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000628 Result.Offset += Index.getSExtValue() * ElementSize;
629 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000630}
Eli Friedman4efaa272008-11-12 09:44:48 +0000631
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000632bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000633 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000634}
635
Eli Friedman4efaa272008-11-12 09:44:48 +0000636//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000637// Pointer Evaluation
638//===----------------------------------------------------------------------===//
639
Anders Carlssonc754aa62008-07-08 05:13:58 +0000640namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000641class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000642 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000643 LValue &Result;
644
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000645 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000646 Result.Base = E;
647 Result.Offset = CharUnits::Zero();
648 return true;
649 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000650public:
Mike Stump1eb44332009-09-09 15:08:12 +0000651
John McCallefdb83e2010-05-07 21:00:08 +0000652 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000653 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000654
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000655 bool Success(const APValue &V, const Expr *E) {
656 Result.setFrom(V);
657 return true;
658 }
659 bool Error(const Stmt *S) {
John McCallefdb83e2010-05-07 21:00:08 +0000660 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000661 }
Richard Smithf10d9172011-10-11 21:43:33 +0000662 bool ValueInitialization(const Expr *E) {
663 return Success((Expr*)0);
664 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000665
John McCallefdb83e2010-05-07 21:00:08 +0000666 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000667 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +0000668 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000669 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +0000670 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000671 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000672 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000673 bool VisitCallExpr(const CallExpr *E);
674 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +0000675 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +0000676 return Success(E);
677 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000678 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000679 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smithf10d9172011-10-11 21:43:33 +0000680 { return ValueInitialization(E); }
John McCall56ca35d2011-02-17 10:25:35 +0000681
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000682 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000683};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000684} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000685
John McCallefdb83e2010-05-07 21:00:08 +0000686static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith436c8892011-10-24 23:14:33 +0000687 assert(E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000688 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000689}
690
John McCallefdb83e2010-05-07 21:00:08 +0000691bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000692 if (E->getOpcode() != BO_Add &&
693 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000694 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000696 const Expr *PExp = E->getLHS();
697 const Expr *IExp = E->getRHS();
698 if (IExp->getType()->isPointerType())
699 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000700
John McCallefdb83e2010-05-07 21:00:08 +0000701 if (!EvaluatePointer(PExp, Result, Info))
702 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000703
John McCallefdb83e2010-05-07 21:00:08 +0000704 llvm::APSInt Offset;
705 if (!EvaluateInteger(IExp, Offset, Info))
706 return false;
707 int64_t AdditionalOffset
708 = Offset.isSigned() ? Offset.getSExtValue()
709 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000710
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000711 // Compute the new offset in the appropriate width.
712
713 QualType PointeeType =
714 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000715 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000717 // Explicitly handle GNU void* and function pointer arithmetic extensions.
718 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000719 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000720 else
John McCallefdb83e2010-05-07 21:00:08 +0000721 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000722
John McCall2de56d12010-08-25 11:45:40 +0000723 if (E->getOpcode() == BO_Add)
John McCallefdb83e2010-05-07 21:00:08 +0000724 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000725 else
John McCallefdb83e2010-05-07 21:00:08 +0000726 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000727
John McCallefdb83e2010-05-07 21:00:08 +0000728 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000729}
Eli Friedman4efaa272008-11-12 09:44:48 +0000730
John McCallefdb83e2010-05-07 21:00:08 +0000731bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
732 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000733}
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000735
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000736bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
737 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000738
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000739 switch (E->getCastKind()) {
740 default:
741 break;
742
Richard Smith436c8892011-10-24 23:14:33 +0000743 case CK_NoOp:
John McCall2de56d12010-08-25 11:45:40 +0000744 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +0000745 case CK_CPointerToObjCPointerCast:
746 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +0000747 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000748 return Visit(SubExpr);
749
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000750 case CK_DerivedToBase:
751 case CK_UncheckedDerivedToBase: {
752 LValue BaseLV;
753 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
754 return false;
755
756 // Now figure out the necessary offset to add to the baseLV to get from
757 // the derived class to the base class.
Ken Dyck7c7f8202011-01-26 02:17:08 +0000758 CharUnits Offset = CharUnits::Zero();
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000759
760 QualType Ty = E->getSubExpr()->getType();
761 const CXXRecordDecl *DerivedDecl =
762 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
763
764 for (CastExpr::path_const_iterator PathI = E->path_begin(),
765 PathE = E->path_end(); PathI != PathE; ++PathI) {
766 const CXXBaseSpecifier *Base = *PathI;
767
768 // FIXME: If the base is virtual, we'd need to determine the type of the
769 // most derived class and we don't support that right now.
770 if (Base->isVirtual())
771 return false;
772
773 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
774 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
775
Ken Dyck7c7f8202011-01-26 02:17:08 +0000776 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000777 DerivedDecl = BaseDecl;
778 }
779
780 Result.Base = BaseLV.getLValueBase();
Ken Dyck7c7f8202011-01-26 02:17:08 +0000781 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000782 return true;
783 }
784
John McCall404cd162010-11-13 01:35:44 +0000785 case CK_NullToPointer: {
786 Result.Base = 0;
787 Result.Offset = CharUnits::Zero();
788 return true;
789 }
790
John McCall2de56d12010-08-25 11:45:40 +0000791 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000792 APValue Value;
793 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000794 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000795
John McCallefdb83e2010-05-07 21:00:08 +0000796 if (Value.isInt()) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000797 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCallefdb83e2010-05-07 21:00:08 +0000798 Result.Base = 0;
799 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
800 return true;
801 } else {
802 // Cast is of an lvalue, no need to change value.
803 Result.Base = Value.getLValueBase();
804 Result.Offset = Value.getLValueOffset();
805 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000806 }
807 }
John McCall2de56d12010-08-25 11:45:40 +0000808 case CK_ArrayToPointerDecay:
809 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000810 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000811 }
812
Richard Smith436c8892011-10-24 23:14:33 +0000813 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000814}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000815
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000816bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000817 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000818 Builtin::BI__builtin___CFStringMakeConstantString ||
819 E->isBuiltinCall(Info.Ctx) ==
820 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000821 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +0000822
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000823 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000824}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000825
826//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000827// Vector Evaluation
828//===----------------------------------------------------------------------===//
829
830namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000831 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +0000832 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
833 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +0000834 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Richard Smith07fc6572011-10-22 21:10:00 +0000836 VectorExprEvaluator(EvalInfo &info, APValue &Result)
837 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Richard Smith07fc6572011-10-22 21:10:00 +0000839 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
840 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
841 // FIXME: remove this APValue copy.
842 Result = APValue(V.data(), V.size());
843 return true;
844 }
845 bool Success(const APValue &V, const Expr *E) {
846 Result = V;
847 return true;
848 }
849 bool Error(const Expr *E) { return false; }
850 bool ValueInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Richard Smith07fc6572011-10-22 21:10:00 +0000852 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +0000853 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +0000854 bool VisitCastExpr(const CastExpr* E);
Richard Smith436c8892011-10-24 23:14:33 +0000855 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
Richard Smith07fc6572011-10-22 21:10:00 +0000856 bool VisitInitListExpr(const InitListExpr *E);
857 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000858 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000859 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000860 // shufflevector, ExtVectorElementExpr
861 // (Note that these require implementing conversions
862 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000863 };
864} // end anonymous namespace
865
866static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith436c8892011-10-24 23:14:33 +0000867 if (!E->getType()->isVectorType())
868 return false;
Richard Smith07fc6572011-10-22 21:10:00 +0000869 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +0000870}
871
Richard Smith07fc6572011-10-22 21:10:00 +0000872bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
873 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000874 QualType EltTy = VTy->getElementType();
875 unsigned NElts = VTy->getNumElements();
876 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000877
Nate Begeman59b5da62009-01-18 03:20:47 +0000878 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000879 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +0000880
Eli Friedman46a52322011-03-25 00:43:55 +0000881 switch (E->getCastKind()) {
882 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +0000883 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000884 if (SETy->isIntegerType()) {
885 APSInt IntResult;
886 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith07fc6572011-10-22 21:10:00 +0000887 return Error(E);
888 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +0000889 } else if (SETy->isRealFloatingType()) {
890 APFloat F(0.0);
891 if (!EvaluateFloat(SE, F, Info))
Richard Smith07fc6572011-10-22 21:10:00 +0000892 return Error(E);
893 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +0000894 } else {
Richard Smith07fc6572011-10-22 21:10:00 +0000895 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +0000896 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000897
898 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +0000899 SmallVector<APValue, 4> Elts(NElts, Val);
900 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +0000901 }
Eli Friedman46a52322011-03-25 00:43:55 +0000902 case CK_BitCast: {
Richard Smith07fc6572011-10-22 21:10:00 +0000903 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedman46a52322011-03-25 00:43:55 +0000904 if (SETy->isVectorType())
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000905 return Visit(SE);
Nate Begemanc0b8b192009-07-01 07:50:47 +0000906
Eli Friedman46a52322011-03-25 00:43:55 +0000907 if (!SETy->isIntegerType())
Richard Smith07fc6572011-10-22 21:10:00 +0000908 return Error(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Eli Friedman46a52322011-03-25 00:43:55 +0000910 APSInt Init;
911 if (!EvaluateInteger(SE, Init, Info))
Richard Smith07fc6572011-10-22 21:10:00 +0000912 return Error(E);
Nate Begemanc0b8b192009-07-01 07:50:47 +0000913
Eli Friedman46a52322011-03-25 00:43:55 +0000914 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
915 "Vectors must be composed of ints or floats");
916
Chris Lattner5f9e2722011-07-23 10:55:15 +0000917 SmallVector<APValue, 4> Elts;
Eli Friedman46a52322011-03-25 00:43:55 +0000918 for (unsigned i = 0; i != NElts; ++i) {
919 APSInt Tmp = Init.extOrTrunc(EltWidth);
920
921 if (EltTy->isIntegerType())
922 Elts.push_back(APValue(Tmp));
923 else
924 Elts.push_back(APValue(APFloat(Tmp)));
925
926 Init >>= EltWidth;
927 }
Richard Smith07fc6572011-10-22 21:10:00 +0000928 return Success(Elts, E);
Nate Begemanc0b8b192009-07-01 07:50:47 +0000929 }
Richard Smith436c8892011-10-24 23:14:33 +0000930 case CK_LValueToRValue:
931 case CK_NoOp:
932 return Visit(SE);
Eli Friedman46a52322011-03-25 00:43:55 +0000933 default:
Richard Smith436c8892011-10-24 23:14:33 +0000934 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +0000935 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000936}
937
Richard Smith07fc6572011-10-22 21:10:00 +0000938bool
Richard Smith436c8892011-10-24 23:14:33 +0000939VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
940 return Visit(E->getInitializer());
941}
942
943bool
Nate Begeman59b5da62009-01-18 03:20:47 +0000944VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +0000945 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000946 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000947 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Nate Begeman59b5da62009-01-18 03:20:47 +0000949 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000950 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +0000951
John McCalla7d6c222010-06-11 17:54:15 +0000952 // If a vector is initialized with a single element, that value
953 // becomes every element of the vector, not just the first.
954 // This is the behavior described in the IBM AltiVec documentation.
955 if (NumInits == 1) {
Richard Smith07fc6572011-10-22 21:10:00 +0000956
957 // Handle the case where the vector is initialized by another
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +0000958 // vector (OpenCL 6.1.6).
959 if (E->getInit(0)->getType()->isVectorType())
Richard Smith07fc6572011-10-22 21:10:00 +0000960 return Visit(E->getInit(0));
961
John McCalla7d6c222010-06-11 17:54:15 +0000962 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000963 if (EltTy->isIntegerType()) {
964 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000965 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith07fc6572011-10-22 21:10:00 +0000966 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +0000967 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000968 } else {
969 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000970 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith07fc6572011-10-22 21:10:00 +0000971 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +0000972 InitValue = APValue(f);
973 }
974 for (unsigned i = 0; i < NumElements; i++) {
975 Elements.push_back(InitValue);
976 }
977 } else {
978 for (unsigned i = 0; i < NumElements; i++) {
979 if (EltTy->isIntegerType()) {
980 llvm::APSInt sInt(32);
981 if (i < NumInits) {
982 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith07fc6572011-10-22 21:10:00 +0000983 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +0000984 } else {
985 sInt = Info.Ctx.MakeIntValue(0, EltTy);
986 }
987 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000988 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000989 llvm::APFloat f(0.0);
990 if (i < NumInits) {
991 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith07fc6572011-10-22 21:10:00 +0000992 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +0000993 } else {
994 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
995 }
996 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000997 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000998 }
999 }
Richard Smith07fc6572011-10-22 21:10:00 +00001000 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00001001}
1002
Richard Smith07fc6572011-10-22 21:10:00 +00001003bool
1004VectorExprEvaluator::ValueInitialization(const Expr *E) {
1005 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00001006 QualType EltTy = VT->getElementType();
1007 APValue ZeroElement;
1008 if (EltTy->isIntegerType())
1009 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1010 else
1011 ZeroElement =
1012 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1013
Chris Lattner5f9e2722011-07-23 10:55:15 +00001014 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00001015 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00001016}
1017
Richard Smith07fc6572011-10-22 21:10:00 +00001018bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00001019 VisitIgnoredValue(E->getSubExpr());
Richard Smith07fc6572011-10-22 21:10:00 +00001020 return ValueInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00001021}
1022
Nate Begeman59b5da62009-01-18 03:20:47 +00001023//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001024// Integer Evaluation
1025//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001026
1027namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001028class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001029 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001030 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00001031public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001032 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001033 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001034
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001035 bool Success(const llvm::APSInt &SI, const Expr *E) {
1036 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001037 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001038 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001039 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001040 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001041 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001042 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001043 return true;
1044 }
1045
Daniel Dunbar131eb432009-02-19 09:06:44 +00001046 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001047 assert(E->getType()->isIntegralOrEnumerationType() &&
1048 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001049 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001050 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001051 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00001052 Result.getInt().setIsUnsigned(
1053 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00001054 return true;
1055 }
1056
1057 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001058 assert(E->getType()->isIntegralOrEnumerationType() &&
1059 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001060 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00001061 return true;
1062 }
1063
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001064 bool Success(CharUnits Size, const Expr *E) {
1065 return Success(Size.getQuantity(), E);
1066 }
1067
1068
Anders Carlsson82206e22008-11-30 18:14:57 +00001069 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001070 // Take the first error.
Richard Smith1e12c592011-10-16 21:26:27 +00001071 if (Info.EvalStatus.Diag == 0) {
1072 Info.EvalStatus.DiagLoc = L;
1073 Info.EvalStatus.Diag = D;
1074 Info.EvalStatus.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +00001075 }
Chris Lattner54176fd2008-07-12 00:14:42 +00001076 return false;
Chris Lattner7a767782008-07-11 19:24:49 +00001077 }
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001079 bool Success(const APValue &V, const Expr *E) {
1080 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00001081 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001082 bool Error(const Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001083 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +00001084 }
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Richard Smithf10d9172011-10-11 21:43:33 +00001086 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1087
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001088 //===--------------------------------------------------------------------===//
1089 // Visitor Methods
1090 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00001091
Chris Lattner4c4867e2008-07-12 00:38:25 +00001092 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001093 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001094 }
1095 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001096 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001097 }
Eli Friedman04309752009-11-24 05:28:59 +00001098
1099 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1100 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001101 if (CheckReferencedDecl(E, E->getDecl()))
1102 return true;
1103
1104 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001105 }
1106 bool VisitMemberExpr(const MemberExpr *E) {
1107 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith436c8892011-10-24 23:14:33 +00001108 // Conservatively assume a MemberExpr will have side-effects
1109 Info.EvalStatus.HasSideEffects = true;
Eli Friedman04309752009-11-24 05:28:59 +00001110 return true;
1111 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001112
1113 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001114 }
1115
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001116 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001117 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001118 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001119 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00001120
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001121 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001122 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00001123
Anders Carlsson3068d112008-11-16 19:01:22 +00001124 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001125 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001126 }
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Richard Smithf10d9172011-10-11 21:43:33 +00001128 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00001129 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00001130 return ValueInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00001131 }
1132
Sebastian Redl64b45f72009-01-05 20:52:13 +00001133 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001134 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001135 }
1136
Francois Pichet6ad6f282010-12-07 00:08:36 +00001137 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1138 return Success(E->getValue(), E);
1139 }
1140
John Wiegley21ff2e52011-04-28 00:16:57 +00001141 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1142 return Success(E->getValue(), E);
1143 }
1144
John Wiegley55262202011-04-25 06:54:41 +00001145 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1146 return Success(E->getValue(), E);
1147 }
1148
Eli Friedman722c7172009-02-28 03:59:05 +00001149 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001150 bool VisitUnaryImag(const UnaryOperator *E);
1151
Sebastian Redl295995c2010-09-10 20:55:47 +00001152 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001153 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00001154
Chris Lattnerfcee0012008-07-11 21:24:13 +00001155private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001156 CharUnits GetAlignOfExpr(const Expr *E);
1157 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001158 static QualType GetObjectType(const Expr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001159 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001160 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001161};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001162} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001163
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001164static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Richard Smith436c8892011-10-24 23:14:33 +00001165 assert(E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001166 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001167}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001168
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001169static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith436c8892011-10-24 23:14:33 +00001170 assert(E->getType()->isIntegralOrEnumerationType());
1171
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001172 APValue Val;
1173 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1174 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001175 Result = Val.getInt();
1176 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001177}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001178
Eli Friedman04309752009-11-24 05:28:59 +00001179bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001180 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001181 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001182 // Check for signedness/width mismatches between E type and ECD value.
1183 bool SameSign = (ECD->getInitVal().isSigned()
1184 == E->getType()->isSignedIntegerOrEnumerationType());
1185 bool SameWidth = (ECD->getInitVal().getBitWidth()
1186 == Info.Ctx.getIntWidth(E->getType()));
1187 if (SameSign && SameWidth)
1188 return Success(ECD->getInitVal(), E);
1189 else {
1190 // Get rid of mismatch (otherwise Success assertions will fail)
1191 // by computing a new value matching the type of E.
1192 llvm::APSInt Val = ECD->getInitVal();
1193 if (!SameSign)
1194 Val.setIsSigned(!ECD->getInitVal().isSigned());
1195 if (!SameWidth)
1196 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1197 return Success(Val, E);
1198 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001199 }
Richard Smith436c8892011-10-24 23:14:33 +00001200
1201 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
1202 // In C, they can also be folded, although they are not ICEs.
1203 if (IsConstNonVolatile(E->getType())) {
1204 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1205 APValue *V = EvaluateVarDeclInit(Info, VD);
1206 if (V && V->isInt())
1207 return Success(V->getInt(), E);
1208 }
1209 }
1210
1211 // Otherwise, random variable references are not constants.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001212 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00001213}
1214
Chris Lattnera4d55d82008-10-06 06:40:35 +00001215/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1216/// as GCC.
1217static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1218 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001219 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001220 enum gcc_type_class {
1221 no_type_class = -1,
1222 void_type_class, integer_type_class, char_type_class,
1223 enumeral_type_class, boolean_type_class,
1224 pointer_type_class, reference_type_class, offset_type_class,
1225 real_type_class, complex_type_class,
1226 function_type_class, method_type_class,
1227 record_type_class, union_type_class,
1228 array_type_class, string_type_class,
1229 lang_type_class
1230 };
Mike Stump1eb44332009-09-09 15:08:12 +00001231
1232 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001233 // ideal, however it is what gcc does.
1234 if (E->getNumArgs() == 0)
1235 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Chris Lattnera4d55d82008-10-06 06:40:35 +00001237 QualType ArgTy = E->getArg(0)->getType();
1238 if (ArgTy->isVoidType())
1239 return void_type_class;
1240 else if (ArgTy->isEnumeralType())
1241 return enumeral_type_class;
1242 else if (ArgTy->isBooleanType())
1243 return boolean_type_class;
1244 else if (ArgTy->isCharType())
1245 return string_type_class; // gcc doesn't appear to use char_type_class
1246 else if (ArgTy->isIntegerType())
1247 return integer_type_class;
1248 else if (ArgTy->isPointerType())
1249 return pointer_type_class;
1250 else if (ArgTy->isReferenceType())
1251 return reference_type_class;
1252 else if (ArgTy->isRealType())
1253 return real_type_class;
1254 else if (ArgTy->isComplexType())
1255 return complex_type_class;
1256 else if (ArgTy->isFunctionType())
1257 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001258 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001259 return record_type_class;
1260 else if (ArgTy->isUnionType())
1261 return union_type_class;
1262 else if (ArgTy->isArrayType())
1263 return array_type_class;
1264 else if (ArgTy->isUnionType())
1265 return union_type_class;
1266 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00001267 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00001268 return -1;
1269}
1270
John McCall42c8f872010-05-10 23:27:23 +00001271/// Retrieves the "underlying object type" of the given expression,
1272/// as used by __builtin_object_size.
1273QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1274 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1275 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1276 return VD->getType();
1277 } else if (isa<CompoundLiteralExpr>(E)) {
1278 return E->getType();
1279 }
1280
1281 return QualType();
1282}
1283
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001284bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00001285 // TODO: Perhaps we should let LLVM lower this?
1286 LValue Base;
1287 if (!EvaluatePointer(E->getArg(0), Base, Info))
1288 return false;
1289
1290 // If we can prove the base is null, lower to zero now.
1291 const Expr *LVBase = Base.getLValueBase();
1292 if (!LVBase) return Success(0, E);
1293
1294 QualType T = GetObjectType(LVBase);
1295 if (T.isNull() ||
1296 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001297 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001298 T->isVariablyModifiedType() ||
1299 T->isDependentType())
1300 return false;
1301
1302 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1303 CharUnits Offset = Base.getLValueOffset();
1304
1305 if (!Offset.isNegative() && Offset <= Size)
1306 Size -= Offset;
1307 else
1308 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001309 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00001310}
1311
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001312bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001313 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001314 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001315 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001316
1317 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001318 if (TryEvaluateBuiltinObjectSize(E))
1319 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001320
Eric Christopherb2aaf512010-01-19 22:58:35 +00001321 // If evaluating the argument has side-effects we can't determine
1322 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001323 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001324 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001325 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001326 return Success(0, E);
1327 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001328
Mike Stump64eda9e2009-10-26 18:35:08 +00001329 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1330 }
1331
Chris Lattner019f4e82008-10-06 05:28:25 +00001332 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001333 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001334
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001335 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001336 // __builtin_constant_p always has one operand: it returns true if that
1337 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001338 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001339
1340 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001341 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001342 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001343 return Success(Operand, E);
1344 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001345
1346 case Builtin::BI__builtin_expect:
1347 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001348
1349 case Builtin::BIstrlen:
1350 case Builtin::BI__builtin_strlen:
1351 // As an extension, we support strlen() and __builtin_strlen() as constant
1352 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001353 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00001354 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1355 // The string literal may have embedded null characters. Find the first
1356 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001357 StringRef Str = S->getString();
1358 StringRef::size_type Pos = Str.find(0);
1359 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00001360 Str = Str.substr(0, Pos);
1361
1362 return Success(Str.size(), E);
1363 }
1364
1365 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00001366
1367 case Builtin::BI__atomic_is_lock_free: {
1368 APSInt SizeVal;
1369 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1370 return false;
1371
1372 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1373 // of two less than the maximum inline atomic width, we know it is
1374 // lock-free. If the size isn't a power of two, or greater than the
1375 // maximum alignment where we promote atomics, we know it is not lock-free
1376 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1377 // the answer can only be determined at runtime; for example, 16-byte
1378 // atomics have lock-free implementations on some, but not all,
1379 // x86-64 processors.
1380
1381 // Check power-of-two.
1382 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1383 if (!Size.isPowerOfTwo())
1384#if 0
1385 // FIXME: Suppress this folding until the ABI for the promotion width
1386 // settles.
1387 return Success(0, E);
1388#else
1389 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1390#endif
1391
1392#if 0
1393 // Check against promotion width.
1394 // FIXME: Suppress this folding until the ABI for the promotion width
1395 // settles.
1396 unsigned PromoteWidthBits =
1397 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1398 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1399 return Success(0, E);
1400#endif
1401
1402 // Check against inlining width.
1403 unsigned InlineWidthBits =
1404 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1405 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1406 return Success(1, E);
1407
1408 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1409 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001410 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001411}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001412
Chris Lattnerb542afe2008-07-11 19:10:17 +00001413bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001414 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00001415 VisitIgnoredValue(E->getLHS());
1416 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00001417 }
1418
1419 if (E->isLogicalOp()) {
1420 // These need to be handled specially because the operands aren't
1421 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001422 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Richard Smith436c8892011-10-24 23:14:33 +00001424 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001425 // We were able to evaluate the LHS, see if we can get away with not
1426 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001427 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001428 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001429
Richard Smith436c8892011-10-24 23:14:33 +00001430 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001431 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001432 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001433 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001434 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001435 }
1436 } else {
Richard Smith436c8892011-10-24 23:14:33 +00001437 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001438 // We can't evaluate the LHS; however, sometimes the result
1439 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001440 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1441 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001442 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001443 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00001444 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001445
1446 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001447 }
1448 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001449 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001450
Eli Friedmana6afa762008-11-13 06:09:17 +00001451 return false;
1452 }
1453
Anders Carlsson286f85e2008-11-16 07:17:21 +00001454 QualType LHSTy = E->getLHS()->getType();
1455 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001456
1457 if (LHSTy->isAnyComplexType()) {
1458 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001459 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001460
1461 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1462 return false;
1463
1464 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1465 return false;
1466
1467 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001468 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001469 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001470 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001471 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1472
John McCall2de56d12010-08-25 11:45:40 +00001473 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001474 return Success((CR_r == APFloat::cmpEqual &&
1475 CR_i == APFloat::cmpEqual), E);
1476 else {
John McCall2de56d12010-08-25 11:45:40 +00001477 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001478 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001479 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001480 CR_r == APFloat::cmpLessThan ||
1481 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001482 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001483 CR_i == APFloat::cmpLessThan ||
1484 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001485 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001486 } else {
John McCall2de56d12010-08-25 11:45:40 +00001487 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001488 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1489 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1490 else {
John McCall2de56d12010-08-25 11:45:40 +00001491 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001492 "Invalid compex comparison.");
1493 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1494 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1495 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001496 }
1497 }
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Anders Carlsson286f85e2008-11-16 07:17:21 +00001499 if (LHSTy->isRealFloatingType() &&
1500 RHSTy->isRealFloatingType()) {
1501 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Anders Carlsson286f85e2008-11-16 07:17:21 +00001503 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1504 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Anders Carlsson286f85e2008-11-16 07:17:21 +00001506 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1507 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Anders Carlsson286f85e2008-11-16 07:17:21 +00001509 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001510
Anders Carlsson286f85e2008-11-16 07:17:21 +00001511 switch (E->getOpcode()) {
1512 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00001513 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001514 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001515 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001516 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001517 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001518 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001519 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001520 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001521 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001522 E);
John McCall2de56d12010-08-25 11:45:40 +00001523 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001524 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001525 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001526 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001527 || CR == APFloat::cmpLessThan
1528 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001529 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001530 }
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001532 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001533 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001534 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001535 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1536 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001537
John McCallefdb83e2010-05-07 21:00:08 +00001538 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001539 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1540 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001541
Eli Friedman5bc86102009-06-14 02:17:33 +00001542 // Reject any bases from the normal codepath; we special-case comparisons
1543 // to null.
1544 if (LHSValue.getLValueBase()) {
1545 if (!E->isEqualityOp())
1546 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001547 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001548 return false;
1549 bool bres;
1550 if (!EvalPointerValueAsBool(LHSValue, bres))
1551 return false;
John McCall2de56d12010-08-25 11:45:40 +00001552 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001553 } else if (RHSValue.getLValueBase()) {
1554 if (!E->isEqualityOp())
1555 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001556 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001557 return false;
1558 bool bres;
1559 if (!EvalPointerValueAsBool(RHSValue, bres))
1560 return false;
John McCall2de56d12010-08-25 11:45:40 +00001561 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001562 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001563
John McCall2de56d12010-08-25 11:45:40 +00001564 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001565 QualType Type = E->getLHS()->getType();
1566 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001567
Ken Dycka7305832010-01-15 12:37:54 +00001568 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001569 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001570 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001571
Ken Dycka7305832010-01-15 12:37:54 +00001572 CharUnits Diff = LHSValue.getLValueOffset() -
1573 RHSValue.getLValueOffset();
1574 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001575 }
1576 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001577 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001578 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001579 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001580 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1581 }
1582 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001583 }
1584 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001585 if (!LHSTy->isIntegralOrEnumerationType() ||
1586 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001587 // We can't continue from here for non-integral types, and they
1588 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001589 return false;
1590 }
1591
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001592 // The LHS of a constant expr is always evaluated and needed.
Richard Smith436c8892011-10-24 23:14:33 +00001593 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001594 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001595
Richard Smith436c8892011-10-24 23:14:33 +00001596 APValue RHSVal;
1597 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001598 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001599
1600 // Handle cases like (unsigned long)&a + 4.
Richard Smith436c8892011-10-24 23:14:33 +00001601 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
1602 CharUnits Offset = Result.getLValueOffset();
Ken Dycka7305832010-01-15 12:37:54 +00001603 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1604 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001605 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001606 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001607 else
Ken Dycka7305832010-01-15 12:37:54 +00001608 Offset -= AdditionalOffset;
Richard Smith436c8892011-10-24 23:14:33 +00001609 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001610 return true;
1611 }
1612
1613 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001614 if (E->getOpcode() == BO_Add &&
Richard Smith436c8892011-10-24 23:14:33 +00001615 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001616 CharUnits Offset = RHSVal.getLValueOffset();
Richard Smith436c8892011-10-24 23:14:33 +00001617 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
Ken Dycka7305832010-01-15 12:37:54 +00001618 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001619 return true;
1620 }
1621
1622 // All the following cases expect both operands to be an integer
Richard Smith436c8892011-10-24 23:14:33 +00001623 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001624 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001625
Richard Smith436c8892011-10-24 23:14:33 +00001626 APSInt& RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00001627
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001628 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001629 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001630 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith436c8892011-10-24 23:14:33 +00001631 case BO_Mul: return Success(Result.getInt() * RHS, E);
1632 case BO_Add: return Success(Result.getInt() + RHS, E);
1633 case BO_Sub: return Success(Result.getInt() - RHS, E);
1634 case BO_And: return Success(Result.getInt() & RHS, E);
1635 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1636 case BO_Or: return Success(Result.getInt() | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001637 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001638 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001639 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith436c8892011-10-24 23:14:33 +00001640 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001641 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001642 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001643 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith436c8892011-10-24 23:14:33 +00001644 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001645 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001646 // During constant-folding, a negative shift is an opposite shift.
1647 if (RHS.isSigned() && RHS.isNegative()) {
1648 RHS = -RHS;
1649 goto shift_right;
1650 }
1651
1652 shift_left:
1653 unsigned SA
Richard Smith436c8892011-10-24 23:14:33 +00001654 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1655 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001656 }
John McCall2de56d12010-08-25 11:45:40 +00001657 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001658 // During constant-folding, a negative shift is an opposite shift.
1659 if (RHS.isSigned() && RHS.isNegative()) {
1660 RHS = -RHS;
1661 goto shift_left;
1662 }
1663
1664 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001665 unsigned SA =
Richard Smith436c8892011-10-24 23:14:33 +00001666 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1667 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001668 }
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Richard Smith436c8892011-10-24 23:14:33 +00001670 case BO_LT: return Success(Result.getInt() < RHS, E);
1671 case BO_GT: return Success(Result.getInt() > RHS, E);
1672 case BO_LE: return Success(Result.getInt() <= RHS, E);
1673 case BO_GE: return Success(Result.getInt() >= RHS, E);
1674 case BO_EQ: return Success(Result.getInt() == RHS, E);
1675 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001676 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001677}
1678
Ken Dyck8b752f12010-01-27 17:10:57 +00001679CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001680 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1681 // the result is the size of the referenced type."
1682 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1683 // result shall be the alignment of the referenced type."
1684 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1685 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00001686
1687 // __alignof is defined to return the preferred alignment.
1688 return Info.Ctx.toCharUnitsFromBits(
1689 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00001690}
1691
Ken Dyck8b752f12010-01-27 17:10:57 +00001692CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001693 E = E->IgnoreParens();
1694
1695 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001696 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001697 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001698 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1699 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001700
Chris Lattneraf707ab2009-01-24 21:53:27 +00001701 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001702 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1703 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001704
Chris Lattnere9feb472009-01-24 21:09:06 +00001705 return GetAlignOfType(E->getType());
1706}
1707
1708
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001709/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1710/// a result as the expression's type.
1711bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1712 const UnaryExprOrTypeTraitExpr *E) {
1713 switch(E->getKind()) {
1714 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00001715 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001716 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001717 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001718 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001719 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001720
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001721 case UETT_VecStep: {
1722 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00001723
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001724 if (Ty->isVectorType()) {
1725 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00001726
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001727 // The vec_step built-in functions that take a 3-component
1728 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1729 if (n == 3)
1730 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001731
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001732 return Success(n, E);
1733 } else
1734 return Success(1, E);
1735 }
1736
1737 case UETT_SizeOf: {
1738 QualType SrcTy = E->getTypeOfArgument();
1739 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1740 // the result is the size of the referenced type."
1741 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1742 // result shall be the alignment of the referenced type."
1743 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1744 SrcTy = Ref->getPointeeType();
1745
1746 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1747 // extension.
1748 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1749 return Success(1, E);
1750
1751 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1752 if (!SrcTy->isConstantSizeType())
1753 return false;
1754
1755 // Get information about the size.
1756 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1757 }
1758 }
1759
1760 llvm_unreachable("unknown expr/type trait");
1761 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001762}
1763
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001764bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001765 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001766 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001767 if (n == 0)
1768 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001769 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001770 for (unsigned i = 0; i != n; ++i) {
1771 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1772 switch (ON.getKind()) {
1773 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001774 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001775 APSInt IdxResult;
1776 if (!EvaluateInteger(Idx, IdxResult, Info))
1777 return false;
1778 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1779 if (!AT)
1780 return false;
1781 CurrentType = AT->getElementType();
1782 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1783 Result += IdxResult.getSExtValue() * ElementSize;
1784 break;
1785 }
1786
1787 case OffsetOfExpr::OffsetOfNode::Field: {
1788 FieldDecl *MemberDecl = ON.getField();
1789 const RecordType *RT = CurrentType->getAs<RecordType>();
1790 if (!RT)
1791 return false;
1792 RecordDecl *RD = RT->getDecl();
1793 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00001794 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001795 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001796 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001797 CurrentType = MemberDecl->getType().getNonReferenceType();
1798 break;
1799 }
1800
1801 case OffsetOfExpr::OffsetOfNode::Identifier:
1802 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001803 return false;
1804
1805 case OffsetOfExpr::OffsetOfNode::Base: {
1806 CXXBaseSpecifier *BaseSpec = ON.getBase();
1807 if (BaseSpec->isVirtual())
1808 return false;
1809
1810 // Find the layout of the class whose base we are looking into.
1811 const RecordType *RT = CurrentType->getAs<RecordType>();
1812 if (!RT)
1813 return false;
1814 RecordDecl *RD = RT->getDecl();
1815 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1816
1817 // Find the base class itself.
1818 CurrentType = BaseSpec->getType();
1819 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1820 if (!BaseRT)
1821 return false;
1822
1823 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00001824 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001825 break;
1826 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001827 }
1828 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001829 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001830}
1831
Chris Lattnerb542afe2008-07-11 19:10:17 +00001832bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001833 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001834 // LNot's operand isn't necessarily an integer, so we handle it specially.
1835 bool bres;
Richard Smith436c8892011-10-24 23:14:33 +00001836 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00001837 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001838 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001839 }
1840
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001841 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001842 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001843 return false;
1844
Chris Lattner87eae5e2008-07-11 22:52:41 +00001845 // Get the operand value into 'Result'.
1846 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001847 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001848
Chris Lattner75a48812008-07-11 22:15:16 +00001849 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001850 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001851 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1852 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001853 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001854 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001855 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1856 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001857 return true;
John McCall2de56d12010-08-25 11:45:40 +00001858 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001859 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001860 return true;
John McCall2de56d12010-08-25 11:45:40 +00001861 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001862 if (!Result.isInt()) return false;
1863 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001864 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001865 if (!Result.isInt()) return false;
1866 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001867 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001868}
Mike Stump1eb44332009-09-09 15:08:12 +00001869
Chris Lattner732b2232008-07-12 01:15:53 +00001870/// HandleCast - This is used to evaluate implicit or explicit casts where the
1871/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001872bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1873 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00001874 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001875 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001876
Eli Friedman46a52322011-03-25 00:43:55 +00001877 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00001878 case CK_BaseToDerived:
1879 case CK_DerivedToBase:
1880 case CK_UncheckedDerivedToBase:
1881 case CK_Dynamic:
1882 case CK_ToUnion:
1883 case CK_ArrayToPointerDecay:
1884 case CK_FunctionToPointerDecay:
1885 case CK_NullToPointer:
1886 case CK_NullToMemberPointer:
1887 case CK_BaseToDerivedMemberPointer:
1888 case CK_DerivedToBaseMemberPointer:
1889 case CK_ConstructorConversion:
1890 case CK_IntegralToPointer:
1891 case CK_ToVoid:
1892 case CK_VectorSplat:
1893 case CK_IntegralToFloating:
1894 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00001895 case CK_CPointerToObjCPointerCast:
1896 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001897 case CK_AnyPointerToBlockPointerCast:
1898 case CK_ObjCObjectLValueCast:
1899 case CK_FloatingRealToComplex:
1900 case CK_FloatingComplexToReal:
1901 case CK_FloatingComplexCast:
1902 case CK_FloatingComplexToIntegralComplex:
1903 case CK_IntegralRealToComplex:
1904 case CK_IntegralComplexCast:
1905 case CK_IntegralComplexToFloatingComplex:
1906 llvm_unreachable("invalid cast kind for integral value");
1907
Eli Friedmane50c2972011-03-25 19:07:11 +00001908 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001909 case CK_Dependent:
1910 case CK_GetObjCProperty:
1911 case CK_LValueBitCast:
1912 case CK_UserDefinedConversion:
John McCall33e56f32011-09-10 06:18:15 +00001913 case CK_ARCProduceObject:
1914 case CK_ARCConsumeObject:
1915 case CK_ARCReclaimReturnedObject:
1916 case CK_ARCExtendBlockObject:
Eli Friedman46a52322011-03-25 00:43:55 +00001917 return false;
1918
1919 case CK_LValueToRValue:
1920 case CK_NoOp:
Richard Smith436c8892011-10-24 23:14:33 +00001921 return Visit(E->getSubExpr());
Eli Friedman46a52322011-03-25 00:43:55 +00001922
1923 case CK_MemberPointerToBoolean:
1924 case CK_PointerToBoolean:
1925 case CK_IntegralToBoolean:
1926 case CK_FloatingToBoolean:
1927 case CK_FloatingComplexToBoolean:
1928 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00001929 bool BoolResult;
Richard Smith436c8892011-10-24 23:14:33 +00001930 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00001931 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001932 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001933 }
1934
Eli Friedman46a52322011-03-25 00:43:55 +00001935 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00001936 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001937 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001938
Eli Friedmanbe265702009-02-20 01:15:07 +00001939 if (!Result.isInt()) {
1940 // Only allow casts of lvalues if they are lossless.
1941 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1942 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001943
Daniel Dunbardd211642009-02-19 22:24:01 +00001944 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001945 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001946 }
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Eli Friedman46a52322011-03-25 00:43:55 +00001948 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00001949 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001950 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001951 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001952
Daniel Dunbardd211642009-02-19 22:24:01 +00001953 if (LV.getLValueBase()) {
1954 // Only allow based lvalue casts if they are lossless.
1955 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1956 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001957
John McCallefdb83e2010-05-07 21:00:08 +00001958 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001959 return true;
1960 }
1961
Ken Dycka7305832010-01-15 12:37:54 +00001962 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1963 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001964 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001965 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001966
Eli Friedman46a52322011-03-25 00:43:55 +00001967 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00001968 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001969 if (!EvaluateComplex(SubExpr, C, Info))
1970 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00001971 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00001972 }
Eli Friedman2217c872009-02-22 11:46:18 +00001973
Eli Friedman46a52322011-03-25 00:43:55 +00001974 case CK_FloatingToIntegral: {
1975 APFloat F(0.0);
1976 if (!EvaluateFloat(SubExpr, F, Info))
1977 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00001978
Eli Friedman46a52322011-03-25 00:43:55 +00001979 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1980 }
1981 }
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Eli Friedman46a52322011-03-25 00:43:55 +00001983 llvm_unreachable("unknown cast resulting in integral value");
1984 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001985}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001986
Eli Friedman722c7172009-02-28 03:59:05 +00001987bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1988 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001989 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001990 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1991 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1992 return Success(LV.getComplexIntReal(), E);
1993 }
1994
1995 return Visit(E->getSubExpr());
1996}
1997
Eli Friedman664a1042009-02-27 04:45:43 +00001998bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001999 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002000 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00002001 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2002 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2003 return Success(LV.getComplexIntImag(), E);
2004 }
2005
Richard Smith8327fad2011-10-24 18:44:57 +00002006 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00002007 return Success(0, E);
2008}
2009
Douglas Gregoree8aff02011-01-04 17:33:58 +00002010bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2011 return Success(E->getPackLength(), E);
2012}
2013
Sebastian Redl295995c2010-09-10 20:55:47 +00002014bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2015 return Success(E->getValue(), E);
2016}
2017
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002018//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002019// Float Evaluation
2020//===----------------------------------------------------------------------===//
2021
2022namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002023class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002024 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002025 APFloat &Result;
2026public:
2027 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002028 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002029
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002030 bool Success(const APValue &V, const Expr *e) {
2031 Result = V.getFloat();
2032 return true;
2033 }
2034 bool Error(const Stmt *S) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002035 return false;
2036 }
2037
Richard Smithf10d9172011-10-11 21:43:33 +00002038 bool ValueInitialization(const Expr *E) {
2039 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2040 return true;
2041 }
2042
Chris Lattner019f4e82008-10-06 05:28:25 +00002043 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002044
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002045 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002046 bool VisitBinaryOperator(const BinaryOperator *E);
2047 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002048 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00002049
John McCallabd3a852010-05-07 22:08:54 +00002050 bool VisitUnaryReal(const UnaryOperator *E);
2051 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002052
Richard Smith436c8892011-10-24 23:14:33 +00002053 bool VisitDeclRefExpr(const DeclRefExpr *E);
2054
John McCallabd3a852010-05-07 22:08:54 +00002055 // FIXME: Missing: array subscript of vector, member of vector,
2056 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002057};
2058} // end anonymous namespace
2059
2060static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith436c8892011-10-24 23:14:33 +00002061 assert(E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002062 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002063}
2064
Jay Foad4ba2a172011-01-12 09:06:06 +00002065static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00002066 QualType ResultTy,
2067 const Expr *Arg,
2068 bool SNaN,
2069 llvm::APFloat &Result) {
2070 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2071 if (!S) return false;
2072
2073 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2074
2075 llvm::APInt fill;
2076
2077 // Treat empty strings as if they were zero.
2078 if (S->getString().empty())
2079 fill = llvm::APInt(32, 0);
2080 else if (S->getString().getAsInteger(0, fill))
2081 return false;
2082
2083 if (SNaN)
2084 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2085 else
2086 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2087 return true;
2088}
2089
Chris Lattner019f4e82008-10-06 05:28:25 +00002090bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00002091 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002092 default:
2093 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2094
Chris Lattner019f4e82008-10-06 05:28:25 +00002095 case Builtin::BI__builtin_huge_val:
2096 case Builtin::BI__builtin_huge_valf:
2097 case Builtin::BI__builtin_huge_vall:
2098 case Builtin::BI__builtin_inf:
2099 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002100 case Builtin::BI__builtin_infl: {
2101 const llvm::fltSemantics &Sem =
2102 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00002103 Result = llvm::APFloat::getInf(Sem);
2104 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002105 }
Mike Stump1eb44332009-09-09 15:08:12 +00002106
John McCalldb7b72a2010-02-28 13:00:19 +00002107 case Builtin::BI__builtin_nans:
2108 case Builtin::BI__builtin_nansf:
2109 case Builtin::BI__builtin_nansl:
2110 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2111 true, Result);
2112
Chris Lattner9e621712008-10-06 06:31:58 +00002113 case Builtin::BI__builtin_nan:
2114 case Builtin::BI__builtin_nanf:
2115 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00002116 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00002117 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00002118 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2119 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002120
2121 case Builtin::BI__builtin_fabs:
2122 case Builtin::BI__builtin_fabsf:
2123 case Builtin::BI__builtin_fabsl:
2124 if (!EvaluateFloat(E->getArg(0), Result, Info))
2125 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002127 if (Result.isNegative())
2128 Result.changeSign();
2129 return true;
2130
Mike Stump1eb44332009-09-09 15:08:12 +00002131 case Builtin::BI__builtin_copysign:
2132 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002133 case Builtin::BI__builtin_copysignl: {
2134 APFloat RHS(0.);
2135 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2136 !EvaluateFloat(E->getArg(1), RHS, Info))
2137 return false;
2138 Result.copySign(RHS);
2139 return true;
2140 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002141 }
2142}
2143
Richard Smith436c8892011-10-24 23:14:33 +00002144bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
2145 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
2146 return true;
2147
2148 const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
2149 if (VD && IsConstNonVolatile(VD->getType())) {
2150 APValue *V = EvaluateVarDeclInit(Info, VD);
2151 if (V && V->isFloat()) {
2152 Result = V->getFloat();
2153 return true;
2154 }
2155 }
2156 return false;
2157}
2158
John McCallabd3a852010-05-07 22:08:54 +00002159bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002160 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2161 ComplexValue CV;
2162 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2163 return false;
2164 Result = CV.FloatReal;
2165 return true;
2166 }
2167
2168 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00002169}
2170
2171bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002172 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2173 ComplexValue CV;
2174 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2175 return false;
2176 Result = CV.FloatImag;
2177 return true;
2178 }
2179
Richard Smith8327fad2011-10-24 18:44:57 +00002180 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00002181 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2182 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00002183 return true;
2184}
2185
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002186bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002187 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00002188 return false;
2189
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002190 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2191 return false;
2192
2193 switch (E->getOpcode()) {
2194 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002195 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002196 return true;
John McCall2de56d12010-08-25 11:45:40 +00002197 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002198 Result.changeSign();
2199 return true;
2200 }
2201}
Chris Lattner019f4e82008-10-06 05:28:25 +00002202
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002203bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002204 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00002205 VisitIgnoredValue(E->getLHS());
2206 return Visit(E->getRHS());
Eli Friedman7f92f032009-11-16 04:25:37 +00002207 }
2208
Anders Carlsson96e93662010-10-31 01:21:47 +00002209 // We can't evaluate pointer-to-member operations.
2210 if (E->isPtrMemOp())
2211 return false;
2212
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002213 // FIXME: Diagnostics? I really don't understand how the warnings
2214 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002215 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002216 if (!EvaluateFloat(E->getLHS(), Result, Info))
2217 return false;
2218 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2219 return false;
2220
2221 switch (E->getOpcode()) {
2222 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002223 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002224 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2225 return true;
John McCall2de56d12010-08-25 11:45:40 +00002226 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002227 Result.add(RHS, APFloat::rmNearestTiesToEven);
2228 return true;
John McCall2de56d12010-08-25 11:45:40 +00002229 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002230 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2231 return true;
John McCall2de56d12010-08-25 11:45:40 +00002232 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002233 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2234 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002235 }
2236}
2237
2238bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2239 Result = E->getValue();
2240 return true;
2241}
2242
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002243bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2244 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Eli Friedman2a523ee2011-03-25 00:54:52 +00002246 switch (E->getCastKind()) {
2247 default:
Richard Smith436c8892011-10-24 23:14:33 +00002248 return false;
2249
2250 case CK_LValueToRValue:
2251 case CK_NoOp:
2252 return Visit(SubExpr);
Eli Friedman2a523ee2011-03-25 00:54:52 +00002253
2254 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002255 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002256 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002257 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002258 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002259 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002260 return true;
2261 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002262
2263 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002264 if (!Visit(SubExpr))
2265 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002266 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2267 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002268 return true;
2269 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002270
Eli Friedman2a523ee2011-03-25 00:54:52 +00002271 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00002272 ComplexValue V;
2273 if (!EvaluateComplex(SubExpr, V, Info))
2274 return false;
2275 Result = V.getComplexFloatReal();
2276 return true;
2277 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002278 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002279
2280 return false;
2281}
2282
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002283//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002284// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002285//===----------------------------------------------------------------------===//
2286
2287namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002288class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002289 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00002290 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002292public:
John McCallf4cf1a12010-05-07 17:22:02 +00002293 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002294 : ExprEvaluatorBaseTy(info), Result(Result) {}
2295
2296 bool Success(const APValue &V, const Expr *e) {
2297 Result.setFrom(V);
2298 return true;
2299 }
2300 bool Error(const Expr *E) {
2301 return false;
2302 }
Mike Stump1eb44332009-09-09 15:08:12 +00002303
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002304 //===--------------------------------------------------------------------===//
2305 // Visitor Methods
2306 //===--------------------------------------------------------------------===//
2307
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002308 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002309
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002310 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002311
John McCallf4cf1a12010-05-07 17:22:02 +00002312 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002313 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00002314 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002315};
2316} // end anonymous namespace
2317
John McCallf4cf1a12010-05-07 17:22:02 +00002318static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2319 EvalInfo &Info) {
Richard Smith436c8892011-10-24 23:14:33 +00002320 assert(E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002321 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002322}
2323
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002324bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2325 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002326
2327 if (SubExpr->getType()->isRealFloatingType()) {
2328 Result.makeComplexFloat();
2329 APFloat &Imag = Result.FloatImag;
2330 if (!EvaluateFloat(SubExpr, Imag, Info))
2331 return false;
2332
2333 Result.FloatReal = APFloat(Imag.getSemantics());
2334 return true;
2335 } else {
2336 assert(SubExpr->getType()->isIntegerType() &&
2337 "Unexpected imaginary literal.");
2338
2339 Result.makeComplexInt();
2340 APSInt &Imag = Result.IntImag;
2341 if (!EvaluateInteger(SubExpr, Imag, Info))
2342 return false;
2343
2344 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2345 return true;
2346 }
2347}
2348
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002349bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002350
John McCall8786da72010-12-14 17:51:41 +00002351 switch (E->getCastKind()) {
2352 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00002353 case CK_BaseToDerived:
2354 case CK_DerivedToBase:
2355 case CK_UncheckedDerivedToBase:
2356 case CK_Dynamic:
2357 case CK_ToUnion:
2358 case CK_ArrayToPointerDecay:
2359 case CK_FunctionToPointerDecay:
2360 case CK_NullToPointer:
2361 case CK_NullToMemberPointer:
2362 case CK_BaseToDerivedMemberPointer:
2363 case CK_DerivedToBaseMemberPointer:
2364 case CK_MemberPointerToBoolean:
2365 case CK_ConstructorConversion:
2366 case CK_IntegralToPointer:
2367 case CK_PointerToIntegral:
2368 case CK_PointerToBoolean:
2369 case CK_ToVoid:
2370 case CK_VectorSplat:
2371 case CK_IntegralCast:
2372 case CK_IntegralToBoolean:
2373 case CK_IntegralToFloating:
2374 case CK_FloatingToIntegral:
2375 case CK_FloatingToBoolean:
2376 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002377 case CK_CPointerToObjCPointerCast:
2378 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00002379 case CK_AnyPointerToBlockPointerCast:
2380 case CK_ObjCObjectLValueCast:
2381 case CK_FloatingComplexToReal:
2382 case CK_FloatingComplexToBoolean:
2383 case CK_IntegralComplexToReal:
2384 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00002385 case CK_ARCProduceObject:
2386 case CK_ARCConsumeObject:
2387 case CK_ARCReclaimReturnedObject:
2388 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00002389 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002390
John McCall8786da72010-12-14 17:51:41 +00002391 case CK_LValueToRValue:
2392 case CK_NoOp:
Richard Smith436c8892011-10-24 23:14:33 +00002393 return Visit(E->getSubExpr());
John McCall8786da72010-12-14 17:51:41 +00002394
2395 case CK_Dependent:
2396 case CK_GetObjCProperty:
Eli Friedman46a52322011-03-25 00:43:55 +00002397 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00002398 case CK_UserDefinedConversion:
2399 return false;
2400
2401 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002402 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002403 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002404 return false;
2405
John McCall8786da72010-12-14 17:51:41 +00002406 Result.makeComplexFloat();
2407 Result.FloatImag = APFloat(Real.getSemantics());
2408 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002409 }
2410
John McCall8786da72010-12-14 17:51:41 +00002411 case CK_FloatingComplexCast: {
2412 if (!Visit(E->getSubExpr()))
2413 return false;
2414
2415 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2416 QualType From
2417 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2418
2419 Result.FloatReal
2420 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2421 Result.FloatImag
2422 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2423 return true;
2424 }
2425
2426 case CK_FloatingComplexToIntegralComplex: {
2427 if (!Visit(E->getSubExpr()))
2428 return false;
2429
2430 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2431 QualType From
2432 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2433 Result.makeComplexInt();
2434 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2435 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2436 return true;
2437 }
2438
2439 case CK_IntegralRealToComplex: {
2440 APSInt &Real = Result.IntReal;
2441 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2442 return false;
2443
2444 Result.makeComplexInt();
2445 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2446 return true;
2447 }
2448
2449 case CK_IntegralComplexCast: {
2450 if (!Visit(E->getSubExpr()))
2451 return false;
2452
2453 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2454 QualType From
2455 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2456
2457 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2458 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2459 return true;
2460 }
2461
2462 case CK_IntegralComplexToFloatingComplex: {
2463 if (!Visit(E->getSubExpr()))
2464 return false;
2465
2466 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2467 QualType From
2468 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2469 Result.makeComplexFloat();
2470 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2471 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2472 return true;
2473 }
2474 }
2475
2476 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002477 return false;
2478}
2479
John McCallf4cf1a12010-05-07 17:22:02 +00002480bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002481 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00002482 VisitIgnoredValue(E->getLHS());
2483 return Visit(E->getRHS());
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002484 }
John McCallf4cf1a12010-05-07 17:22:02 +00002485 if (!Visit(E->getLHS()))
2486 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002487
John McCallf4cf1a12010-05-07 17:22:02 +00002488 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002489 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002490 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002491
Daniel Dunbar3f279872009-01-29 01:32:56 +00002492 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2493 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002494 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002495 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002496 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002497 if (Result.isComplexFloat()) {
2498 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2499 APFloat::rmNearestTiesToEven);
2500 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2501 APFloat::rmNearestTiesToEven);
2502 } else {
2503 Result.getComplexIntReal() += RHS.getComplexIntReal();
2504 Result.getComplexIntImag() += RHS.getComplexIntImag();
2505 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002506 break;
John McCall2de56d12010-08-25 11:45:40 +00002507 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002508 if (Result.isComplexFloat()) {
2509 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2510 APFloat::rmNearestTiesToEven);
2511 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2512 APFloat::rmNearestTiesToEven);
2513 } else {
2514 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2515 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2516 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002517 break;
John McCall2de56d12010-08-25 11:45:40 +00002518 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002519 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002520 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002521 APFloat &LHS_r = LHS.getComplexFloatReal();
2522 APFloat &LHS_i = LHS.getComplexFloatImag();
2523 APFloat &RHS_r = RHS.getComplexFloatReal();
2524 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002525
Daniel Dunbar3f279872009-01-29 01:32:56 +00002526 APFloat Tmp = LHS_r;
2527 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2528 Result.getComplexFloatReal() = Tmp;
2529 Tmp = LHS_i;
2530 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2531 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2532
2533 Tmp = LHS_r;
2534 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2535 Result.getComplexFloatImag() = Tmp;
2536 Tmp = LHS_i;
2537 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2538 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2539 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002540 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002541 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002542 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2543 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002544 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002545 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2546 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2547 }
2548 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002549 case BO_Div:
2550 if (Result.isComplexFloat()) {
2551 ComplexValue LHS = Result;
2552 APFloat &LHS_r = LHS.getComplexFloatReal();
2553 APFloat &LHS_i = LHS.getComplexFloatImag();
2554 APFloat &RHS_r = RHS.getComplexFloatReal();
2555 APFloat &RHS_i = RHS.getComplexFloatImag();
2556 APFloat &Res_r = Result.getComplexFloatReal();
2557 APFloat &Res_i = Result.getComplexFloatImag();
2558
2559 APFloat Den = RHS_r;
2560 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2561 APFloat Tmp = RHS_i;
2562 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2563 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2564
2565 Res_r = LHS_r;
2566 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2567 Tmp = LHS_i;
2568 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2569 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2570 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2571
2572 Res_i = LHS_i;
2573 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2574 Tmp = LHS_r;
2575 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2576 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2577 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2578 } else {
2579 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2580 // FIXME: what about diagnostics?
2581 return false;
2582 }
2583 ComplexValue LHS = Result;
2584 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2585 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2586 Result.getComplexIntReal() =
2587 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2588 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2589 Result.getComplexIntImag() =
2590 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2591 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2592 }
2593 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002594 }
2595
John McCallf4cf1a12010-05-07 17:22:02 +00002596 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002597}
2598
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002599bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2600 // Get the operand value into 'Result'.
2601 if (!Visit(E->getSubExpr()))
2602 return false;
2603
2604 switch (E->getOpcode()) {
2605 default:
2606 // FIXME: what about diagnostics?
2607 return false;
2608 case UO_Extension:
2609 return true;
2610 case UO_Plus:
2611 // The result is always just the subexpr.
2612 return true;
2613 case UO_Minus:
2614 if (Result.isComplexFloat()) {
2615 Result.getComplexFloatReal().changeSign();
2616 Result.getComplexFloatImag().changeSign();
2617 }
2618 else {
2619 Result.getComplexIntReal() = -Result.getComplexIntReal();
2620 Result.getComplexIntImag() = -Result.getComplexIntImag();
2621 }
2622 return true;
2623 case UO_Not:
2624 if (Result.isComplexFloat())
2625 Result.getComplexFloatImag().changeSign();
2626 else
2627 Result.getComplexIntImag() = -Result.getComplexIntImag();
2628 return true;
2629 }
2630}
2631
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002632//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002633// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002634//===----------------------------------------------------------------------===//
2635
Richard Smith1e12c592011-10-16 21:26:27 +00002636static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith436c8892011-10-24 23:14:33 +00002637 if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00002638 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002639 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00002640 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00002641 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002642 return false;
Richard Smith436c8892011-10-24 23:14:33 +00002643 if (Result.isLValue() &&
2644 !IsGlobalLValue(Result.getLValueBase()))
2645 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002646 } else if (E->getType()->hasPointerRepresentation()) {
2647 LValue LV;
2648 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002649 return false;
Richard Smith436c8892011-10-24 23:14:33 +00002650 if (!IsGlobalLValue(LV.Base))
2651 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00002652 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00002653 } else if (E->getType()->isRealFloatingType()) {
2654 llvm::APFloat F(0.0);
2655 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002656 return false;
Richard Smith436c8892011-10-24 23:14:33 +00002657
Richard Smith1e12c592011-10-16 21:26:27 +00002658 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00002659 } else if (E->getType()->isAnyComplexType()) {
2660 ComplexValue C;
2661 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002662 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00002663 C.moveInto(Result);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002664 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002665 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002666
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002667 return true;
2668}
2669
John McCall56ca35d2011-02-17 10:25:35 +00002670/// Evaluate - Return true if this is a constant which we can fold using
2671/// any crazy technique (that has nothing to do with language standards) that
2672/// we want to. If this function returns true, it returns the folded constant
Richard Smith436c8892011-10-24 23:14:33 +00002673/// in Result.
John McCall56ca35d2011-02-17 10:25:35 +00002674bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2675 EvalInfo Info(Ctx, Result);
Richard Smith436c8892011-10-24 23:14:33 +00002676 return ::Evaluate(Result.Val, Info, this);
John McCall56ca35d2011-02-17 10:25:35 +00002677}
2678
Jay Foad4ba2a172011-01-12 09:06:06 +00002679bool Expr::EvaluateAsBooleanCondition(bool &Result,
2680 const ASTContext &Ctx) const {
Richard Smith436c8892011-10-24 23:14:33 +00002681 EvalStatus Scratch;
2682 EvalInfo Info(Ctx, Scratch);
2683
2684 return HandleConversionToBool(this, Result, Info);
John McCallcd7a4452010-01-05 23:42:56 +00002685}
2686
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002687bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith436c8892011-10-24 23:14:33 +00002688 EvalStatus Scratch;
2689 EvalInfo Info(Ctx, Scratch);
2690
2691 return EvaluateInteger(this, Result, Info) && !Scratch.HasSideEffects;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002692}
2693
Jay Foad4ba2a172011-01-12 09:06:06 +00002694bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002695 EvalInfo Info(Ctx, Result);
2696
John McCallefdb83e2010-05-07 21:00:08 +00002697 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002698 if (EvaluateLValue(this, LV, Info) &&
2699 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002700 IsGlobalLValue(LV.Base)) {
2701 LV.moveInto(Result.Val);
2702 return true;
2703 }
2704 return false;
2705}
2706
Jay Foad4ba2a172011-01-12 09:06:06 +00002707bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2708 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002709 EvalInfo Info(Ctx, Result);
2710
2711 LValue LV;
2712 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002713 LV.moveInto(Result.Val);
2714 return true;
2715 }
2716 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002717}
2718
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002719/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002720/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002721bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002722 EvalResult Result;
2723 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002724}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002725
Jay Foad4ba2a172011-01-12 09:06:06 +00002726bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00002727 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002728}
2729
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002730APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002731 EvalResult EvalResult;
2732 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002733 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002734 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002735 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002736
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002737 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002738}
John McCalld905f5a2010-05-07 05:32:02 +00002739
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002740 bool Expr::EvalResult::isGlobalLValue() const {
2741 assert(Val.isLValue());
2742 return IsGlobalLValue(Val.getLValueBase());
2743 }
2744
2745
John McCalld905f5a2010-05-07 05:32:02 +00002746/// isIntegerConstantExpr - this recursive routine will test if an expression is
2747/// an integer constant expression.
2748
2749/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2750/// comma, etc
2751///
2752/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2753/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2754/// cast+dereference.
2755
2756// CheckICE - This function does the fundamental ICE checking: the returned
2757// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2758// Note that to reduce code duplication, this helper does no evaluation
2759// itself; the caller checks whether the expression is evaluatable, and
2760// in the rare cases where CheckICE actually cares about the evaluated
2761// value, it calls into Evalute.
2762//
2763// Meanings of Val:
2764// 0: This expression is an ICE if it can be evaluated by Evaluate.
2765// 1: This expression is not an ICE, but if it isn't evaluated, it's
2766// a legal subexpression for an ICE. This return value is used to handle
2767// the comma operator in C99 mode.
2768// 2: This expression is not an ICE, and is not a legal subexpression for one.
2769
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002770namespace {
2771
John McCalld905f5a2010-05-07 05:32:02 +00002772struct ICEDiag {
2773 unsigned Val;
2774 SourceLocation Loc;
2775
2776 public:
2777 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2778 ICEDiag() : Val(0) {}
2779};
2780
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002781}
2782
2783static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002784
2785static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2786 Expr::EvalResult EVResult;
2787 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2788 !EVResult.Val.isInt()) {
2789 return ICEDiag(2, E->getLocStart());
2790 }
2791 return NoDiag();
2792}
2793
2794static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2795 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002796 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002797 return ICEDiag(2, E->getLocStart());
2798 }
2799
2800 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00002801#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00002802#define STMT(Node, Base) case Expr::Node##Class:
2803#define EXPR(Node, Base)
2804#include "clang/AST/StmtNodes.inc"
2805 case Expr::PredefinedExprClass:
2806 case Expr::FloatingLiteralClass:
2807 case Expr::ImaginaryLiteralClass:
2808 case Expr::StringLiteralClass:
2809 case Expr::ArraySubscriptExprClass:
2810 case Expr::MemberExprClass:
2811 case Expr::CompoundAssignOperatorClass:
2812 case Expr::CompoundLiteralExprClass:
2813 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002814 case Expr::DesignatedInitExprClass:
2815 case Expr::ImplicitValueInitExprClass:
2816 case Expr::ParenListExprClass:
2817 case Expr::VAArgExprClass:
2818 case Expr::AddrLabelExprClass:
2819 case Expr::StmtExprClass:
2820 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00002821 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002822 case Expr::CXXDynamicCastExprClass:
2823 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002824 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002825 case Expr::CXXNullPtrLiteralExprClass:
2826 case Expr::CXXThisExprClass:
2827 case Expr::CXXThrowExprClass:
2828 case Expr::CXXNewExprClass:
2829 case Expr::CXXDeleteExprClass:
2830 case Expr::CXXPseudoDestructorExprClass:
2831 case Expr::UnresolvedLookupExprClass:
2832 case Expr::DependentScopeDeclRefExprClass:
2833 case Expr::CXXConstructExprClass:
2834 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002835 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002836 case Expr::CXXTemporaryObjectExprClass:
2837 case Expr::CXXUnresolvedConstructExprClass:
2838 case Expr::CXXDependentScopeMemberExprClass:
2839 case Expr::UnresolvedMemberExprClass:
2840 case Expr::ObjCStringLiteralClass:
2841 case Expr::ObjCEncodeExprClass:
2842 case Expr::ObjCMessageExprClass:
2843 case Expr::ObjCSelectorExprClass:
2844 case Expr::ObjCProtocolExprClass:
2845 case Expr::ObjCIvarRefExprClass:
2846 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002847 case Expr::ObjCIsaExprClass:
2848 case Expr::ShuffleVectorExprClass:
2849 case Expr::BlockExprClass:
2850 case Expr::BlockDeclRefExprClass:
2851 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002852 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002853 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00002854 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002855 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002856 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00002857 case Expr::MaterializeTemporaryExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00002858 case Expr::AtomicExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002859 return ICEDiag(2, E->getLocStart());
2860
Sebastian Redlcea8d962011-09-24 17:48:14 +00002861 case Expr::InitListExprClass:
2862 if (Ctx.getLangOptions().CPlusPlus0x) {
2863 const InitListExpr *ILE = cast<InitListExpr>(E);
2864 if (ILE->getNumInits() == 0)
2865 return NoDiag();
2866 if (ILE->getNumInits() == 1)
2867 return CheckICE(ILE->getInit(0), Ctx);
2868 // Fall through for more than 1 expression.
2869 }
2870 return ICEDiag(2, E->getLocStart());
2871
Douglas Gregoree8aff02011-01-04 17:33:58 +00002872 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002873 case Expr::GNUNullExprClass:
2874 // GCC considers the GNU __null value to be an integral constant expression.
2875 return NoDiag();
2876
John McCall91a57552011-07-15 05:09:51 +00002877 case Expr::SubstNonTypeTemplateParmExprClass:
2878 return
2879 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
2880
John McCalld905f5a2010-05-07 05:32:02 +00002881 case Expr::ParenExprClass:
2882 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00002883 case Expr::GenericSelectionExprClass:
2884 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002885 case Expr::IntegerLiteralClass:
2886 case Expr::CharacterLiteralClass:
2887 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002888 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002889 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002890 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00002891 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00002892 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002893 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002894 return NoDiag();
2895 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002896 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00002897 // C99 6.6/3 allows function calls within unevaluated subexpressions of
2898 // constant expressions, but they can never be ICEs because an ICE cannot
2899 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00002900 const CallExpr *CE = cast<CallExpr>(E);
2901 if (CE->isBuiltinCall(Ctx))
2902 return CheckEvalInICE(E, Ctx);
2903 return ICEDiag(2, E->getLocStart());
2904 }
2905 case Expr::DeclRefExprClass:
2906 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2907 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00002908 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00002909 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2910
2911 // Parameter variables are never constants. Without this check,
2912 // getAnyInitializer() can find a default argument, which leads
2913 // to chaos.
2914 if (isa<ParmVarDecl>(D))
2915 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2916
2917 // C++ 7.1.5.1p2
2918 // A variable of non-volatile const-qualified integral or enumeration
2919 // type initialized by an ICE can be used in ICEs.
2920 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCalld905f5a2010-05-07 05:32:02 +00002921 // Look for a declaration of this variable that has an initializer.
2922 const VarDecl *ID = 0;
2923 const Expr *Init = Dcl->getAnyInitializer(ID);
2924 if (Init) {
2925 if (ID->isInitKnownICE()) {
2926 // We have already checked whether this subexpression is an
2927 // integral constant expression.
2928 if (ID->isInitICE())
2929 return NoDiag();
2930 else
2931 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2932 }
2933
2934 // It's an ICE whether or not the definition we found is
2935 // out-of-line. See DR 721 and the discussion in Clang PR
2936 // 6206 for details.
2937
2938 if (Dcl->isCheckingICE()) {
2939 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2940 }
2941
2942 Dcl->setCheckingICE();
2943 ICEDiag Result = CheckICE(Init, Ctx);
2944 // Cache the result of the ICE test.
2945 Dcl->setInitKnownICE(Result.Val == 0);
2946 return Result;
2947 }
2948 }
2949 }
2950 return ICEDiag(2, E->getLocStart());
2951 case Expr::UnaryOperatorClass: {
2952 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2953 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002954 case UO_PostInc:
2955 case UO_PostDec:
2956 case UO_PreInc:
2957 case UO_PreDec:
2958 case UO_AddrOf:
2959 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00002960 // C99 6.6/3 allows increment and decrement within unevaluated
2961 // subexpressions of constant expressions, but they can never be ICEs
2962 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00002963 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002964 case UO_Extension:
2965 case UO_LNot:
2966 case UO_Plus:
2967 case UO_Minus:
2968 case UO_Not:
2969 case UO_Real:
2970 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002971 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002972 }
2973
2974 // OffsetOf falls through here.
2975 }
2976 case Expr::OffsetOfExprClass: {
2977 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2978 // Evaluate matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00002979 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00002980 // compliance: we should warn earlier for offsetof expressions with
2981 // array subscripts that aren't ICEs, and if the array subscripts
2982 // are ICEs, the value of the offsetof must be an integer constant.
2983 return CheckEvalInICE(E, Ctx);
2984 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002985 case Expr::UnaryExprOrTypeTraitExprClass: {
2986 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2987 if ((Exp->getKind() == UETT_SizeOf) &&
2988 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00002989 return ICEDiag(2, E->getLocStart());
2990 return NoDiag();
2991 }
2992 case Expr::BinaryOperatorClass: {
2993 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2994 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002995 case BO_PtrMemD:
2996 case BO_PtrMemI:
2997 case BO_Assign:
2998 case BO_MulAssign:
2999 case BO_DivAssign:
3000 case BO_RemAssign:
3001 case BO_AddAssign:
3002 case BO_SubAssign:
3003 case BO_ShlAssign:
3004 case BO_ShrAssign:
3005 case BO_AndAssign:
3006 case BO_XorAssign:
3007 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00003008 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3009 // constant expressions, but they can never be ICEs because an ICE cannot
3010 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00003011 return ICEDiag(2, E->getLocStart());
3012
John McCall2de56d12010-08-25 11:45:40 +00003013 case BO_Mul:
3014 case BO_Div:
3015 case BO_Rem:
3016 case BO_Add:
3017 case BO_Sub:
3018 case BO_Shl:
3019 case BO_Shr:
3020 case BO_LT:
3021 case BO_GT:
3022 case BO_LE:
3023 case BO_GE:
3024 case BO_EQ:
3025 case BO_NE:
3026 case BO_And:
3027 case BO_Xor:
3028 case BO_Or:
3029 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00003030 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3031 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00003032 if (Exp->getOpcode() == BO_Div ||
3033 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00003034 // Evaluate gives an error for undefined Div/Rem, so make sure
3035 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00003036 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003037 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003038 if (REval == 0)
3039 return ICEDiag(1, E->getLocStart());
3040 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003041 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003042 if (LEval.isMinSignedValue())
3043 return ICEDiag(1, E->getLocStart());
3044 }
3045 }
3046 }
John McCall2de56d12010-08-25 11:45:40 +00003047 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00003048 if (Ctx.getLangOptions().C99) {
3049 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3050 // if it isn't evaluated.
3051 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3052 return ICEDiag(1, E->getLocStart());
3053 } else {
3054 // In both C89 and C++, commas in ICEs are illegal.
3055 return ICEDiag(2, E->getLocStart());
3056 }
3057 }
3058 if (LHSResult.Val >= RHSResult.Val)
3059 return LHSResult;
3060 return RHSResult;
3061 }
John McCall2de56d12010-08-25 11:45:40 +00003062 case BO_LAnd:
3063 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00003064 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00003065
3066 // C++0x [expr.const]p2:
3067 // [...] subexpressions of logical AND (5.14), logical OR
3068 // (5.15), and condi- tional (5.16) operations that are not
3069 // evaluated are not considered.
3070 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3071 if (Exp->getOpcode() == BO_LAnd &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003072 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregor63fe6812011-05-24 16:02:01 +00003073 return LHSResult;
3074
3075 if (Exp->getOpcode() == BO_LOr &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003076 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregor63fe6812011-05-24 16:02:01 +00003077 return LHSResult;
3078 }
3079
John McCalld905f5a2010-05-07 05:32:02 +00003080 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3081 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3082 // Rare case where the RHS has a comma "side-effect"; we need
3083 // to actually check the condition to see whether the side
3084 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00003085 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003086 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00003087 return RHSResult;
3088 return NoDiag();
3089 }
3090
3091 if (LHSResult.Val >= RHSResult.Val)
3092 return LHSResult;
3093 return RHSResult;
3094 }
3095 }
3096 }
3097 case Expr::ImplicitCastExprClass:
3098 case Expr::CStyleCastExprClass:
3099 case Expr::CXXFunctionalCastExprClass:
3100 case Expr::CXXStaticCastExprClass:
3101 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00003102 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003103 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00003104 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith98326ed2011-10-25 00:21:54 +00003105 if (isa<ExplicitCastExpr>(E) &&
Richard Smith32cb4712011-10-24 18:26:35 +00003106 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3107 return NoDiag();
Eli Friedmaneea0e812011-09-29 21:49:34 +00003108 switch (cast<CastExpr>(E)->getCastKind()) {
3109 case CK_LValueToRValue:
3110 case CK_NoOp:
3111 case CK_IntegralToBoolean:
3112 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00003113 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00003114 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00003115 return ICEDiag(2, E->getLocStart());
3116 }
John McCalld905f5a2010-05-07 05:32:02 +00003117 }
John McCall56ca35d2011-02-17 10:25:35 +00003118 case Expr::BinaryConditionalOperatorClass: {
3119 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3120 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3121 if (CommonResult.Val == 2) return CommonResult;
3122 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3123 if (FalseResult.Val == 2) return FalseResult;
3124 if (CommonResult.Val == 1) return CommonResult;
3125 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003126 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00003127 return FalseResult;
3128 }
John McCalld905f5a2010-05-07 05:32:02 +00003129 case Expr::ConditionalOperatorClass: {
3130 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3131 // If the condition (ignoring parens) is a __builtin_constant_p call,
3132 // then only the true side is actually considered in an integer constant
3133 // expression, and it is fully evaluated. This is an important GNU
3134 // extension. See GCC PR38377 for discussion.
3135 if (const CallExpr *CallCE
3136 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3137 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3138 Expr::EvalResult EVResult;
3139 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3140 !EVResult.Val.isInt()) {
3141 return ICEDiag(2, E->getLocStart());
3142 }
3143 return NoDiag();
3144 }
3145 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003146 if (CondResult.Val == 2)
3147 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00003148
3149 // C++0x [expr.const]p2:
3150 // subexpressions of [...] conditional (5.16) operations that
3151 // are not evaluated are not considered
3152 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003153 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregor63fe6812011-05-24 16:02:01 +00003154 : false;
3155 ICEDiag TrueResult = NoDiag();
3156 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3157 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3158 ICEDiag FalseResult = NoDiag();
3159 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3160 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3161
John McCalld905f5a2010-05-07 05:32:02 +00003162 if (TrueResult.Val == 2)
3163 return TrueResult;
3164 if (FalseResult.Val == 2)
3165 return FalseResult;
3166 if (CondResult.Val == 1)
3167 return CondResult;
3168 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3169 return NoDiag();
3170 // Rare case where the diagnostics depend on which side is evaluated
3171 // Note that if we get here, CondResult is 0, and at least one of
3172 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003173 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00003174 return FalseResult;
3175 }
3176 return TrueResult;
3177 }
3178 case Expr::CXXDefaultArgExprClass:
3179 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3180 case Expr::ChooseExprClass: {
3181 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3182 }
3183 }
3184
3185 // Silence a GCC warning
3186 return ICEDiag(2, E->getLocStart());
3187}
3188
3189bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3190 SourceLocation *Loc, bool isEvaluated) const {
3191 ICEDiag d = CheckICE(this, Ctx);
3192 if (d.Val != 0) {
3193 if (Loc) *Loc = d.Loc;
3194 return false;
3195 }
Richard Smith436c8892011-10-24 23:14:33 +00003196 EvalResult EvalResult;
3197 if (!Evaluate(EvalResult, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00003198 llvm_unreachable("ICE cannot be evaluated!");
Richard Smith436c8892011-10-24 23:14:33 +00003199 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3200 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3201 Result = EvalResult.Val.getInt();
John McCalld905f5a2010-05-07 05:32:02 +00003202 return true;
3203}