blob: 98fe07f1b68c8b16666b1aecb0f21dc238da3edc [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 Smith41bf4f32011-10-24 21:07:08 +0000154static bool EvalPointerValueAsBool(const 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 Smith41bf4f32011-10-24 21:07:08 +0000186static bool HandleConversionToBool(const APValue &Val, bool &Result) {
187 switch (Val.getKind()) {
188 case APValue::Uninitialized:
189 return false;
190 case APValue::Int:
191 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +0000192 return true;
Richard Smith41bf4f32011-10-24 21:07:08 +0000193 case APValue::Float:
194 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +0000195 return true;
Richard Smith41bf4f32011-10-24 21:07:08 +0000196 case APValue::ComplexInt:
197 Result = Val.getComplexIntReal().getBoolValue() ||
198 Val.getComplexIntImag().getBoolValue();
199 return true;
200 case APValue::ComplexFloat:
201 Result = !Val.getComplexFloatReal().isZero() ||
202 !Val.getComplexFloatImag().isZero();
203 return true;
204 case APValue::LValue:
205 {
206 LValue PointerResult;
207 PointerResult.setFrom(Val);
208 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedmana1f47c42009-03-23 04:38:34 +0000209 }
Richard Smith41bf4f32011-10-24 21:07:08 +0000210 case APValue::Vector:
211 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000212 }
213
Richard Smith41bf4f32011-10-24 21:07:08 +0000214 llvm_unreachable("unknown APValue kind");
215}
216
217static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
218 EvalInfo &Info) {
219 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
220 APValue Val;
221 if (!Evaluate(Val, Info, E))
222 return false;
223 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +0000224}
225
Mike Stump1eb44332009-09-09 15:08:12 +0000226static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000227 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000228 unsigned DestWidth = Ctx.getIntWidth(DestType);
229 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000230 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000232 // FIXME: Warning for overflow.
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000233 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000234 bool ignored;
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000235 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
236 return Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000237}
238
Mike Stump1eb44332009-09-09 15:08:12 +0000239static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000240 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000241 bool ignored;
242 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000243 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000244 APFloat::rmNearestTiesToEven, &ignored);
245 return Result;
246}
247
Mike Stump1eb44332009-09-09 15:08:12 +0000248static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000249 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000250 unsigned DestWidth = Ctx.getIntWidth(DestType);
251 APSInt Result = Value;
252 // Figure out if this is a truncate, extend or noop cast.
253 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000254 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000255 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000256 return Result;
257}
258
Mike Stump1eb44332009-09-09 15:08:12 +0000259static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000260 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000261
262 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
263 Result.convertFromAPInt(Value, Value.isSigned(),
264 APFloat::rmNearestTiesToEven);
265 return Result;
266}
267
Richard Smith03f96112011-10-24 17:54:18 +0000268/// Try to evaluate the initializer for a variable declaration.
269static APValue *EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD) {
270 if (isa<ParmVarDecl>(VD))
271 return 0;
272
273 const Expr *Init = VD->getAnyInitializer();
274 if (!Init)
275 return 0;
276
277 if (APValue *V = VD->getEvaluatedValue())
278 return V;
279
280 if (VD->isEvaluatingValue())
281 return 0;
282
283 VD->setEvaluatingValue();
284
Richard Smith03f96112011-10-24 17:54:18 +0000285 Expr::EvalResult EResult;
Richard Smith41bf4f32011-10-24 21:07:08 +0000286 EvalInfo InitInfo(Info.Ctx, EResult);
287 // FIXME: The caller will need to know whether the value was a constant
288 // expression. If not, we should propagate up a diagnostic.
289 if (Evaluate(EResult.Val, InitInfo, Init))
Richard Smith03f96112011-10-24 17:54:18 +0000290 VD->setEvaluatedValue(EResult.Val);
291 else
292 VD->setEvaluatedValue(APValue());
293
294 return VD->getEvaluatedValue();
295}
296
297bool IsConstNonVolatile(QualType T) {
298 Qualifiers Quals = T.getQualifiers();
299 return Quals.hasConst() && !Quals.hasVolatile();
300}
301
Richard Smith41bf4f32011-10-24 21:07:08 +0000302bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
303 const LValue &LValue, APValue &RValue) {
304 const Expr *Base = LValue.Base;
305
306 // FIXME: Indirection through a null pointer deserves a diagnostic.
307 if (!Base)
308 return false;
309
310 // FIXME: Support accessing subobjects of objects of literal types. A simple
311 // byte offset is insufficient for C++11 semantics: we need to know how the
312 // reference was formed (which union member was named, for instance).
313 // FIXME: Support subobjects of StringLiteral and PredefinedExpr.
314 if (!LValue.Offset.isZero())
315 return false;
316
317 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
318 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
319 // In C, they can also be folded, although they are not ICEs.
320 // In C++0x, constexpr variables are constant expressions too.
321 // We allow folding any const variable of literal type initialized with
322 // a constant expression.
323 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
324 if (VD && IsConstNonVolatile(VD->getType()) && Type->isLiteralType()) {
325 APValue *V = EvaluateVarDeclInit(Info, VD);
326 if (V && !V->isUninit()) {
327 RValue = *V;
328 return true;
329 }
330 }
331 return false;
332 }
333
334 // FIXME: C++11: Support MaterializeTemporaryExpr in LValueExprEvaluator and
335 // here.
336
337 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
338 // initializer until now for such expressions. Such an expression can't be
339 // an ICE in C, so this only matters for fold.
340 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
341 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
342 return Evaluate(RValue, Info, CLE->getInitializer());
343 }
344
345 return false;
346}
347
Mike Stumpc4c90452009-10-27 22:09:17 +0000348namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000349class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000350 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +0000351 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +0000352public:
353
Richard Smith1e12c592011-10-16 21:26:27 +0000354 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +0000355
356 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000357 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +0000358 return true;
359 }
360
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000361 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
362 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +0000363 return Visit(E->getResultExpr());
364 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000365 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +0000366 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000367 return true;
368 return false;
369 }
John McCallf85e1932011-06-15 23:02:42 +0000370 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +0000371 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +0000372 return true;
373 return false;
374 }
375 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +0000376 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +0000377 return true;
378 return false;
379 }
380
Mike Stumpc4c90452009-10-27 22:09:17 +0000381 // We don't want to evaluate BlockExprs multiple times, as they generate
382 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000383 bool VisitBlockExpr(const BlockExpr *E) { return true; }
384 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
385 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +0000386 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000387 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
388 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
389 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
390 bool VisitStringLiteral(const StringLiteral *E) { return false; }
391 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
392 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000393 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000394 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000395 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000396 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +0000397 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000398 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
399 bool VisitBinAssign(const BinaryOperator *E) { return true; }
400 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
401 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +0000402 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000403 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
404 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
405 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
406 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
407 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +0000408 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000409 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000410 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000411 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000412 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000413
414 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000415 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +0000416 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
417 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000418 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000419 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +0000420 return false;
421 }
Douglas Gregoree8aff02011-01-04 17:33:58 +0000422
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000423 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000424};
425
John McCall56ca35d2011-02-17 10:25:35 +0000426class OpaqueValueEvaluation {
427 EvalInfo &info;
428 OpaqueValueExpr *opaqueValue;
429
430public:
431 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
432 Expr *value)
433 : info(info), opaqueValue(opaqueValue) {
434
435 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +0000436 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +0000437 this->opaqueValue = 0;
438 return;
439 }
John McCall56ca35d2011-02-17 10:25:35 +0000440 }
441
442 bool hasError() const { return opaqueValue == 0; }
443
444 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +0000445 // FIXME: This will not work for recursive constexpr functions using opaque
446 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +0000447 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
448 }
449};
450
Mike Stumpc4c90452009-10-27 22:09:17 +0000451} // end anonymous namespace
452
Eli Friedman4efaa272008-11-12 09:44:48 +0000453//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000454// Generic Evaluation
455//===----------------------------------------------------------------------===//
456namespace {
457
458template <class Derived, typename RetTy=void>
459class ExprEvaluatorBase
460 : public ConstStmtVisitor<Derived, RetTy> {
461private:
462 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
463 return static_cast<Derived*>(this)->Success(V, E);
464 }
465 RetTy DerivedError(const Expr *E) {
466 return static_cast<Derived*>(this)->Error(E);
467 }
Richard Smithf10d9172011-10-11 21:43:33 +0000468 RetTy DerivedValueInitialization(const Expr *E) {
469 return static_cast<Derived*>(this)->ValueInitialization(E);
470 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000471
472protected:
473 EvalInfo &Info;
474 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
475 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
476
Richard Smithf10d9172011-10-11 21:43:33 +0000477 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
478
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000479public:
480 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
481
482 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000483 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000484 }
485 RetTy VisitExpr(const Expr *E) {
486 return DerivedError(E);
487 }
488
489 RetTy VisitParenExpr(const ParenExpr *E)
490 { return StmtVisitorTy::Visit(E->getSubExpr()); }
491 RetTy VisitUnaryExtension(const UnaryOperator *E)
492 { return StmtVisitorTy::Visit(E->getSubExpr()); }
493 RetTy VisitUnaryPlus(const UnaryOperator *E)
494 { return StmtVisitorTy::Visit(E->getSubExpr()); }
495 RetTy VisitChooseExpr(const ChooseExpr *E)
496 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
497 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
498 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +0000499 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
500 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000501
502 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
503 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
504 if (opaque.hasError())
505 return DerivedError(E);
506
507 bool cond;
Richard Smith41bf4f32011-10-24 21:07:08 +0000508 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000509 return DerivedError(E);
510
511 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
512 }
513
514 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
515 bool BoolResult;
Richard Smith41bf4f32011-10-24 21:07:08 +0000516 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000517 return DerivedError(E);
518
Richard Smith41bf4f32011-10-24 21:07:08 +0000519 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000520 return StmtVisitorTy::Visit(EvalExpr);
521 }
522
523 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
524 const APValue *value = Info.getOpaqueValue(E);
525 if (!value)
526 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
527 : DerivedError(E));
528 return DerivedSuccess(*value, E);
529 }
Richard Smithf10d9172011-10-11 21:43:33 +0000530
Richard Smith41bf4f32011-10-24 21:07:08 +0000531 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
532 return StmtVisitorTy::Visit(E->getInitializer());
533 }
Richard Smithf10d9172011-10-11 21:43:33 +0000534 RetTy VisitInitListExpr(const InitListExpr *E) {
535 if (Info.getLangOpts().CPlusPlus0x) {
536 if (E->getNumInits() == 0)
537 return DerivedValueInitialization(E);
538 if (E->getNumInits() == 1)
539 return StmtVisitorTy::Visit(E->getInit(0));
540 }
541 return DerivedError(E);
542 }
543 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
544 return DerivedValueInitialization(E);
545 }
546 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
547 return DerivedValueInitialization(E);
548 }
549
Richard Smith41bf4f32011-10-24 21:07:08 +0000550 RetTy VisitCastExpr(const CastExpr *E) {
551 switch (E->getCastKind()) {
552 default:
553 break;
554
555 case CK_NoOp:
556 return StmtVisitorTy::Visit(E->getSubExpr());
557
558 case CK_LValueToRValue: {
559 LValue LVal;
560 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
561 APValue RVal;
562 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
563 return DerivedSuccess(RVal, E);
564 }
565 break;
566 }
567 }
568
569 return DerivedError(E);
570 }
571
Richard Smith8327fad2011-10-24 18:44:57 +0000572 /// Visit a value which is evaluated, but whose value is ignored.
573 void VisitIgnoredValue(const Expr *E) {
574 APValue Scratch;
575 if (!Evaluate(Scratch, Info, E))
576 Info.EvalStatus.HasSideEffects = true;
577 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000578};
579
580}
581
582//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000583// LValue Evaluation
Richard Smith41bf4f32011-10-24 21:07:08 +0000584//
585// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
586// function designators (in C), decl references to void objects (in C), and
587// temporaries (if building with -Wno-address-of-temporary).
Eli Friedman4efaa272008-11-12 09:44:48 +0000588//===----------------------------------------------------------------------===//
589namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000590class LValueExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000591 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000592 LValue &Result;
Chandler Carruth01248392011-08-22 17:24:56 +0000593 const Decl *PrevDecl;
John McCallefdb83e2010-05-07 21:00:08 +0000594
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000595 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000596 Result.Base = E;
597 Result.Offset = CharUnits::Zero();
598 return true;
599 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000600public:
Mike Stump1eb44332009-09-09 15:08:12 +0000601
John McCallefdb83e2010-05-07 21:00:08 +0000602 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth01248392011-08-22 17:24:56 +0000603 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000604
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000605 bool Success(const APValue &V, const Expr *E) {
606 Result.setFrom(V);
607 return true;
608 }
609 bool Error(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000610 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000611 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000612
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000613 bool VisitDeclRefExpr(const DeclRefExpr *E);
614 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
615 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
616 bool VisitMemberExpr(const MemberExpr *E);
617 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
618 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
619 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
620 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +0000621
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000622 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000623 switch (E->getCastKind()) {
624 default:
Richard Smith41bf4f32011-10-24 21:07:08 +0000625 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +0000626
Eli Friedmandb924222011-10-11 00:13:24 +0000627 case CK_LValueBitCast:
Anders Carlsson26bc2202009-10-03 16:30:22 +0000628 return Visit(E->getSubExpr());
Eli Friedmandb924222011-10-11 00:13:24 +0000629
Richard Smith41bf4f32011-10-24 21:07:08 +0000630 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
631 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlsson26bc2202009-10-03 16:30:22 +0000632 }
633 }
Sebastian Redlcea8d962011-09-24 17:48:14 +0000634
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000635 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000636
Eli Friedman4efaa272008-11-12 09:44:48 +0000637};
638} // end anonymous namespace
639
Richard Smith41bf4f32011-10-24 21:07:08 +0000640/// Evaluate an expression as an lvalue. This can be legitimately called on
641/// expressions which are not glvalues, in a few cases:
642/// * function designators in C,
643/// * "extern void" objects,
644/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +0000645static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000646 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000647}
648
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000649bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000650 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000651 return Success(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000652 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000653 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000654 return Success(E);
Chandler Carruth761c94e2010-05-16 09:32:51 +0000655 // Reference parameters can refer to anything even if they have an
656 // "initializer" in the form of a default argument.
Chandler Carruth01248392011-08-22 17:24:56 +0000657 if (!isa<ParmVarDecl>(VD)) {
Richard Smith41bf4f32011-10-24 21:07:08 +0000658 APValue *V = EvaluateVarDeclInit(Info, VD);
659 if (V && !V->isUninit()) {
660 assert(V->isLValue() && "reference init not glvalue");
661 Result.Base = V->getLValueBase();
662 Result.Offset = V->getLValueOffset();
663 return true;
664 }
Chandler Carruth01248392011-08-22 17:24:56 +0000665 }
Eli Friedman50c39ea2009-05-27 06:04:58 +0000666 }
667
Richard Smith41bf4f32011-10-24 21:07:08 +0000668 return Error(E);
Anders Carlsson35873c42008-11-24 04:41:22 +0000669}
670
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000671bool
672LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith41bf4f32011-10-24 21:07:08 +0000673 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
674 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
675 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +0000676 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000677}
678
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000679bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000680 QualType Ty;
681 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000682 if (!EvaluatePointer(E->getBase(), Result, Info))
683 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000684 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000685 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000686 if (!Visit(E->getBase()))
687 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000688 Ty = E->getBase()->getType();
689 }
690
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000691 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000692 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000693
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000694 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor86f19402008-12-20 23:49:58 +0000695 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000696 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000697
698 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000699 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000700
Eli Friedman82905742011-07-07 01:54:01 +0000701 unsigned i = FD->getFieldIndex();
Ken Dyckfb1e3bc2011-01-18 01:56:16 +0000702 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCallefdb83e2010-05-07 21:00:08 +0000703 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000704}
705
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000706bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith41bf4f32011-10-24 21:07:08 +0000707 // FIXME: Deal with vectors as array subscript bases.
708 if (E->getBase()->getType()->isVectorType())
709 return false;
710
Anders Carlsson3068d112008-11-16 19:01:22 +0000711 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000712 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Anders Carlsson3068d112008-11-16 19:01:22 +0000714 APSInt Index;
715 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000716 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000717
Ken Dyck199c3d62010-01-11 17:06:35 +0000718 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000719 Result.Offset += Index.getSExtValue() * ElementSize;
720 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000721}
Eli Friedman4efaa272008-11-12 09:44:48 +0000722
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000723bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000724 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000725}
726
Eli Friedman4efaa272008-11-12 09:44:48 +0000727//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000728// Pointer Evaluation
729//===----------------------------------------------------------------------===//
730
Anders Carlssonc754aa62008-07-08 05:13:58 +0000731namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000732class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000733 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000734 LValue &Result;
735
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000736 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000737 Result.Base = E;
738 Result.Offset = CharUnits::Zero();
739 return true;
740 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000741public:
Mike Stump1eb44332009-09-09 15:08:12 +0000742
John McCallefdb83e2010-05-07 21:00:08 +0000743 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000744 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000745
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000746 bool Success(const APValue &V, const Expr *E) {
747 Result.setFrom(V);
748 return true;
749 }
750 bool Error(const Stmt *S) {
John McCallefdb83e2010-05-07 21:00:08 +0000751 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000752 }
Richard Smithf10d9172011-10-11 21:43:33 +0000753 bool ValueInitialization(const Expr *E) {
754 return Success((Expr*)0);
755 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000756
John McCallefdb83e2010-05-07 21:00:08 +0000757 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000758 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +0000759 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000760 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +0000761 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000762 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000763 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000764 bool VisitCallExpr(const CallExpr *E);
765 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +0000766 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +0000767 return Success(E);
768 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000769 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000770 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smithf10d9172011-10-11 21:43:33 +0000771 { return ValueInitialization(E); }
John McCall56ca35d2011-02-17 10:25:35 +0000772
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000773 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000774};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000775} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000776
John McCallefdb83e2010-05-07 21:00:08 +0000777static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith41bf4f32011-10-24 21:07:08 +0000778 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000779 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000780}
781
John McCallefdb83e2010-05-07 21:00:08 +0000782bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000783 if (E->getOpcode() != BO_Add &&
784 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000785 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000787 const Expr *PExp = E->getLHS();
788 const Expr *IExp = E->getRHS();
789 if (IExp->getType()->isPointerType())
790 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000791
John McCallefdb83e2010-05-07 21:00:08 +0000792 if (!EvaluatePointer(PExp, Result, Info))
793 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000794
John McCallefdb83e2010-05-07 21:00:08 +0000795 llvm::APSInt Offset;
796 if (!EvaluateInteger(IExp, Offset, Info))
797 return false;
798 int64_t AdditionalOffset
799 = Offset.isSigned() ? Offset.getSExtValue()
800 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000801
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000802 // Compute the new offset in the appropriate width.
803
804 QualType PointeeType =
805 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000806 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000808 // Explicitly handle GNU void* and function pointer arithmetic extensions.
809 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000810 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000811 else
John McCallefdb83e2010-05-07 21:00:08 +0000812 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000813
John McCall2de56d12010-08-25 11:45:40 +0000814 if (E->getOpcode() == BO_Add)
John McCallefdb83e2010-05-07 21:00:08 +0000815 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000816 else
John McCallefdb83e2010-05-07 21:00:08 +0000817 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000818
John McCallefdb83e2010-05-07 21:00:08 +0000819 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000820}
Eli Friedman4efaa272008-11-12 09:44:48 +0000821
John McCallefdb83e2010-05-07 21:00:08 +0000822bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
823 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000824}
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000826
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000827bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
828 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000829
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000830 switch (E->getCastKind()) {
831 default:
832 break;
833
John McCall2de56d12010-08-25 11:45:40 +0000834 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +0000835 case CK_CPointerToObjCPointerCast:
836 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +0000837 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000838 return Visit(SubExpr);
839
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000840 case CK_DerivedToBase:
841 case CK_UncheckedDerivedToBase: {
842 LValue BaseLV;
843 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
844 return false;
845
846 // Now figure out the necessary offset to add to the baseLV to get from
847 // the derived class to the base class.
Ken Dyck7c7f8202011-01-26 02:17:08 +0000848 CharUnits Offset = CharUnits::Zero();
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000849
850 QualType Ty = E->getSubExpr()->getType();
851 const CXXRecordDecl *DerivedDecl =
852 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
853
854 for (CastExpr::path_const_iterator PathI = E->path_begin(),
855 PathE = E->path_end(); PathI != PathE; ++PathI) {
856 const CXXBaseSpecifier *Base = *PathI;
857
858 // FIXME: If the base is virtual, we'd need to determine the type of the
859 // most derived class and we don't support that right now.
860 if (Base->isVirtual())
861 return false;
862
863 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
864 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
865
Ken Dyck7c7f8202011-01-26 02:17:08 +0000866 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000867 DerivedDecl = BaseDecl;
868 }
869
870 Result.Base = BaseLV.getLValueBase();
Ken Dyck7c7f8202011-01-26 02:17:08 +0000871 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000872 return true;
873 }
874
John McCall404cd162010-11-13 01:35:44 +0000875 case CK_NullToPointer: {
876 Result.Base = 0;
877 Result.Offset = CharUnits::Zero();
878 return true;
879 }
880
John McCall2de56d12010-08-25 11:45:40 +0000881 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000882 APValue Value;
883 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000884 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000885
John McCallefdb83e2010-05-07 21:00:08 +0000886 if (Value.isInt()) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000887 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCallefdb83e2010-05-07 21:00:08 +0000888 Result.Base = 0;
889 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
890 return true;
891 } else {
892 // Cast is of an lvalue, no need to change value.
893 Result.Base = Value.getLValueBase();
894 Result.Offset = Value.getLValueOffset();
895 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000896 }
897 }
John McCall2de56d12010-08-25 11:45:40 +0000898 case CK_ArrayToPointerDecay:
899 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000900 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000901 }
902
Richard Smith41bf4f32011-10-24 21:07:08 +0000903 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000904}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000905
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000906bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000907 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000908 Builtin::BI__builtin___CFStringMakeConstantString ||
909 E->isBuiltinCall(Info.Ctx) ==
910 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000911 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +0000912
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000913 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000914}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000915
916//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000917// Vector Evaluation
918//===----------------------------------------------------------------------===//
919
920namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000921 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +0000922 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
923 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +0000924 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Richard Smith07fc6572011-10-22 21:10:00 +0000926 VectorExprEvaluator(EvalInfo &info, APValue &Result)
927 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Richard Smith07fc6572011-10-22 21:10:00 +0000929 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
930 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
931 // FIXME: remove this APValue copy.
932 Result = APValue(V.data(), V.size());
933 return true;
934 }
935 bool Success(const APValue &V, const Expr *E) {
936 Result = V;
937 return true;
938 }
939 bool Error(const Expr *E) { return false; }
940 bool ValueInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Richard Smith07fc6572011-10-22 21:10:00 +0000942 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +0000943 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +0000944 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +0000945 bool VisitInitListExpr(const InitListExpr *E);
946 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000947 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000948 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000949 // shufflevector, ExtVectorElementExpr
950 // (Note that these require implementing conversions
951 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000952 };
953} // end anonymous namespace
954
955static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith41bf4f32011-10-24 21:07:08 +0000956 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +0000957 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +0000958}
959
Richard Smith07fc6572011-10-22 21:10:00 +0000960bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
961 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000962 QualType EltTy = VTy->getElementType();
963 unsigned NElts = VTy->getNumElements();
964 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Nate Begeman59b5da62009-01-18 03:20:47 +0000966 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000967 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +0000968
Eli Friedman46a52322011-03-25 00:43:55 +0000969 switch (E->getCastKind()) {
970 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +0000971 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000972 if (SETy->isIntegerType()) {
973 APSInt IntResult;
974 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith07fc6572011-10-22 21:10:00 +0000975 return Error(E);
976 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +0000977 } else if (SETy->isRealFloatingType()) {
978 APFloat F(0.0);
979 if (!EvaluateFloat(SE, F, Info))
Richard Smith07fc6572011-10-22 21:10:00 +0000980 return Error(E);
981 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +0000982 } else {
Richard Smith07fc6572011-10-22 21:10:00 +0000983 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +0000984 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000985
986 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +0000987 SmallVector<APValue, 4> Elts(NElts, Val);
988 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +0000989 }
Eli Friedman46a52322011-03-25 00:43:55 +0000990 case CK_BitCast: {
Richard Smith07fc6572011-10-22 21:10:00 +0000991 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedman46a52322011-03-25 00:43:55 +0000992 if (SETy->isVectorType())
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000993 return Visit(SE);
Nate Begemanc0b8b192009-07-01 07:50:47 +0000994
Eli Friedman46a52322011-03-25 00:43:55 +0000995 if (!SETy->isIntegerType())
Richard Smith07fc6572011-10-22 21:10:00 +0000996 return Error(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Eli Friedman46a52322011-03-25 00:43:55 +0000998 APSInt Init;
999 if (!EvaluateInteger(SE, Init, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00001000 return Error(E);
Nate Begemanc0b8b192009-07-01 07:50:47 +00001001
Eli Friedman46a52322011-03-25 00:43:55 +00001002 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1003 "Vectors must be composed of ints or floats");
1004
Chris Lattner5f9e2722011-07-23 10:55:15 +00001005 SmallVector<APValue, 4> Elts;
Eli Friedman46a52322011-03-25 00:43:55 +00001006 for (unsigned i = 0; i != NElts; ++i) {
1007 APSInt Tmp = Init.extOrTrunc(EltWidth);
1008
1009 if (EltTy->isIntegerType())
1010 Elts.push_back(APValue(Tmp));
1011 else
1012 Elts.push_back(APValue(APFloat(Tmp)));
1013
1014 Init >>= EltWidth;
1015 }
Richard Smith07fc6572011-10-22 21:10:00 +00001016 return Success(Elts, E);
Nate Begemanc0b8b192009-07-01 07:50:47 +00001017 }
Eli Friedman46a52322011-03-25 00:43:55 +00001018 default:
Richard Smith41bf4f32011-10-24 21:07:08 +00001019 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00001020 }
Nate Begeman59b5da62009-01-18 03:20:47 +00001021}
1022
Richard Smith07fc6572011-10-22 21:10:00 +00001023bool
Nate Begeman59b5da62009-01-18 03:20:47 +00001024VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00001025 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00001026 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00001027 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Nate Begeman59b5da62009-01-18 03:20:47 +00001029 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001030 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00001031
John McCalla7d6c222010-06-11 17:54:15 +00001032 // If a vector is initialized with a single element, that value
1033 // becomes every element of the vector, not just the first.
1034 // This is the behavior described in the IBM AltiVec documentation.
1035 if (NumInits == 1) {
Richard Smith07fc6572011-10-22 21:10:00 +00001036
1037 // Handle the case where the vector is initialized by another
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +00001038 // vector (OpenCL 6.1.6).
1039 if (E->getInit(0)->getType()->isVectorType())
Richard Smith07fc6572011-10-22 21:10:00 +00001040 return Visit(E->getInit(0));
1041
John McCalla7d6c222010-06-11 17:54:15 +00001042 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +00001043 if (EltTy->isIntegerType()) {
1044 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +00001045 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00001046 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00001047 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +00001048 } else {
1049 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +00001050 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00001051 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00001052 InitValue = APValue(f);
1053 }
1054 for (unsigned i = 0; i < NumElements; i++) {
1055 Elements.push_back(InitValue);
1056 }
1057 } else {
1058 for (unsigned i = 0; i < NumElements; i++) {
1059 if (EltTy->isIntegerType()) {
1060 llvm::APSInt sInt(32);
1061 if (i < NumInits) {
1062 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00001063 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00001064 } else {
1065 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1066 }
1067 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +00001068 } else {
John McCalla7d6c222010-06-11 17:54:15 +00001069 llvm::APFloat f(0.0);
1070 if (i < NumInits) {
1071 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00001072 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00001073 } else {
1074 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1075 }
1076 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +00001077 }
Nate Begeman59b5da62009-01-18 03:20:47 +00001078 }
1079 }
Richard Smith07fc6572011-10-22 21:10:00 +00001080 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00001081}
1082
Richard Smith07fc6572011-10-22 21:10:00 +00001083bool
1084VectorExprEvaluator::ValueInitialization(const Expr *E) {
1085 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00001086 QualType EltTy = VT->getElementType();
1087 APValue ZeroElement;
1088 if (EltTy->isIntegerType())
1089 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1090 else
1091 ZeroElement =
1092 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1093
Chris Lattner5f9e2722011-07-23 10:55:15 +00001094 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00001095 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00001096}
1097
Richard Smith07fc6572011-10-22 21:10:00 +00001098bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00001099 VisitIgnoredValue(E->getSubExpr());
Richard Smith07fc6572011-10-22 21:10:00 +00001100 return ValueInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00001101}
1102
Nate Begeman59b5da62009-01-18 03:20:47 +00001103//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001104// Integer Evaluation
Richard Smith41bf4f32011-10-24 21:07:08 +00001105//
1106// As a GNU extension, we support casting pointers to sufficiently-wide integer
1107// types and back in constant folding. Integer values are thus represented
1108// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001109//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001110
1111namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001112class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001113 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001114 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00001115public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001116 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001117 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001118
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001119 bool Success(const llvm::APSInt &SI, const Expr *E) {
1120 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001121 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001122 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001123 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001124 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001125 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001126 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001127 return true;
1128 }
1129
Daniel Dunbar131eb432009-02-19 09:06:44 +00001130 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001131 assert(E->getType()->isIntegralOrEnumerationType() &&
1132 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001133 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001134 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001135 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00001136 Result.getInt().setIsUnsigned(
1137 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00001138 return true;
1139 }
1140
1141 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001142 assert(E->getType()->isIntegralOrEnumerationType() &&
1143 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001144 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00001145 return true;
1146 }
1147
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001148 bool Success(CharUnits Size, const Expr *E) {
1149 return Success(Size.getQuantity(), E);
1150 }
1151
1152
Anders Carlsson82206e22008-11-30 18:14:57 +00001153 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001154 // Take the first error.
Richard Smith1e12c592011-10-16 21:26:27 +00001155 if (Info.EvalStatus.Diag == 0) {
1156 Info.EvalStatus.DiagLoc = L;
1157 Info.EvalStatus.Diag = D;
1158 Info.EvalStatus.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +00001159 }
Chris Lattner54176fd2008-07-12 00:14:42 +00001160 return false;
Chris Lattner7a767782008-07-11 19:24:49 +00001161 }
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001163 bool Success(const APValue &V, const Expr *E) {
1164 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00001165 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001166 bool Error(const Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001167 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +00001168 }
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Richard Smithf10d9172011-10-11 21:43:33 +00001170 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1171
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001172 //===--------------------------------------------------------------------===//
1173 // Visitor Methods
1174 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00001175
Chris Lattner4c4867e2008-07-12 00:38:25 +00001176 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001177 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001178 }
1179 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001180 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001181 }
Eli Friedman04309752009-11-24 05:28:59 +00001182
1183 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1184 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001185 if (CheckReferencedDecl(E, E->getDecl()))
1186 return true;
1187
1188 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001189 }
1190 bool VisitMemberExpr(const MemberExpr *E) {
1191 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith41bf4f32011-10-24 21:07:08 +00001192 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00001193 return true;
1194 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001195
1196 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001197 }
1198
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001199 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001200 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001201 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001202 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00001203
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001204 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001205 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00001206
Anders Carlsson3068d112008-11-16 19:01:22 +00001207 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001208 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001209 }
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Richard Smithf10d9172011-10-11 21:43:33 +00001211 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00001212 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00001213 return ValueInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00001214 }
1215
Sebastian Redl64b45f72009-01-05 20:52:13 +00001216 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001217 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001218 }
1219
Francois Pichet6ad6f282010-12-07 00:08:36 +00001220 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1221 return Success(E->getValue(), E);
1222 }
1223
John Wiegley21ff2e52011-04-28 00:16:57 +00001224 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1225 return Success(E->getValue(), E);
1226 }
1227
John Wiegley55262202011-04-25 06:54:41 +00001228 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1229 return Success(E->getValue(), E);
1230 }
1231
Eli Friedman722c7172009-02-28 03:59:05 +00001232 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001233 bool VisitUnaryImag(const UnaryOperator *E);
1234
Sebastian Redl295995c2010-09-10 20:55:47 +00001235 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001236 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00001237
Chris Lattnerfcee0012008-07-11 21:24:13 +00001238private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001239 CharUnits GetAlignOfExpr(const Expr *E);
1240 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001241 static QualType GetObjectType(const Expr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001242 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001243 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001244};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001245} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001246
Richard Smith41bf4f32011-10-24 21:07:08 +00001247/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1248/// produce either the integer value or a pointer.
1249///
1250/// GCC has a heinous extension which folds casts between pointer types and
1251/// pointer-sized integral types. We support this by allowing the evaluation of
1252/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1253/// Some simple arithmetic on such values is supported (they are treated much
1254/// like char*).
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001255static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Richard Smith41bf4f32011-10-24 21:07:08 +00001256 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001257 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001258}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001259
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001260static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
1261 APValue Val;
1262 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1263 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001264 Result = Val.getInt();
1265 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001266}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001267
Eli Friedman04309752009-11-24 05:28:59 +00001268bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001269 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001270 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001271 // Check for signedness/width mismatches between E type and ECD value.
1272 bool SameSign = (ECD->getInitVal().isSigned()
1273 == E->getType()->isSignedIntegerOrEnumerationType());
1274 bool SameWidth = (ECD->getInitVal().getBitWidth()
1275 == Info.Ctx.getIntWidth(E->getType()));
1276 if (SameSign && SameWidth)
1277 return Success(ECD->getInitVal(), E);
1278 else {
1279 // Get rid of mismatch (otherwise Success assertions will fail)
1280 // by computing a new value matching the type of E.
1281 llvm::APSInt Val = ECD->getInitVal();
1282 if (!SameSign)
1283 Val.setIsSigned(!ECD->getInitVal().isSigned());
1284 if (!SameWidth)
1285 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1286 return Success(Val, E);
1287 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001288 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001289 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00001290}
1291
Chris Lattnera4d55d82008-10-06 06:40:35 +00001292/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1293/// as GCC.
1294static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1295 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001296 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001297 enum gcc_type_class {
1298 no_type_class = -1,
1299 void_type_class, integer_type_class, char_type_class,
1300 enumeral_type_class, boolean_type_class,
1301 pointer_type_class, reference_type_class, offset_type_class,
1302 real_type_class, complex_type_class,
1303 function_type_class, method_type_class,
1304 record_type_class, union_type_class,
1305 array_type_class, string_type_class,
1306 lang_type_class
1307 };
Mike Stump1eb44332009-09-09 15:08:12 +00001308
1309 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001310 // ideal, however it is what gcc does.
1311 if (E->getNumArgs() == 0)
1312 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Chris Lattnera4d55d82008-10-06 06:40:35 +00001314 QualType ArgTy = E->getArg(0)->getType();
1315 if (ArgTy->isVoidType())
1316 return void_type_class;
1317 else if (ArgTy->isEnumeralType())
1318 return enumeral_type_class;
1319 else if (ArgTy->isBooleanType())
1320 return boolean_type_class;
1321 else if (ArgTy->isCharType())
1322 return string_type_class; // gcc doesn't appear to use char_type_class
1323 else if (ArgTy->isIntegerType())
1324 return integer_type_class;
1325 else if (ArgTy->isPointerType())
1326 return pointer_type_class;
1327 else if (ArgTy->isReferenceType())
1328 return reference_type_class;
1329 else if (ArgTy->isRealType())
1330 return real_type_class;
1331 else if (ArgTy->isComplexType())
1332 return complex_type_class;
1333 else if (ArgTy->isFunctionType())
1334 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001335 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001336 return record_type_class;
1337 else if (ArgTy->isUnionType())
1338 return union_type_class;
1339 else if (ArgTy->isArrayType())
1340 return array_type_class;
1341 else if (ArgTy->isUnionType())
1342 return union_type_class;
1343 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00001344 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00001345 return -1;
1346}
1347
John McCall42c8f872010-05-10 23:27:23 +00001348/// Retrieves the "underlying object type" of the given expression,
1349/// as used by __builtin_object_size.
1350QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1351 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1352 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1353 return VD->getType();
1354 } else if (isa<CompoundLiteralExpr>(E)) {
1355 return E->getType();
1356 }
1357
1358 return QualType();
1359}
1360
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001361bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00001362 // TODO: Perhaps we should let LLVM lower this?
1363 LValue Base;
1364 if (!EvaluatePointer(E->getArg(0), Base, Info))
1365 return false;
1366
1367 // If we can prove the base is null, lower to zero now.
1368 const Expr *LVBase = Base.getLValueBase();
1369 if (!LVBase) return Success(0, E);
1370
1371 QualType T = GetObjectType(LVBase);
1372 if (T.isNull() ||
1373 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001374 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001375 T->isVariablyModifiedType() ||
1376 T->isDependentType())
1377 return false;
1378
1379 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1380 CharUnits Offset = Base.getLValueOffset();
1381
1382 if (!Offset.isNegative() && Offset <= Size)
1383 Size -= Offset;
1384 else
1385 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001386 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00001387}
1388
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001389bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001390 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001391 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001392 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001393
1394 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001395 if (TryEvaluateBuiltinObjectSize(E))
1396 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001397
Eric Christopherb2aaf512010-01-19 22:58:35 +00001398 // If evaluating the argument has side-effects we can't determine
1399 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001400 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001401 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001402 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001403 return Success(0, E);
1404 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001405
Mike Stump64eda9e2009-10-26 18:35:08 +00001406 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1407 }
1408
Chris Lattner019f4e82008-10-06 05:28:25 +00001409 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001410 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001412 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001413 // __builtin_constant_p always has one operand: it returns true if that
1414 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001415 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001416
1417 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001418 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001419 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001420 return Success(Operand, E);
1421 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001422
1423 case Builtin::BI__builtin_expect:
1424 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001425
1426 case Builtin::BIstrlen:
1427 case Builtin::BI__builtin_strlen:
1428 // As an extension, we support strlen() and __builtin_strlen() as constant
1429 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001430 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00001431 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1432 // The string literal may have embedded null characters. Find the first
1433 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001434 StringRef Str = S->getString();
1435 StringRef::size_type Pos = Str.find(0);
1436 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00001437 Str = Str.substr(0, Pos);
1438
1439 return Success(Str.size(), E);
1440 }
1441
1442 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00001443
1444 case Builtin::BI__atomic_is_lock_free: {
1445 APSInt SizeVal;
1446 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1447 return false;
1448
1449 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1450 // of two less than the maximum inline atomic width, we know it is
1451 // lock-free. If the size isn't a power of two, or greater than the
1452 // maximum alignment where we promote atomics, we know it is not lock-free
1453 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1454 // the answer can only be determined at runtime; for example, 16-byte
1455 // atomics have lock-free implementations on some, but not all,
1456 // x86-64 processors.
1457
1458 // Check power-of-two.
1459 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1460 if (!Size.isPowerOfTwo())
1461#if 0
1462 // FIXME: Suppress this folding until the ABI for the promotion width
1463 // settles.
1464 return Success(0, E);
1465#else
1466 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1467#endif
1468
1469#if 0
1470 // Check against promotion width.
1471 // FIXME: Suppress this folding until the ABI for the promotion width
1472 // settles.
1473 unsigned PromoteWidthBits =
1474 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1475 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1476 return Success(0, E);
1477#endif
1478
1479 // Check against inlining width.
1480 unsigned InlineWidthBits =
1481 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1482 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1483 return Success(1, E);
1484
1485 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1486 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001487 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001488}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001489
Chris Lattnerb542afe2008-07-11 19:10:17 +00001490bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith41bf4f32011-10-24 21:07:08 +00001491 if (E->isAssignmentOp())
1492 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1493
John McCall2de56d12010-08-25 11:45:40 +00001494 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00001495 VisitIgnoredValue(E->getLHS());
1496 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00001497 }
1498
1499 if (E->isLogicalOp()) {
1500 // These need to be handled specially because the operands aren't
1501 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001502 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Richard Smith41bf4f32011-10-24 21:07:08 +00001504 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001505 // We were able to evaluate the LHS, see if we can get away with not
1506 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001507 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001508 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001509
Richard Smith41bf4f32011-10-24 21:07:08 +00001510 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001511 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001512 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001513 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001514 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001515 }
1516 } else {
Richard Smith41bf4f32011-10-24 21:07:08 +00001517 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001518 // We can't evaluate the LHS; however, sometimes the result
1519 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001520 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1521 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001522 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001523 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00001524 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001525
1526 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001527 }
1528 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001529 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001530
Eli Friedmana6afa762008-11-13 06:09:17 +00001531 return false;
1532 }
1533
Anders Carlsson286f85e2008-11-16 07:17:21 +00001534 QualType LHSTy = E->getLHS()->getType();
1535 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001536
1537 if (LHSTy->isAnyComplexType()) {
1538 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001539 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001540
1541 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1542 return false;
1543
1544 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1545 return false;
1546
1547 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001548 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001549 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001550 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001551 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1552
John McCall2de56d12010-08-25 11:45:40 +00001553 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001554 return Success((CR_r == APFloat::cmpEqual &&
1555 CR_i == APFloat::cmpEqual), E);
1556 else {
John McCall2de56d12010-08-25 11:45:40 +00001557 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001558 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001559 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001560 CR_r == APFloat::cmpLessThan ||
1561 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001562 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001563 CR_i == APFloat::cmpLessThan ||
1564 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001565 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001566 } else {
John McCall2de56d12010-08-25 11:45:40 +00001567 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001568 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1569 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1570 else {
John McCall2de56d12010-08-25 11:45:40 +00001571 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001572 "Invalid compex comparison.");
1573 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1574 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1575 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001576 }
1577 }
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Anders Carlsson286f85e2008-11-16 07:17:21 +00001579 if (LHSTy->isRealFloatingType() &&
1580 RHSTy->isRealFloatingType()) {
1581 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Anders Carlsson286f85e2008-11-16 07:17:21 +00001583 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1584 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Anders Carlsson286f85e2008-11-16 07:17:21 +00001586 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1587 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Anders Carlsson286f85e2008-11-16 07:17:21 +00001589 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001590
Anders Carlsson286f85e2008-11-16 07:17:21 +00001591 switch (E->getOpcode()) {
1592 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00001593 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001594 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001595 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001596 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001597 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001598 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001599 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001600 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001601 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001602 E);
John McCall2de56d12010-08-25 11:45:40 +00001603 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001604 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001605 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001606 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001607 || CR == APFloat::cmpLessThan
1608 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001609 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001610 }
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001612 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001613 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001614 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001615 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1616 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001617
John McCallefdb83e2010-05-07 21:00:08 +00001618 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001619 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1620 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001621
Eli Friedman5bc86102009-06-14 02:17:33 +00001622 // Reject any bases from the normal codepath; we special-case comparisons
1623 // to null.
1624 if (LHSValue.getLValueBase()) {
1625 if (!E->isEqualityOp())
1626 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001627 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001628 return false;
1629 bool bres;
1630 if (!EvalPointerValueAsBool(LHSValue, bres))
1631 return false;
John McCall2de56d12010-08-25 11:45:40 +00001632 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001633 } else if (RHSValue.getLValueBase()) {
1634 if (!E->isEqualityOp())
1635 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001636 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001637 return false;
1638 bool bres;
1639 if (!EvalPointerValueAsBool(RHSValue, bres))
1640 return false;
John McCall2de56d12010-08-25 11:45:40 +00001641 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001642 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001643
John McCall2de56d12010-08-25 11:45:40 +00001644 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001645 QualType Type = E->getLHS()->getType();
1646 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001647
Ken Dycka7305832010-01-15 12:37:54 +00001648 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001649 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001650 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001651
Ken Dycka7305832010-01-15 12:37:54 +00001652 CharUnits Diff = LHSValue.getLValueOffset() -
1653 RHSValue.getLValueOffset();
1654 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001655 }
1656 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001657 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001658 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001659 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001660 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1661 }
1662 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001663 }
1664 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001665 if (!LHSTy->isIntegralOrEnumerationType() ||
1666 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001667 // We can't continue from here for non-integral types, and they
1668 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001669 return false;
1670 }
1671
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001672 // The LHS of a constant expr is always evaluated and needed.
Richard Smith41bf4f32011-10-24 21:07:08 +00001673 APValue LHSVal;
1674 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner54176fd2008-07-12 00:14:42 +00001675 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001676
Richard Smith41bf4f32011-10-24 21:07:08 +00001677 if (!Visit(E->getRHS()))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001678 return false;
Richard Smith41bf4f32011-10-24 21:07:08 +00001679 APValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001680
1681 // Handle cases like (unsigned long)&a + 4.
Richard Smith41bf4f32011-10-24 21:07:08 +00001682 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
1683 CharUnits Offset = LHSVal.getLValueOffset();
Ken Dycka7305832010-01-15 12:37:54 +00001684 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1685 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001686 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001687 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001688 else
Ken Dycka7305832010-01-15 12:37:54 +00001689 Offset -= AdditionalOffset;
Richard Smith41bf4f32011-10-24 21:07:08 +00001690 Result = APValue(LHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001691 return true;
1692 }
1693
1694 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001695 if (E->getOpcode() == BO_Add &&
Richard Smith41bf4f32011-10-24 21:07:08 +00001696 RHSVal.isLValue() && LHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001697 CharUnits Offset = RHSVal.getLValueOffset();
Richard Smith41bf4f32011-10-24 21:07:08 +00001698 Offset += CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Ken Dycka7305832010-01-15 12:37:54 +00001699 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001700 return true;
1701 }
1702
1703 // All the following cases expect both operands to be an integer
Richard Smith41bf4f32011-10-24 21:07:08 +00001704 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001705 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001706
Richard Smith41bf4f32011-10-24 21:07:08 +00001707 APSInt &LHS = LHSVal.getInt();
1708 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00001709
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001710 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001711 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001712 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith41bf4f32011-10-24 21:07:08 +00001713 case BO_Mul: return Success(LHS * RHS, E);
1714 case BO_Add: return Success(LHS + RHS, E);
1715 case BO_Sub: return Success(LHS - RHS, E);
1716 case BO_And: return Success(LHS & RHS, E);
1717 case BO_Xor: return Success(LHS ^ RHS, E);
1718 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001719 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001720 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001721 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith41bf4f32011-10-24 21:07:08 +00001722 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001723 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001724 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001725 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith41bf4f32011-10-24 21:07:08 +00001726 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001727 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001728 // During constant-folding, a negative shift is an opposite shift.
1729 if (RHS.isSigned() && RHS.isNegative()) {
1730 RHS = -RHS;
1731 goto shift_right;
1732 }
1733
1734 shift_left:
1735 unsigned SA
Richard Smith41bf4f32011-10-24 21:07:08 +00001736 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1737 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001738 }
John McCall2de56d12010-08-25 11:45:40 +00001739 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001740 // During constant-folding, a negative shift is an opposite shift.
1741 if (RHS.isSigned() && RHS.isNegative()) {
1742 RHS = -RHS;
1743 goto shift_left;
1744 }
1745
1746 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001747 unsigned SA =
Richard Smith41bf4f32011-10-24 21:07:08 +00001748 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1749 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001750 }
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Richard Smith41bf4f32011-10-24 21:07:08 +00001752 case BO_LT: return Success(LHS < RHS, E);
1753 case BO_GT: return Success(LHS > RHS, E);
1754 case BO_LE: return Success(LHS <= RHS, E);
1755 case BO_GE: return Success(LHS >= RHS, E);
1756 case BO_EQ: return Success(LHS == RHS, E);
1757 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001758 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001759}
1760
Ken Dyck8b752f12010-01-27 17:10:57 +00001761CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001762 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1763 // the result is the size of the referenced type."
1764 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1765 // result shall be the alignment of the referenced type."
1766 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1767 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00001768
1769 // __alignof is defined to return the preferred alignment.
1770 return Info.Ctx.toCharUnitsFromBits(
1771 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00001772}
1773
Ken Dyck8b752f12010-01-27 17:10:57 +00001774CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001775 E = E->IgnoreParens();
1776
1777 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001778 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001779 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001780 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1781 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001782
Chris Lattneraf707ab2009-01-24 21:53:27 +00001783 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001784 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1785 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001786
Chris Lattnere9feb472009-01-24 21:09:06 +00001787 return GetAlignOfType(E->getType());
1788}
1789
1790
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001791/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1792/// a result as the expression's type.
1793bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1794 const UnaryExprOrTypeTraitExpr *E) {
1795 switch(E->getKind()) {
1796 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00001797 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001798 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001799 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001800 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001801 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001802
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001803 case UETT_VecStep: {
1804 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00001805
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001806 if (Ty->isVectorType()) {
1807 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00001808
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001809 // The vec_step built-in functions that take a 3-component
1810 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1811 if (n == 3)
1812 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001813
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001814 return Success(n, E);
1815 } else
1816 return Success(1, E);
1817 }
1818
1819 case UETT_SizeOf: {
1820 QualType SrcTy = E->getTypeOfArgument();
1821 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1822 // the result is the size of the referenced type."
1823 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1824 // result shall be the alignment of the referenced type."
1825 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1826 SrcTy = Ref->getPointeeType();
1827
1828 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1829 // extension.
1830 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1831 return Success(1, E);
1832
1833 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1834 if (!SrcTy->isConstantSizeType())
1835 return false;
1836
1837 // Get information about the size.
1838 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1839 }
1840 }
1841
1842 llvm_unreachable("unknown expr/type trait");
1843 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001844}
1845
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001846bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001847 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001848 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001849 if (n == 0)
1850 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001851 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001852 for (unsigned i = 0; i != n; ++i) {
1853 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1854 switch (ON.getKind()) {
1855 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001856 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001857 APSInt IdxResult;
1858 if (!EvaluateInteger(Idx, IdxResult, Info))
1859 return false;
1860 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1861 if (!AT)
1862 return false;
1863 CurrentType = AT->getElementType();
1864 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1865 Result += IdxResult.getSExtValue() * ElementSize;
1866 break;
1867 }
1868
1869 case OffsetOfExpr::OffsetOfNode::Field: {
1870 FieldDecl *MemberDecl = ON.getField();
1871 const RecordType *RT = CurrentType->getAs<RecordType>();
1872 if (!RT)
1873 return false;
1874 RecordDecl *RD = RT->getDecl();
1875 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00001876 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001877 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001878 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001879 CurrentType = MemberDecl->getType().getNonReferenceType();
1880 break;
1881 }
1882
1883 case OffsetOfExpr::OffsetOfNode::Identifier:
1884 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001885 return false;
1886
1887 case OffsetOfExpr::OffsetOfNode::Base: {
1888 CXXBaseSpecifier *BaseSpec = ON.getBase();
1889 if (BaseSpec->isVirtual())
1890 return false;
1891
1892 // Find the layout of the class whose base we are looking into.
1893 const RecordType *RT = CurrentType->getAs<RecordType>();
1894 if (!RT)
1895 return false;
1896 RecordDecl *RD = RT->getDecl();
1897 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1898
1899 // Find the base class itself.
1900 CurrentType = BaseSpec->getType();
1901 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1902 if (!BaseRT)
1903 return false;
1904
1905 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00001906 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001907 break;
1908 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001909 }
1910 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001911 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001912}
1913
Chris Lattnerb542afe2008-07-11 19:10:17 +00001914bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001915 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001916 // LNot's operand isn't necessarily an integer, so we handle it specially.
1917 bool bres;
Richard Smith41bf4f32011-10-24 21:07:08 +00001918 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00001919 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001920 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001921 }
1922
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001923 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001924 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001925 return false;
1926
Chris Lattner87eae5e2008-07-11 22:52:41 +00001927 // Get the operand value into 'Result'.
1928 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001929 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001930
Chris Lattner75a48812008-07-11 22:15:16 +00001931 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001932 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001933 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1934 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001935 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001936 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001937 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1938 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001939 return true;
John McCall2de56d12010-08-25 11:45:40 +00001940 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001941 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001942 return true;
John McCall2de56d12010-08-25 11:45:40 +00001943 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001944 if (!Result.isInt()) return false;
1945 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001946 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001947 if (!Result.isInt()) return false;
1948 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001949 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001950}
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Chris Lattner732b2232008-07-12 01:15:53 +00001952/// HandleCast - This is used to evaluate implicit or explicit casts where the
1953/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001954bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1955 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00001956 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001957 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001958
Eli Friedman46a52322011-03-25 00:43:55 +00001959 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00001960 case CK_BaseToDerived:
1961 case CK_DerivedToBase:
1962 case CK_UncheckedDerivedToBase:
1963 case CK_Dynamic:
1964 case CK_ToUnion:
1965 case CK_ArrayToPointerDecay:
1966 case CK_FunctionToPointerDecay:
1967 case CK_NullToPointer:
1968 case CK_NullToMemberPointer:
1969 case CK_BaseToDerivedMemberPointer:
1970 case CK_DerivedToBaseMemberPointer:
1971 case CK_ConstructorConversion:
1972 case CK_IntegralToPointer:
1973 case CK_ToVoid:
1974 case CK_VectorSplat:
1975 case CK_IntegralToFloating:
1976 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00001977 case CK_CPointerToObjCPointerCast:
1978 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001979 case CK_AnyPointerToBlockPointerCast:
1980 case CK_ObjCObjectLValueCast:
1981 case CK_FloatingRealToComplex:
1982 case CK_FloatingComplexToReal:
1983 case CK_FloatingComplexCast:
1984 case CK_FloatingComplexToIntegralComplex:
1985 case CK_IntegralRealToComplex:
1986 case CK_IntegralComplexCast:
1987 case CK_IntegralComplexToFloatingComplex:
1988 llvm_unreachable("invalid cast kind for integral value");
1989
Eli Friedmane50c2972011-03-25 19:07:11 +00001990 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001991 case CK_Dependent:
1992 case CK_GetObjCProperty:
1993 case CK_LValueBitCast:
1994 case CK_UserDefinedConversion:
John McCall33e56f32011-09-10 06:18:15 +00001995 case CK_ARCProduceObject:
1996 case CK_ARCConsumeObject:
1997 case CK_ARCReclaimReturnedObject:
1998 case CK_ARCExtendBlockObject:
Eli Friedman46a52322011-03-25 00:43:55 +00001999 return false;
2000
2001 case CK_LValueToRValue:
2002 case CK_NoOp:
Richard Smith41bf4f32011-10-24 21:07:08 +00002003 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00002004
2005 case CK_MemberPointerToBoolean:
2006 case CK_PointerToBoolean:
2007 case CK_IntegralToBoolean:
2008 case CK_FloatingToBoolean:
2009 case CK_FloatingComplexToBoolean:
2010 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002011 bool BoolResult;
Richard Smith41bf4f32011-10-24 21:07:08 +00002012 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002013 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00002014 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002015 }
2016
Eli Friedman46a52322011-03-25 00:43:55 +00002017 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00002018 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00002019 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002020
Eli Friedmanbe265702009-02-20 01:15:07 +00002021 if (!Result.isInt()) {
2022 // Only allow casts of lvalues if they are lossless.
2023 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2024 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002025
Daniel Dunbardd211642009-02-19 22:24:01 +00002026 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002027 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00002028 }
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Eli Friedman46a52322011-03-25 00:43:55 +00002030 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00002031 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00002032 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00002033 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00002034
Daniel Dunbardd211642009-02-19 22:24:01 +00002035 if (LV.getLValueBase()) {
2036 // Only allow based lvalue casts if they are lossless.
2037 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2038 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00002039
John McCallefdb83e2010-05-07 21:00:08 +00002040 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00002041 return true;
2042 }
2043
Ken Dycka7305832010-01-15 12:37:54 +00002044 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2045 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00002046 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00002047 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002048
Eli Friedman46a52322011-03-25 00:43:55 +00002049 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00002050 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00002051 if (!EvaluateComplex(SubExpr, C, Info))
2052 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00002053 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00002054 }
Eli Friedman2217c872009-02-22 11:46:18 +00002055
Eli Friedman46a52322011-03-25 00:43:55 +00002056 case CK_FloatingToIntegral: {
2057 APFloat F(0.0);
2058 if (!EvaluateFloat(SubExpr, F, Info))
2059 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00002060
Eli Friedman46a52322011-03-25 00:43:55 +00002061 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2062 }
2063 }
Mike Stump1eb44332009-09-09 15:08:12 +00002064
Eli Friedman46a52322011-03-25 00:43:55 +00002065 llvm_unreachable("unknown cast resulting in integral value");
2066 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002067}
Anders Carlsson2bad1682008-07-08 14:30:00 +00002068
Eli Friedman722c7172009-02-28 03:59:05 +00002069bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2070 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002071 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00002072 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2073 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2074 return Success(LV.getComplexIntReal(), E);
2075 }
2076
2077 return Visit(E->getSubExpr());
2078}
2079
Eli Friedman664a1042009-02-27 04:45:43 +00002080bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00002081 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002082 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00002083 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2084 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2085 return Success(LV.getComplexIntImag(), E);
2086 }
2087
Richard Smith8327fad2011-10-24 18:44:57 +00002088 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00002089 return Success(0, E);
2090}
2091
Douglas Gregoree8aff02011-01-04 17:33:58 +00002092bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2093 return Success(E->getPackLength(), E);
2094}
2095
Sebastian Redl295995c2010-09-10 20:55:47 +00002096bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2097 return Success(E->getValue(), E);
2098}
2099
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002100//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002101// Float Evaluation
2102//===----------------------------------------------------------------------===//
2103
2104namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002105class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002106 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002107 APFloat &Result;
2108public:
2109 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002110 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002111
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002112 bool Success(const APValue &V, const Expr *e) {
2113 Result = V.getFloat();
2114 return true;
2115 }
2116 bool Error(const Stmt *S) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002117 return false;
2118 }
2119
Richard Smithf10d9172011-10-11 21:43:33 +00002120 bool ValueInitialization(const Expr *E) {
2121 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2122 return true;
2123 }
2124
Chris Lattner019f4e82008-10-06 05:28:25 +00002125 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002126
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002127 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002128 bool VisitBinaryOperator(const BinaryOperator *E);
2129 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002130 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00002131
John McCallabd3a852010-05-07 22:08:54 +00002132 bool VisitUnaryReal(const UnaryOperator *E);
2133 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002134
John McCallabd3a852010-05-07 22:08:54 +00002135 // FIXME: Missing: array subscript of vector, member of vector,
2136 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002137};
2138} // end anonymous namespace
2139
2140static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith41bf4f32011-10-24 21:07:08 +00002141 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002142 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002143}
2144
Jay Foad4ba2a172011-01-12 09:06:06 +00002145static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00002146 QualType ResultTy,
2147 const Expr *Arg,
2148 bool SNaN,
2149 llvm::APFloat &Result) {
2150 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2151 if (!S) return false;
2152
2153 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2154
2155 llvm::APInt fill;
2156
2157 // Treat empty strings as if they were zero.
2158 if (S->getString().empty())
2159 fill = llvm::APInt(32, 0);
2160 else if (S->getString().getAsInteger(0, fill))
2161 return false;
2162
2163 if (SNaN)
2164 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2165 else
2166 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2167 return true;
2168}
2169
Chris Lattner019f4e82008-10-06 05:28:25 +00002170bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00002171 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002172 default:
2173 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2174
Chris Lattner019f4e82008-10-06 05:28:25 +00002175 case Builtin::BI__builtin_huge_val:
2176 case Builtin::BI__builtin_huge_valf:
2177 case Builtin::BI__builtin_huge_vall:
2178 case Builtin::BI__builtin_inf:
2179 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002180 case Builtin::BI__builtin_infl: {
2181 const llvm::fltSemantics &Sem =
2182 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00002183 Result = llvm::APFloat::getInf(Sem);
2184 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002185 }
Mike Stump1eb44332009-09-09 15:08:12 +00002186
John McCalldb7b72a2010-02-28 13:00:19 +00002187 case Builtin::BI__builtin_nans:
2188 case Builtin::BI__builtin_nansf:
2189 case Builtin::BI__builtin_nansl:
2190 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2191 true, Result);
2192
Chris Lattner9e621712008-10-06 06:31:58 +00002193 case Builtin::BI__builtin_nan:
2194 case Builtin::BI__builtin_nanf:
2195 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00002196 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00002197 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00002198 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2199 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002200
2201 case Builtin::BI__builtin_fabs:
2202 case Builtin::BI__builtin_fabsf:
2203 case Builtin::BI__builtin_fabsl:
2204 if (!EvaluateFloat(E->getArg(0), Result, Info))
2205 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002207 if (Result.isNegative())
2208 Result.changeSign();
2209 return true;
2210
Mike Stump1eb44332009-09-09 15:08:12 +00002211 case Builtin::BI__builtin_copysign:
2212 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002213 case Builtin::BI__builtin_copysignl: {
2214 APFloat RHS(0.);
2215 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2216 !EvaluateFloat(E->getArg(1), RHS, Info))
2217 return false;
2218 Result.copySign(RHS);
2219 return true;
2220 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002221 }
2222}
2223
John McCallabd3a852010-05-07 22:08:54 +00002224bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002225 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2226 ComplexValue CV;
2227 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2228 return false;
2229 Result = CV.FloatReal;
2230 return true;
2231 }
2232
2233 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00002234}
2235
2236bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002237 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2238 ComplexValue CV;
2239 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2240 return false;
2241 Result = CV.FloatImag;
2242 return true;
2243 }
2244
Richard Smith8327fad2011-10-24 18:44:57 +00002245 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00002246 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2247 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00002248 return true;
2249}
2250
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002251bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002252 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00002253 return false;
2254
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002255 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2256 return false;
2257
2258 switch (E->getOpcode()) {
2259 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002260 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002261 return true;
John McCall2de56d12010-08-25 11:45:40 +00002262 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002263 Result.changeSign();
2264 return true;
2265 }
2266}
Chris Lattner019f4e82008-10-06 05:28:25 +00002267
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002268bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002269 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00002270 VisitIgnoredValue(E->getLHS());
2271 return Visit(E->getRHS());
Eli Friedman7f92f032009-11-16 04:25:37 +00002272 }
2273
Anders Carlsson96e93662010-10-31 01:21:47 +00002274 // We can't evaluate pointer-to-member operations.
2275 if (E->isPtrMemOp())
2276 return false;
2277
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002278 // FIXME: Diagnostics? I really don't understand how the warnings
2279 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002280 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002281 if (!EvaluateFloat(E->getLHS(), Result, Info))
2282 return false;
2283 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2284 return false;
2285
2286 switch (E->getOpcode()) {
2287 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002288 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002289 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2290 return true;
John McCall2de56d12010-08-25 11:45:40 +00002291 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002292 Result.add(RHS, APFloat::rmNearestTiesToEven);
2293 return true;
John McCall2de56d12010-08-25 11:45:40 +00002294 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002295 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2296 return true;
John McCall2de56d12010-08-25 11:45:40 +00002297 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002298 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2299 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002300 }
2301}
2302
2303bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2304 Result = E->getValue();
2305 return true;
2306}
2307
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002308bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2309 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002310
Eli Friedman2a523ee2011-03-25 00:54:52 +00002311 switch (E->getCastKind()) {
2312 default:
Richard Smith41bf4f32011-10-24 21:07:08 +00002313 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00002314
2315 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002316 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002317 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002318 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002319 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002320 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002321 return true;
2322 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002323
2324 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002325 if (!Visit(SubExpr))
2326 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002327 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2328 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002329 return true;
2330 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002331
Eli Friedman2a523ee2011-03-25 00:54:52 +00002332 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00002333 ComplexValue V;
2334 if (!EvaluateComplex(SubExpr, V, Info))
2335 return false;
2336 Result = V.getComplexFloatReal();
2337 return true;
2338 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002339 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002340
2341 return false;
2342}
2343
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002344//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002345// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002346//===----------------------------------------------------------------------===//
2347
2348namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002349class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002350 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00002351 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002352
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002353public:
John McCallf4cf1a12010-05-07 17:22:02 +00002354 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002355 : ExprEvaluatorBaseTy(info), Result(Result) {}
2356
2357 bool Success(const APValue &V, const Expr *e) {
2358 Result.setFrom(V);
2359 return true;
2360 }
2361 bool Error(const Expr *E) {
2362 return false;
2363 }
Mike Stump1eb44332009-09-09 15:08:12 +00002364
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002365 //===--------------------------------------------------------------------===//
2366 // Visitor Methods
2367 //===--------------------------------------------------------------------===//
2368
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002369 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002370
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002371 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002372
John McCallf4cf1a12010-05-07 17:22:02 +00002373 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002374 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00002375 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002376};
2377} // end anonymous namespace
2378
John McCallf4cf1a12010-05-07 17:22:02 +00002379static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2380 EvalInfo &Info) {
Richard Smith41bf4f32011-10-24 21:07:08 +00002381 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002382 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002383}
2384
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002385bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2386 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002387
2388 if (SubExpr->getType()->isRealFloatingType()) {
2389 Result.makeComplexFloat();
2390 APFloat &Imag = Result.FloatImag;
2391 if (!EvaluateFloat(SubExpr, Imag, Info))
2392 return false;
2393
2394 Result.FloatReal = APFloat(Imag.getSemantics());
2395 return true;
2396 } else {
2397 assert(SubExpr->getType()->isIntegerType() &&
2398 "Unexpected imaginary literal.");
2399
2400 Result.makeComplexInt();
2401 APSInt &Imag = Result.IntImag;
2402 if (!EvaluateInteger(SubExpr, Imag, Info))
2403 return false;
2404
2405 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2406 return true;
2407 }
2408}
2409
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002410bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002411
John McCall8786da72010-12-14 17:51:41 +00002412 switch (E->getCastKind()) {
2413 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00002414 case CK_BaseToDerived:
2415 case CK_DerivedToBase:
2416 case CK_UncheckedDerivedToBase:
2417 case CK_Dynamic:
2418 case CK_ToUnion:
2419 case CK_ArrayToPointerDecay:
2420 case CK_FunctionToPointerDecay:
2421 case CK_NullToPointer:
2422 case CK_NullToMemberPointer:
2423 case CK_BaseToDerivedMemberPointer:
2424 case CK_DerivedToBaseMemberPointer:
2425 case CK_MemberPointerToBoolean:
2426 case CK_ConstructorConversion:
2427 case CK_IntegralToPointer:
2428 case CK_PointerToIntegral:
2429 case CK_PointerToBoolean:
2430 case CK_ToVoid:
2431 case CK_VectorSplat:
2432 case CK_IntegralCast:
2433 case CK_IntegralToBoolean:
2434 case CK_IntegralToFloating:
2435 case CK_FloatingToIntegral:
2436 case CK_FloatingToBoolean:
2437 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002438 case CK_CPointerToObjCPointerCast:
2439 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00002440 case CK_AnyPointerToBlockPointerCast:
2441 case CK_ObjCObjectLValueCast:
2442 case CK_FloatingComplexToReal:
2443 case CK_FloatingComplexToBoolean:
2444 case CK_IntegralComplexToReal:
2445 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00002446 case CK_ARCProduceObject:
2447 case CK_ARCConsumeObject:
2448 case CK_ARCReclaimReturnedObject:
2449 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00002450 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002451
John McCall8786da72010-12-14 17:51:41 +00002452 case CK_LValueToRValue:
2453 case CK_NoOp:
Richard Smith41bf4f32011-10-24 21:07:08 +00002454 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00002455
2456 case CK_Dependent:
2457 case CK_GetObjCProperty:
Eli Friedman46a52322011-03-25 00:43:55 +00002458 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00002459 case CK_UserDefinedConversion:
2460 return false;
2461
2462 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002463 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002464 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002465 return false;
2466
John McCall8786da72010-12-14 17:51:41 +00002467 Result.makeComplexFloat();
2468 Result.FloatImag = APFloat(Real.getSemantics());
2469 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002470 }
2471
John McCall8786da72010-12-14 17:51:41 +00002472 case CK_FloatingComplexCast: {
2473 if (!Visit(E->getSubExpr()))
2474 return false;
2475
2476 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2477 QualType From
2478 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2479
2480 Result.FloatReal
2481 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2482 Result.FloatImag
2483 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2484 return true;
2485 }
2486
2487 case CK_FloatingComplexToIntegralComplex: {
2488 if (!Visit(E->getSubExpr()))
2489 return false;
2490
2491 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2492 QualType From
2493 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2494 Result.makeComplexInt();
2495 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2496 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2497 return true;
2498 }
2499
2500 case CK_IntegralRealToComplex: {
2501 APSInt &Real = Result.IntReal;
2502 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2503 return false;
2504
2505 Result.makeComplexInt();
2506 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2507 return true;
2508 }
2509
2510 case CK_IntegralComplexCast: {
2511 if (!Visit(E->getSubExpr()))
2512 return false;
2513
2514 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2515 QualType From
2516 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2517
2518 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2519 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2520 return true;
2521 }
2522
2523 case CK_IntegralComplexToFloatingComplex: {
2524 if (!Visit(E->getSubExpr()))
2525 return false;
2526
2527 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2528 QualType From
2529 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2530 Result.makeComplexFloat();
2531 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2532 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2533 return true;
2534 }
2535 }
2536
2537 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002538 return false;
2539}
2540
John McCallf4cf1a12010-05-07 17:22:02 +00002541bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002542 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00002543 VisitIgnoredValue(E->getLHS());
2544 return Visit(E->getRHS());
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002545 }
John McCallf4cf1a12010-05-07 17:22:02 +00002546 if (!Visit(E->getLHS()))
2547 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002548
John McCallf4cf1a12010-05-07 17:22:02 +00002549 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002550 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002551 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002552
Daniel Dunbar3f279872009-01-29 01:32:56 +00002553 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2554 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002555 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002556 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002557 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002558 if (Result.isComplexFloat()) {
2559 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2560 APFloat::rmNearestTiesToEven);
2561 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2562 APFloat::rmNearestTiesToEven);
2563 } else {
2564 Result.getComplexIntReal() += RHS.getComplexIntReal();
2565 Result.getComplexIntImag() += RHS.getComplexIntImag();
2566 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002567 break;
John McCall2de56d12010-08-25 11:45:40 +00002568 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002569 if (Result.isComplexFloat()) {
2570 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2571 APFloat::rmNearestTiesToEven);
2572 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2573 APFloat::rmNearestTiesToEven);
2574 } else {
2575 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2576 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2577 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002578 break;
John McCall2de56d12010-08-25 11:45:40 +00002579 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002580 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002581 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002582 APFloat &LHS_r = LHS.getComplexFloatReal();
2583 APFloat &LHS_i = LHS.getComplexFloatImag();
2584 APFloat &RHS_r = RHS.getComplexFloatReal();
2585 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Daniel Dunbar3f279872009-01-29 01:32:56 +00002587 APFloat Tmp = LHS_r;
2588 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2589 Result.getComplexFloatReal() = Tmp;
2590 Tmp = LHS_i;
2591 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2592 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2593
2594 Tmp = LHS_r;
2595 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2596 Result.getComplexFloatImag() = Tmp;
2597 Tmp = LHS_i;
2598 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2599 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2600 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002601 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002602 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002603 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2604 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002605 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002606 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2607 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2608 }
2609 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002610 case BO_Div:
2611 if (Result.isComplexFloat()) {
2612 ComplexValue LHS = Result;
2613 APFloat &LHS_r = LHS.getComplexFloatReal();
2614 APFloat &LHS_i = LHS.getComplexFloatImag();
2615 APFloat &RHS_r = RHS.getComplexFloatReal();
2616 APFloat &RHS_i = RHS.getComplexFloatImag();
2617 APFloat &Res_r = Result.getComplexFloatReal();
2618 APFloat &Res_i = Result.getComplexFloatImag();
2619
2620 APFloat Den = RHS_r;
2621 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2622 APFloat Tmp = RHS_i;
2623 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2624 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2625
2626 Res_r = LHS_r;
2627 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2628 Tmp = LHS_i;
2629 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2630 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2631 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2632
2633 Res_i = LHS_i;
2634 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2635 Tmp = LHS_r;
2636 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2637 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2638 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2639 } else {
2640 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2641 // FIXME: what about diagnostics?
2642 return false;
2643 }
2644 ComplexValue LHS = Result;
2645 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2646 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2647 Result.getComplexIntReal() =
2648 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2649 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2650 Result.getComplexIntImag() =
2651 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2652 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2653 }
2654 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002655 }
2656
John McCallf4cf1a12010-05-07 17:22:02 +00002657 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002658}
2659
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002660bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2661 // Get the operand value into 'Result'.
2662 if (!Visit(E->getSubExpr()))
2663 return false;
2664
2665 switch (E->getOpcode()) {
2666 default:
2667 // FIXME: what about diagnostics?
2668 return false;
2669 case UO_Extension:
2670 return true;
2671 case UO_Plus:
2672 // The result is always just the subexpr.
2673 return true;
2674 case UO_Minus:
2675 if (Result.isComplexFloat()) {
2676 Result.getComplexFloatReal().changeSign();
2677 Result.getComplexFloatImag().changeSign();
2678 }
2679 else {
2680 Result.getComplexIntReal() = -Result.getComplexIntReal();
2681 Result.getComplexIntImag() = -Result.getComplexIntImag();
2682 }
2683 return true;
2684 case UO_Not:
2685 if (Result.isComplexFloat())
2686 Result.getComplexFloatImag().changeSign();
2687 else
2688 Result.getComplexIntImag() = -Result.getComplexIntImag();
2689 return true;
2690 }
2691}
2692
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002693//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002694// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002695//===----------------------------------------------------------------------===//
2696
Richard Smith1e12c592011-10-16 21:26:27 +00002697static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith41bf4f32011-10-24 21:07:08 +00002698 // In C, function designators are not lvalues, but we evaluate them as if they
2699 // are.
2700 if (E->isGLValue() || E->getType()->isFunctionType()) {
2701 LValue LV;
2702 if (!EvaluateLValue(E, LV, Info))
2703 return false;
2704 LV.moveInto(Result);
2705 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00002706 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002707 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00002708 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00002709 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002710 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002711 } else if (E->getType()->hasPointerRepresentation()) {
2712 LValue LV;
2713 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002714 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00002715 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00002716 } else if (E->getType()->isRealFloatingType()) {
2717 llvm::APFloat F(0.0);
2718 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002719 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00002720 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00002721 } else if (E->getType()->isAnyComplexType()) {
2722 ComplexValue C;
2723 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002724 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00002725 C.moveInto(Result);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002726 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002727 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002728
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002729 return true;
2730}
2731
John McCall56ca35d2011-02-17 10:25:35 +00002732/// Evaluate - Return true if this is a constant which we can fold using
2733/// any crazy technique (that has nothing to do with language standards) that
2734/// we want to. If this function returns true, it returns the folded constant
Richard Smith41bf4f32011-10-24 21:07:08 +00002735/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
2736/// will be applied to the result.
John McCall56ca35d2011-02-17 10:25:35 +00002737bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2738 EvalInfo Info(Ctx, Result);
Richard Smith41bf4f32011-10-24 21:07:08 +00002739
2740 if (!::Evaluate(Result.Val, Info, this))
2741 return false;
2742
2743 if (isGLValue()) {
2744 LValue LV;
2745 LV.setFrom(Result.Val);
2746 return HandleLValueToRValueConversion(Info, getType(), LV, Result.Val);
2747 } else if (Result.Val.isLValue()) {
2748 // FIXME: We don't allow expressions to fold to references to locals. Code
2749 // which calls Evaluate() isn't ready for that yet. For instance, we don't
2750 // have any checking that the initializer of a pointer in C is an address
2751 // constant.
2752 if (!IsGlobalLValue(Result.Val.getLValueBase()))
2753 return false;
2754 }
2755
2756 return true;
John McCall56ca35d2011-02-17 10:25:35 +00002757}
2758
Jay Foad4ba2a172011-01-12 09:06:06 +00002759bool Expr::EvaluateAsBooleanCondition(bool &Result,
2760 const ASTContext &Ctx) const {
Richard Smith41bf4f32011-10-24 21:07:08 +00002761 EvalResult Scratch;
2762 return Evaluate(Scratch, Ctx) && HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00002763}
2764
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002765bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith41bf4f32011-10-24 21:07:08 +00002766 EvalResult ExprResult;
2767 if (!Evaluate(ExprResult, Ctx) || ExprResult.HasSideEffects ||
2768 !ExprResult.Val.isInt())
2769 return false;
2770 Result = ExprResult.Val.getInt();
2771 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002772}
2773
Jay Foad4ba2a172011-01-12 09:06:06 +00002774bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002775 EvalInfo Info(Ctx, Result);
2776
John McCallefdb83e2010-05-07 21:00:08 +00002777 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002778 if (EvaluateLValue(this, LV, Info) &&
2779 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002780 IsGlobalLValue(LV.Base)) {
2781 LV.moveInto(Result.Val);
2782 return true;
2783 }
2784 return false;
2785}
2786
Jay Foad4ba2a172011-01-12 09:06:06 +00002787bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2788 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002789 EvalInfo Info(Ctx, Result);
2790
2791 LValue LV;
2792 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002793 LV.moveInto(Result.Val);
2794 return true;
2795 }
2796 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002797}
2798
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002799/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002800/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002801bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002802 EvalResult Result;
2803 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002804}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002805
Jay Foad4ba2a172011-01-12 09:06:06 +00002806bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00002807 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002808}
2809
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002810APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002811 EvalResult EvalResult;
2812 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002813 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002814 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002815 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002816
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002817 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002818}
John McCalld905f5a2010-05-07 05:32:02 +00002819
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002820 bool Expr::EvalResult::isGlobalLValue() const {
2821 assert(Val.isLValue());
2822 return IsGlobalLValue(Val.getLValueBase());
2823 }
2824
2825
John McCalld905f5a2010-05-07 05:32:02 +00002826/// isIntegerConstantExpr - this recursive routine will test if an expression is
2827/// an integer constant expression.
2828
2829/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2830/// comma, etc
2831///
2832/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2833/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2834/// cast+dereference.
2835
2836// CheckICE - This function does the fundamental ICE checking: the returned
2837// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2838// Note that to reduce code duplication, this helper does no evaluation
2839// itself; the caller checks whether the expression is evaluatable, and
2840// in the rare cases where CheckICE actually cares about the evaluated
2841// value, it calls into Evalute.
2842//
2843// Meanings of Val:
2844// 0: This expression is an ICE if it can be evaluated by Evaluate.
2845// 1: This expression is not an ICE, but if it isn't evaluated, it's
2846// a legal subexpression for an ICE. This return value is used to handle
2847// the comma operator in C99 mode.
2848// 2: This expression is not an ICE, and is not a legal subexpression for one.
2849
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002850namespace {
2851
John McCalld905f5a2010-05-07 05:32:02 +00002852struct ICEDiag {
2853 unsigned Val;
2854 SourceLocation Loc;
2855
2856 public:
2857 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2858 ICEDiag() : Val(0) {}
2859};
2860
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002861}
2862
2863static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002864
2865static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2866 Expr::EvalResult EVResult;
2867 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2868 !EVResult.Val.isInt()) {
2869 return ICEDiag(2, E->getLocStart());
2870 }
2871 return NoDiag();
2872}
2873
2874static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2875 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002876 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002877 return ICEDiag(2, E->getLocStart());
2878 }
2879
2880 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00002881#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00002882#define STMT(Node, Base) case Expr::Node##Class:
2883#define EXPR(Node, Base)
2884#include "clang/AST/StmtNodes.inc"
2885 case Expr::PredefinedExprClass:
2886 case Expr::FloatingLiteralClass:
2887 case Expr::ImaginaryLiteralClass:
2888 case Expr::StringLiteralClass:
2889 case Expr::ArraySubscriptExprClass:
2890 case Expr::MemberExprClass:
2891 case Expr::CompoundAssignOperatorClass:
2892 case Expr::CompoundLiteralExprClass:
2893 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002894 case Expr::DesignatedInitExprClass:
2895 case Expr::ImplicitValueInitExprClass:
2896 case Expr::ParenListExprClass:
2897 case Expr::VAArgExprClass:
2898 case Expr::AddrLabelExprClass:
2899 case Expr::StmtExprClass:
2900 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00002901 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002902 case Expr::CXXDynamicCastExprClass:
2903 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002904 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002905 case Expr::CXXNullPtrLiteralExprClass:
2906 case Expr::CXXThisExprClass:
2907 case Expr::CXXThrowExprClass:
2908 case Expr::CXXNewExprClass:
2909 case Expr::CXXDeleteExprClass:
2910 case Expr::CXXPseudoDestructorExprClass:
2911 case Expr::UnresolvedLookupExprClass:
2912 case Expr::DependentScopeDeclRefExprClass:
2913 case Expr::CXXConstructExprClass:
2914 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002915 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002916 case Expr::CXXTemporaryObjectExprClass:
2917 case Expr::CXXUnresolvedConstructExprClass:
2918 case Expr::CXXDependentScopeMemberExprClass:
2919 case Expr::UnresolvedMemberExprClass:
2920 case Expr::ObjCStringLiteralClass:
2921 case Expr::ObjCEncodeExprClass:
2922 case Expr::ObjCMessageExprClass:
2923 case Expr::ObjCSelectorExprClass:
2924 case Expr::ObjCProtocolExprClass:
2925 case Expr::ObjCIvarRefExprClass:
2926 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002927 case Expr::ObjCIsaExprClass:
2928 case Expr::ShuffleVectorExprClass:
2929 case Expr::BlockExprClass:
2930 case Expr::BlockDeclRefExprClass:
2931 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002932 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002933 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00002934 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002935 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002936 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00002937 case Expr::MaterializeTemporaryExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00002938 case Expr::AtomicExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002939 return ICEDiag(2, E->getLocStart());
2940
Sebastian Redlcea8d962011-09-24 17:48:14 +00002941 case Expr::InitListExprClass:
2942 if (Ctx.getLangOptions().CPlusPlus0x) {
2943 const InitListExpr *ILE = cast<InitListExpr>(E);
2944 if (ILE->getNumInits() == 0)
2945 return NoDiag();
2946 if (ILE->getNumInits() == 1)
2947 return CheckICE(ILE->getInit(0), Ctx);
2948 // Fall through for more than 1 expression.
2949 }
2950 return ICEDiag(2, E->getLocStart());
2951
Douglas Gregoree8aff02011-01-04 17:33:58 +00002952 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002953 case Expr::GNUNullExprClass:
2954 // GCC considers the GNU __null value to be an integral constant expression.
2955 return NoDiag();
2956
John McCall91a57552011-07-15 05:09:51 +00002957 case Expr::SubstNonTypeTemplateParmExprClass:
2958 return
2959 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
2960
John McCalld905f5a2010-05-07 05:32:02 +00002961 case Expr::ParenExprClass:
2962 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00002963 case Expr::GenericSelectionExprClass:
2964 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002965 case Expr::IntegerLiteralClass:
2966 case Expr::CharacterLiteralClass:
2967 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002968 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002969 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002970 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00002971 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00002972 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002973 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002974 return NoDiag();
2975 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002976 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002977 const CallExpr *CE = cast<CallExpr>(E);
2978 if (CE->isBuiltinCall(Ctx))
2979 return CheckEvalInICE(E, Ctx);
2980 return ICEDiag(2, E->getLocStart());
2981 }
2982 case Expr::DeclRefExprClass:
2983 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2984 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00002985 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00002986 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2987
2988 // Parameter variables are never constants. Without this check,
2989 // getAnyInitializer() can find a default argument, which leads
2990 // to chaos.
2991 if (isa<ParmVarDecl>(D))
2992 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2993
2994 // C++ 7.1.5.1p2
2995 // A variable of non-volatile const-qualified integral or enumeration
2996 // type initialized by an ICE can be used in ICEs.
2997 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCalld905f5a2010-05-07 05:32:02 +00002998 // Look for a declaration of this variable that has an initializer.
2999 const VarDecl *ID = 0;
3000 const Expr *Init = Dcl->getAnyInitializer(ID);
3001 if (Init) {
3002 if (ID->isInitKnownICE()) {
3003 // We have already checked whether this subexpression is an
3004 // integral constant expression.
3005 if (ID->isInitICE())
3006 return NoDiag();
3007 else
3008 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3009 }
3010
3011 // It's an ICE whether or not the definition we found is
3012 // out-of-line. See DR 721 and the discussion in Clang PR
3013 // 6206 for details.
3014
3015 if (Dcl->isCheckingICE()) {
3016 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3017 }
3018
3019 Dcl->setCheckingICE();
3020 ICEDiag Result = CheckICE(Init, Ctx);
3021 // Cache the result of the ICE test.
3022 Dcl->setInitKnownICE(Result.Val == 0);
3023 return Result;
3024 }
3025 }
3026 }
3027 return ICEDiag(2, E->getLocStart());
3028 case Expr::UnaryOperatorClass: {
3029 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3030 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00003031 case UO_PostInc:
3032 case UO_PostDec:
3033 case UO_PreInc:
3034 case UO_PreDec:
3035 case UO_AddrOf:
3036 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00003037 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00003038 case UO_Extension:
3039 case UO_LNot:
3040 case UO_Plus:
3041 case UO_Minus:
3042 case UO_Not:
3043 case UO_Real:
3044 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00003045 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003046 }
3047
3048 // OffsetOf falls through here.
3049 }
3050 case Expr::OffsetOfExprClass: {
3051 // Note that per C99, offsetof must be an ICE. And AFAIK, using
3052 // Evaluate matches the proposed gcc behavior for cases like
3053 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
3054 // compliance: we should warn earlier for offsetof expressions with
3055 // array subscripts that aren't ICEs, and if the array subscripts
3056 // are ICEs, the value of the offsetof must be an integer constant.
3057 return CheckEvalInICE(E, Ctx);
3058 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003059 case Expr::UnaryExprOrTypeTraitExprClass: {
3060 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3061 if ((Exp->getKind() == UETT_SizeOf) &&
3062 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00003063 return ICEDiag(2, E->getLocStart());
3064 return NoDiag();
3065 }
3066 case Expr::BinaryOperatorClass: {
3067 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3068 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00003069 case BO_PtrMemD:
3070 case BO_PtrMemI:
3071 case BO_Assign:
3072 case BO_MulAssign:
3073 case BO_DivAssign:
3074 case BO_RemAssign:
3075 case BO_AddAssign:
3076 case BO_SubAssign:
3077 case BO_ShlAssign:
3078 case BO_ShrAssign:
3079 case BO_AndAssign:
3080 case BO_XorAssign:
3081 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00003082 return ICEDiag(2, E->getLocStart());
3083
John McCall2de56d12010-08-25 11:45:40 +00003084 case BO_Mul:
3085 case BO_Div:
3086 case BO_Rem:
3087 case BO_Add:
3088 case BO_Sub:
3089 case BO_Shl:
3090 case BO_Shr:
3091 case BO_LT:
3092 case BO_GT:
3093 case BO_LE:
3094 case BO_GE:
3095 case BO_EQ:
3096 case BO_NE:
3097 case BO_And:
3098 case BO_Xor:
3099 case BO_Or:
3100 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00003101 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3102 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00003103 if (Exp->getOpcode() == BO_Div ||
3104 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00003105 // Evaluate gives an error for undefined Div/Rem, so make sure
3106 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00003107 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003108 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003109 if (REval == 0)
3110 return ICEDiag(1, E->getLocStart());
3111 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003112 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003113 if (LEval.isMinSignedValue())
3114 return ICEDiag(1, E->getLocStart());
3115 }
3116 }
3117 }
John McCall2de56d12010-08-25 11:45:40 +00003118 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00003119 if (Ctx.getLangOptions().C99) {
3120 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3121 // if it isn't evaluated.
3122 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3123 return ICEDiag(1, E->getLocStart());
3124 } else {
3125 // In both C89 and C++, commas in ICEs are illegal.
3126 return ICEDiag(2, E->getLocStart());
3127 }
3128 }
3129 if (LHSResult.Val >= RHSResult.Val)
3130 return LHSResult;
3131 return RHSResult;
3132 }
John McCall2de56d12010-08-25 11:45:40 +00003133 case BO_LAnd:
3134 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00003135 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00003136
3137 // C++0x [expr.const]p2:
3138 // [...] subexpressions of logical AND (5.14), logical OR
3139 // (5.15), and condi- tional (5.16) operations that are not
3140 // evaluated are not considered.
3141 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3142 if (Exp->getOpcode() == BO_LAnd &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003143 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregor63fe6812011-05-24 16:02:01 +00003144 return LHSResult;
3145
3146 if (Exp->getOpcode() == BO_LOr &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003147 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregor63fe6812011-05-24 16:02:01 +00003148 return LHSResult;
3149 }
3150
John McCalld905f5a2010-05-07 05:32:02 +00003151 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3152 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3153 // Rare case where the RHS has a comma "side-effect"; we need
3154 // to actually check the condition to see whether the side
3155 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00003156 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003157 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00003158 return RHSResult;
3159 return NoDiag();
3160 }
3161
3162 if (LHSResult.Val >= RHSResult.Val)
3163 return LHSResult;
3164 return RHSResult;
3165 }
3166 }
3167 }
3168 case Expr::ImplicitCastExprClass:
3169 case Expr::CStyleCastExprClass:
3170 case Expr::CXXFunctionalCastExprClass:
3171 case Expr::CXXStaticCastExprClass:
3172 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00003173 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003174 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00003175 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith32cb4712011-10-24 18:26:35 +00003176 if (E->getStmtClass() != Expr::ImplicitCastExprClass &&
3177 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3178 return NoDiag();
Eli Friedmaneea0e812011-09-29 21:49:34 +00003179 switch (cast<CastExpr>(E)->getCastKind()) {
3180 case CK_LValueToRValue:
3181 case CK_NoOp:
3182 case CK_IntegralToBoolean:
3183 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00003184 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00003185 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00003186 return ICEDiag(2, E->getLocStart());
3187 }
John McCalld905f5a2010-05-07 05:32:02 +00003188 }
John McCall56ca35d2011-02-17 10:25:35 +00003189 case Expr::BinaryConditionalOperatorClass: {
3190 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3191 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3192 if (CommonResult.Val == 2) return CommonResult;
3193 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3194 if (FalseResult.Val == 2) return FalseResult;
3195 if (CommonResult.Val == 1) return CommonResult;
3196 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003197 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00003198 return FalseResult;
3199 }
John McCalld905f5a2010-05-07 05:32:02 +00003200 case Expr::ConditionalOperatorClass: {
3201 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3202 // If the condition (ignoring parens) is a __builtin_constant_p call,
3203 // then only the true side is actually considered in an integer constant
3204 // expression, and it is fully evaluated. This is an important GNU
3205 // extension. See GCC PR38377 for discussion.
3206 if (const CallExpr *CallCE
3207 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3208 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3209 Expr::EvalResult EVResult;
3210 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3211 !EVResult.Val.isInt()) {
3212 return ICEDiag(2, E->getLocStart());
3213 }
3214 return NoDiag();
3215 }
3216 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003217 if (CondResult.Val == 2)
3218 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00003219
3220 // C++0x [expr.const]p2:
3221 // subexpressions of [...] conditional (5.16) operations that
3222 // are not evaluated are not considered
3223 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003224 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregor63fe6812011-05-24 16:02:01 +00003225 : false;
3226 ICEDiag TrueResult = NoDiag();
3227 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3228 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3229 ICEDiag FalseResult = NoDiag();
3230 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3231 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3232
John McCalld905f5a2010-05-07 05:32:02 +00003233 if (TrueResult.Val == 2)
3234 return TrueResult;
3235 if (FalseResult.Val == 2)
3236 return FalseResult;
3237 if (CondResult.Val == 1)
3238 return CondResult;
3239 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3240 return NoDiag();
3241 // Rare case where the diagnostics depend on which side is evaluated
3242 // Note that if we get here, CondResult is 0, and at least one of
3243 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003244 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00003245 return FalseResult;
3246 }
3247 return TrueResult;
3248 }
3249 case Expr::CXXDefaultArgExprClass:
3250 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3251 case Expr::ChooseExprClass: {
3252 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3253 }
3254 }
3255
3256 // Silence a GCC warning
3257 return ICEDiag(2, E->getLocStart());
3258}
3259
3260bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3261 SourceLocation *Loc, bool isEvaluated) const {
3262 ICEDiag d = CheckICE(this, Ctx);
3263 if (d.Val != 0) {
3264 if (Loc) *Loc = d.Loc;
3265 return false;
3266 }
Richard Smith41bf4f32011-10-24 21:07:08 +00003267 if (!EvaluateAsInt(Result, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00003268 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00003269 return true;
3270}