blob: 6e2e15c6cb6bea51e525d20e20173aa01b907a0a [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Richard Smith254a73d2011-10-28 22:34:42 +000046 struct CallStackFrame;
47
Benjamin Kramer024e6192011-03-04 13:12:48 +000048 struct EvalInfo {
49 const ASTContext &Ctx;
50
Richard Smith725810a2011-10-16 21:26:27 +000051 /// EvalStatus - Contains information about the evaluation.
52 Expr::EvalStatus &EvalStatus;
Benjamin Kramer024e6192011-03-04 13:12:48 +000053
Richard Smith254a73d2011-10-28 22:34:42 +000054 /// CurrentCall - The top of the constexpr call stack.
55 const CallStackFrame *CurrentCall;
56
57 /// NumCalls - The number of calls we've evaluated so far.
58 unsigned NumCalls;
59
60 /// CallStackDepth - The number of calls in the call stack right now.
61 unsigned CallStackDepth;
62
Benjamin Kramer024e6192011-03-04 13:12:48 +000063 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
64 MapTy OpaqueValues;
65 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
66 MapTy::const_iterator i = OpaqueValues.find(e);
67 if (i == OpaqueValues.end()) return 0;
68 return &i->second;
69 }
70
Richard Smith725810a2011-10-16 21:26:27 +000071 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith254a73d2011-10-28 22:34:42 +000072 : Ctx(C), EvalStatus(S), CurrentCall(0), NumCalls(0), CallStackDepth(0) {}
Richard Smith4ce706a2011-10-11 21:43:33 +000073
74 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
Benjamin Kramer024e6192011-03-04 13:12:48 +000075 };
76
Richard Smith254a73d2011-10-28 22:34:42 +000077 /// A stack frame in the constexpr call stack.
78 struct CallStackFrame {
79 EvalInfo &Info;
80
81 /// Parent - The caller of this stack frame.
82 const CallStackFrame *Caller;
83
84 /// ParmBindings - Parameter bindings for this function call, indexed by
85 /// parameters' function scope indices.
86 const APValue *Arguments;
87
88 /// CallIndex - The index of the current call. This is used to match lvalues
89 /// referring to parameters up with the corresponding stack frame, and to
90 /// detect when the parameter is no longer in scope.
91 unsigned CallIndex;
92
93 CallStackFrame(EvalInfo &Info, const APValue *Arguments)
94 : Info(Info), Caller(Info.CurrentCall), Arguments(Arguments),
95 CallIndex(Info.NumCalls++) {
96 Info.CurrentCall = this;
97 ++Info.CallStackDepth;
98 }
99 ~CallStackFrame() {
100 assert(Info.CurrentCall == this && "calls retired out of order");
101 --Info.CallStackDepth;
102 Info.CurrentCall = Caller;
103 }
104 };
105
John McCall93d91dc2010-05-07 17:22:02 +0000106 struct ComplexValue {
107 private:
108 bool IsInt;
109
110 public:
111 APSInt IntReal, IntImag;
112 APFloat FloatReal, FloatImag;
113
114 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
115
116 void makeComplexFloat() { IsInt = false; }
117 bool isComplexFloat() const { return !IsInt; }
118 APFloat &getComplexFloatReal() { return FloatReal; }
119 APFloat &getComplexFloatImag() { return FloatImag; }
120
121 void makeComplexInt() { IsInt = true; }
122 bool isComplexInt() const { return IsInt; }
123 APSInt &getComplexIntReal() { return IntReal; }
124 APSInt &getComplexIntImag() { return IntImag; }
125
John McCallc07a0c72011-02-17 10:25:35 +0000126 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000127 if (isComplexFloat())
128 v = APValue(FloatReal, FloatImag);
129 else
130 v = APValue(IntReal, IntImag);
131 }
John McCallc07a0c72011-02-17 10:25:35 +0000132 void setFrom(const APValue &v) {
133 assert(v.isComplexFloat() || v.isComplexInt());
134 if (v.isComplexFloat()) {
135 makeComplexFloat();
136 FloatReal = v.getComplexFloatReal();
137 FloatImag = v.getComplexFloatImag();
138 } else {
139 makeComplexInt();
140 IntReal = v.getComplexIntReal();
141 IntImag = v.getComplexIntImag();
142 }
143 }
John McCall93d91dc2010-05-07 17:22:02 +0000144 };
John McCall45d55e42010-05-07 21:00:08 +0000145
146 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000147 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000148 CharUnits Offset;
149
Peter Collingbournee9200682011-05-13 03:29:01 +0000150 const Expr *getLValueBase() { return Base; }
John McCall45d55e42010-05-07 21:00:08 +0000151 CharUnits getLValueOffset() { return Offset; }
152
John McCallc07a0c72011-02-17 10:25:35 +0000153 void moveInto(APValue &v) const {
John McCall45d55e42010-05-07 21:00:08 +0000154 v = APValue(Base, Offset);
155 }
John McCallc07a0c72011-02-17 10:25:35 +0000156 void setFrom(const APValue &v) {
157 assert(v.isLValue());
158 Base = v.getLValueBase();
159 Offset = v.getLValueOffset();
160 }
John McCall45d55e42010-05-07 21:00:08 +0000161 };
John McCall93d91dc2010-05-07 17:22:02 +0000162}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000163
Richard Smith725810a2011-10-16 21:26:27 +0000164static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000165static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
166static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000167static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattner6c4d2552009-10-28 23:59:40 +0000168static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
169 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000170static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000171static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000172
173//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000174// Misc utilities
175//===----------------------------------------------------------------------===//
176
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000177static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000178 if (!E) return true;
179
180 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
181 if (isa<FunctionDecl>(DRE->getDecl()))
182 return true;
183 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
184 return VD->hasGlobalStorage();
185 return false;
186 }
187
188 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
189 return CLE->isFileScope();
190
Richard Smith11562c52011-10-28 17:51:58 +0000191 if (isa<MemberExpr>(E))
192 return false;
193
John McCall95007602010-05-10 23:27:23 +0000194 return true;
195}
196
Richard Smith11562c52011-10-28 17:51:58 +0000197static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCall45d55e42010-05-07 21:00:08 +0000198 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000199
John McCalleb3e4f32010-05-07 21:34:32 +0000200 // A null base expression indicates a null pointer. These are always
201 // evaluatable, and they are false unless the offset is zero.
202 if (!Base) {
203 Result = !Value.Offset.isZero();
204 return true;
205 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000206
John McCall95007602010-05-10 23:27:23 +0000207 // Require the base expression to be a global l-value.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000208 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000209
John McCalleb3e4f32010-05-07 21:34:32 +0000210 // We have a non-null base expression. These are generally known to
211 // be true, but if it'a decl-ref to a weak symbol it can be null at
212 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000213 Result = true;
214
215 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000216 if (!DeclRef)
217 return true;
218
John McCalleb3e4f32010-05-07 21:34:32 +0000219 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000220 const ValueDecl* Decl = DeclRef->getDecl();
221 if (Decl->hasAttr<WeakAttr>() ||
222 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000223 Decl->isWeakImported())
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000224 return false;
225
Eli Friedman334046a2009-06-14 02:17:33 +0000226 return true;
227}
228
Richard Smith11562c52011-10-28 17:51:58 +0000229static bool HandleConversionToBool(const APValue &Val, bool &Result) {
230 switch (Val.getKind()) {
231 case APValue::Uninitialized:
232 return false;
233 case APValue::Int:
234 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000235 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000236 case APValue::Float:
237 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000238 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000239 case APValue::ComplexInt:
240 Result = Val.getComplexIntReal().getBoolValue() ||
241 Val.getComplexIntImag().getBoolValue();
242 return true;
243 case APValue::ComplexFloat:
244 Result = !Val.getComplexFloatReal().isZero() ||
245 !Val.getComplexFloatImag().isZero();
246 return true;
247 case APValue::LValue:
248 {
249 LValue PointerResult;
250 PointerResult.setFrom(Val);
251 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedman64004332009-03-23 04:38:34 +0000252 }
Richard Smith11562c52011-10-28 17:51:58 +0000253 case APValue::Vector:
254 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000255 }
256
Richard Smith11562c52011-10-28 17:51:58 +0000257 llvm_unreachable("unknown APValue kind");
258}
259
260static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
261 EvalInfo &Info) {
262 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
263 APValue Val;
264 if (!Evaluate(Val, Info, E))
265 return false;
266 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000267}
268
Mike Stump11289f42009-09-09 15:08:12 +0000269static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000270 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000271 unsigned DestWidth = Ctx.getIntWidth(DestType);
272 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000273 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000274
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000275 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000276 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000277 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000278 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
279 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000280}
281
Mike Stump11289f42009-09-09 15:08:12 +0000282static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000283 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000284 bool ignored;
285 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000286 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000287 APFloat::rmNearestTiesToEven, &ignored);
288 return Result;
289}
290
Mike Stump11289f42009-09-09 15:08:12 +0000291static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000292 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000293 unsigned DestWidth = Ctx.getIntWidth(DestType);
294 APSInt Result = Value;
295 // Figure out if this is a truncate, extend or noop cast.
296 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000297 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000298 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000299 return Result;
300}
301
Mike Stump11289f42009-09-09 15:08:12 +0000302static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000303 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000304
305 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
306 Result.convertFromAPInt(Value, Value.isSigned(),
307 APFloat::rmNearestTiesToEven);
308 return Result;
309}
310
Richard Smith27908702011-10-24 17:54:18 +0000311/// Try to evaluate the initializer for a variable declaration.
Richard Smith254a73d2011-10-28 22:34:42 +0000312static const APValue *EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD) {
313 // If this is a parameter to an active constexpr function call, perform
314 // argument substitution.
315 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
316 // FIXME This assumes that all parameters must be parameters of the current
317 // call. Add the CallIndex to the LValue representation and use that to
318 // check.
319 if (Info.CurrentCall)
320 return &Info.CurrentCall->Arguments[PVD->getFunctionScopeIndex()];
Richard Smith27908702011-10-24 17:54:18 +0000321 return 0;
Richard Smith254a73d2011-10-28 22:34:42 +0000322 }
Richard Smith27908702011-10-24 17:54:18 +0000323
324 const Expr *Init = VD->getAnyInitializer();
325 if (!Init)
326 return 0;
327
328 if (APValue *V = VD->getEvaluatedValue())
329 return V;
330
331 if (VD->isEvaluatingValue())
332 return 0;
333
334 VD->setEvaluatingValue();
335
Richard Smith27908702011-10-24 17:54:18 +0000336 Expr::EvalResult EResult;
Richard Smith11562c52011-10-28 17:51:58 +0000337 EvalInfo InitInfo(Info.Ctx, EResult);
338 // FIXME: The caller will need to know whether the value was a constant
339 // expression. If not, we should propagate up a diagnostic.
340 if (Evaluate(EResult.Val, InitInfo, Init))
Richard Smith27908702011-10-24 17:54:18 +0000341 VD->setEvaluatedValue(EResult.Val);
342 else
343 VD->setEvaluatedValue(APValue());
344
345 return VD->getEvaluatedValue();
346}
347
Richard Smith11562c52011-10-28 17:51:58 +0000348static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000349 Qualifiers Quals = T.getQualifiers();
350 return Quals.hasConst() && !Quals.hasVolatile();
351}
352
Richard Smith11562c52011-10-28 17:51:58 +0000353bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
354 const LValue &LVal, APValue &RVal) {
355 const Expr *Base = LVal.Base;
356
357 // FIXME: Indirection through a null pointer deserves a diagnostic.
358 if (!Base)
359 return false;
360
361 // FIXME: Support accessing subobjects of objects of literal types. A simple
362 // byte offset is insufficient for C++11 semantics: we need to know how the
363 // reference was formed (which union member was named, for instance).
364 // FIXME: Support subobjects of StringLiteral and PredefinedExpr.
365 if (!LVal.Offset.isZero())
366 return false;
367
368 const Decl *D = 0;
369
370 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
371 // If the lvalue has been cast to some other type, don't try to read it.
372 // FIXME: Could simulate a bitcast here.
373 if (!Info.Ctx.hasSameUnqualifiedType(Type, DRE->getType()))
374 return false;
375 D = DRE->getDecl();
376 }
377
378 // FIXME: Static data members accessed via a MemberExpr are represented as
379 // that MemberExpr. We should use the Decl directly instead.
380 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
381 if (!Info.Ctx.hasSameUnqualifiedType(Type, ME->getType()))
382 return false;
383 D = ME->getMemberDecl();
384 assert(!isa<FieldDecl>(D) && "shouldn't see fields here");
385 }
386
387 if (D) {
388 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
389 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +0000390 // expressions are constant expressions too. Inside constexpr functions,
391 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +0000392 // In C, such things can also be folded, although they are not ICEs.
393 //
394 // FIXME: Allow folding any const variable of literal type initialized with
395 // a constant expression. For now, we only allow variables with integral and
396 // floating types to be folded.
Richard Smith254a73d2011-10-28 22:34:42 +0000397 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
398 // interpretation of C++11 suggests that volatile parameters are OK if
399 // they're never read (there's no prohibition against constructing volatile
400 // objects in constant expressions), but lvalue-to-rvalue conversions on
401 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +0000402 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith254a73d2011-10-28 22:34:42 +0000403 if (!VD || !(IsConstNonVolatile(VD->getType()) || isa<ParmVarDecl>(VD)) ||
404 !(Type->isIntegralOrEnumerationType() || Type->isRealFloatingType()))
Richard Smith11562c52011-10-28 17:51:58 +0000405 return false;
406
Richard Smith254a73d2011-10-28 22:34:42 +0000407 const APValue *V = EvaluateVarDeclInit(Info, VD);
Richard Smith11562c52011-10-28 17:51:58 +0000408 if (!V || V->isUninit())
409 return false;
410
Richard Smith254a73d2011-10-28 22:34:42 +0000411 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue()) {
Richard Smith11562c52011-10-28 17:51:58 +0000412 RVal = *V;
413 return true;
414 }
415
416 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
417 // conversion. This happens when the declaration and the lvalue should be
418 // considered synonymous, for instance when initializing an array of char
419 // from a string literal. Continue as if the initializer lvalue was the
420 // value we were originally given.
421 Base = V->getLValueBase();
422 if (!V->getLValueOffset().isZero())
423 return false;
424 }
425
426 // FIXME: C++11: Support MaterializeTemporaryExpr in LValueExprEvaluator and
427 // here.
428
429 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
430 // initializer until now for such expressions. Such an expression can't be
431 // an ICE in C, so this only matters for fold.
432 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
433 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
434 return Evaluate(RVal, Info, CLE->getInitializer());
435 }
436
437 return false;
438}
439
Mike Stump876387b2009-10-27 22:09:17 +0000440namespace {
Richard Smith254a73d2011-10-28 22:34:42 +0000441enum EvalStmtResult {
442 /// Evaluation failed.
443 ESR_Failed,
444 /// Hit a 'return' statement.
445 ESR_Returned,
446 /// Evaluation succeeded.
447 ESR_Succeeded
448};
449}
450
451// Evaluate a statement.
452static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
453 const Stmt *S) {
454 switch (S->getStmtClass()) {
455 default:
456 return ESR_Failed;
457
458 case Stmt::NullStmtClass:
459 case Stmt::DeclStmtClass:
460 return ESR_Succeeded;
461
462 case Stmt::ReturnStmtClass:
463 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
464 return ESR_Returned;
465 return ESR_Failed;
466
467 case Stmt::CompoundStmtClass: {
468 const CompoundStmt *CS = cast<CompoundStmt>(S);
469 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
470 BE = CS->body_end(); BI != BE; ++BI) {
471 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
472 if (ESR != ESR_Succeeded)
473 return ESR;
474 }
475 return ESR_Succeeded;
476 }
477 }
478}
479
480/// Evaluate a function call.
481static bool HandleFunctionCall(ArrayRef<const Expr*> Args, const Stmt *Body,
482 EvalInfo &Info, APValue &Result) {
483 // FIXME: Implement a proper call limit, along with a command-line flag.
484 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
485 return false;
486
487 SmallVector<APValue, 16> ArgValues(Args.size());
488 // FIXME: Deal with default arguments and 'this'.
489 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
490 I != E; ++I)
491 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
492 return false;
493
494 CallStackFrame Frame(Info, ArgValues.data());
495 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
496}
497
498namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000499class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000500 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000501 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000502public:
503
Richard Smith725810a2011-10-16 21:26:27 +0000504 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000505
506 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000507 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000508 return true;
509 }
510
Peter Collingbournee9200682011-05-13 03:29:01 +0000511 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
512 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000513 return Visit(E->getResultExpr());
514 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000515 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000516 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000517 return true;
518 return false;
519 }
John McCall31168b02011-06-15 23:02:42 +0000520 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000521 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000522 return true;
523 return false;
524 }
525 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000526 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000527 return true;
528 return false;
529 }
530
Mike Stump876387b2009-10-27 22:09:17 +0000531 // We don't want to evaluate BlockExprs multiple times, as they generate
532 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000533 bool VisitBlockExpr(const BlockExpr *E) { return true; }
534 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
535 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000536 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000537 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
538 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
539 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
540 bool VisitStringLiteral(const StringLiteral *E) { return false; }
541 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
542 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000543 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000544 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000545 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000546 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000547 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000548 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
549 bool VisitBinAssign(const BinaryOperator *E) { return true; }
550 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
551 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000552 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000553 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
554 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
555 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
556 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
557 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000558 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000559 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000560 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000561 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000562 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000563
564 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000565 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000566 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
567 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000568 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000569 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000570 return false;
571 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000572
Peter Collingbournee9200682011-05-13 03:29:01 +0000573 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000574};
575
John McCallc07a0c72011-02-17 10:25:35 +0000576class OpaqueValueEvaluation {
577 EvalInfo &info;
578 OpaqueValueExpr *opaqueValue;
579
580public:
581 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
582 Expr *value)
583 : info(info), opaqueValue(opaqueValue) {
584
585 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000586 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000587 this->opaqueValue = 0;
588 return;
589 }
John McCallc07a0c72011-02-17 10:25:35 +0000590 }
591
592 bool hasError() const { return opaqueValue == 0; }
593
594 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000595 // FIXME: This will not work for recursive constexpr functions using opaque
596 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000597 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
598 }
599};
600
Mike Stump876387b2009-10-27 22:09:17 +0000601} // end anonymous namespace
602
Eli Friedman9a156e52008-11-12 09:44:48 +0000603//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000604// Generic Evaluation
605//===----------------------------------------------------------------------===//
606namespace {
607
608template <class Derived, typename RetTy=void>
609class ExprEvaluatorBase
610 : public ConstStmtVisitor<Derived, RetTy> {
611private:
612 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
613 return static_cast<Derived*>(this)->Success(V, E);
614 }
615 RetTy DerivedError(const Expr *E) {
616 return static_cast<Derived*>(this)->Error(E);
617 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000618 RetTy DerivedValueInitialization(const Expr *E) {
619 return static_cast<Derived*>(this)->ValueInitialization(E);
620 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000621
622protected:
623 EvalInfo &Info;
624 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
625 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
626
Richard Smith4ce706a2011-10-11 21:43:33 +0000627 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
628
Peter Collingbournee9200682011-05-13 03:29:01 +0000629public:
630 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
631
632 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000633 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000634 }
635 RetTy VisitExpr(const Expr *E) {
636 return DerivedError(E);
637 }
638
639 RetTy VisitParenExpr(const ParenExpr *E)
640 { return StmtVisitorTy::Visit(E->getSubExpr()); }
641 RetTy VisitUnaryExtension(const UnaryOperator *E)
642 { return StmtVisitorTy::Visit(E->getSubExpr()); }
643 RetTy VisitUnaryPlus(const UnaryOperator *E)
644 { return StmtVisitorTy::Visit(E->getSubExpr()); }
645 RetTy VisitChooseExpr(const ChooseExpr *E)
646 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
647 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
648 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000649 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
650 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000651
652 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
653 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
654 if (opaque.hasError())
655 return DerivedError(E);
656
657 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +0000658 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000659 return DerivedError(E);
660
661 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
662 }
663
664 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
665 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +0000666 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000667 return DerivedError(E);
668
Richard Smith11562c52011-10-28 17:51:58 +0000669 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +0000670 return StmtVisitorTy::Visit(EvalExpr);
671 }
672
673 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
674 const APValue *value = Info.getOpaqueValue(E);
675 if (!value)
676 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
677 : DerivedError(E));
678 return DerivedSuccess(*value, E);
679 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000680
Richard Smith254a73d2011-10-28 22:34:42 +0000681 RetTy VisitCallExpr(const CallExpr *E) {
682 const Expr *Callee = E->getCallee();
683 QualType CalleeType = Callee->getType();
684
685 // FIXME: Handle the case where Callee is a (parenthesized) MemberExpr for a
686 // non-static member function.
687 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember))
688 return DerivedError(E);
689
690 if (!CalleeType->isFunctionType() && !CalleeType->isFunctionPointerType())
691 return DerivedError(E);
692
693 APValue Call;
694 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
695 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
696 return DerivedError(Callee);
697
698 const FunctionDecl *FD = 0;
699 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Call.getLValueBase()))
700 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
701 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Call.getLValueBase()))
702 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
703 if (!FD)
704 return DerivedError(Callee);
705
706 // Don't call function pointers which have been cast to some other type.
707 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
708 return DerivedError(E);
709
710 const FunctionDecl *Definition;
711 Stmt *Body = FD->getBody(Definition);
712 APValue Result;
713 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
714
715 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
716 HandleFunctionCall(Args, Body, Info, Result))
717 return DerivedSuccess(Result, E);
718
719 return DerivedError(E);
720 }
721
Richard Smith11562c52011-10-28 17:51:58 +0000722 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
723 return StmtVisitorTy::Visit(E->getInitializer());
724 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000725 RetTy VisitInitListExpr(const InitListExpr *E) {
726 if (Info.getLangOpts().CPlusPlus0x) {
727 if (E->getNumInits() == 0)
728 return DerivedValueInitialization(E);
729 if (E->getNumInits() == 1)
730 return StmtVisitorTy::Visit(E->getInit(0));
731 }
732 return DerivedError(E);
733 }
734 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
735 return DerivedValueInitialization(E);
736 }
737 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
738 return DerivedValueInitialization(E);
739 }
740
Richard Smith11562c52011-10-28 17:51:58 +0000741 RetTy VisitCastExpr(const CastExpr *E) {
742 switch (E->getCastKind()) {
743 default:
744 break;
745
746 case CK_NoOp:
747 return StmtVisitorTy::Visit(E->getSubExpr());
748
749 case CK_LValueToRValue: {
750 LValue LVal;
751 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
752 APValue RVal;
753 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
754 return DerivedSuccess(RVal, E);
755 }
756 break;
757 }
758 }
759
760 return DerivedError(E);
761 }
762
Richard Smith4a678122011-10-24 18:44:57 +0000763 /// Visit a value which is evaluated, but whose value is ignored.
764 void VisitIgnoredValue(const Expr *E) {
765 APValue Scratch;
766 if (!Evaluate(Scratch, Info, E))
767 Info.EvalStatus.HasSideEffects = true;
768 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000769};
770
771}
772
773//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000774// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +0000775//
776// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
777// function designators (in C), decl references to void objects (in C), and
778// temporaries (if building with -Wno-address-of-temporary).
779//
780// LValue evaluation produces values comprising a base expression of one of the
781// following types:
782// * DeclRefExpr
783// * MemberExpr for a static member
784// * CompoundLiteralExpr in C
785// * StringLiteral
786// * PredefinedExpr
787// * ObjCEncodeExpr
788// * AddrLabelExpr
789// * BlockExpr
790// * CallExpr for a MakeStringConstant builtin
791// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +0000792//===----------------------------------------------------------------------===//
793namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000794class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000795 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000796 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000797 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000798
Peter Collingbournee9200682011-05-13 03:29:01 +0000799 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000800 Result.Base = E;
801 Result.Offset = CharUnits::Zero();
802 return true;
803 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000804public:
Mike Stump11289f42009-09-09 15:08:12 +0000805
John McCall45d55e42010-05-07 21:00:08 +0000806 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000807 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000808
Peter Collingbournee9200682011-05-13 03:29:01 +0000809 bool Success(const APValue &V, const Expr *E) {
810 Result.setFrom(V);
811 return true;
812 }
813 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000814 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000815 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000816
Richard Smith11562c52011-10-28 17:51:58 +0000817 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
818
Peter Collingbournee9200682011-05-13 03:29:01 +0000819 bool VisitDeclRefExpr(const DeclRefExpr *E);
820 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
821 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
822 bool VisitMemberExpr(const MemberExpr *E);
823 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
824 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
825 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
826 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000827
Peter Collingbournee9200682011-05-13 03:29:01 +0000828 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000829 switch (E->getCastKind()) {
830 default:
Richard Smith11562c52011-10-28 17:51:58 +0000831 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000832
Eli Friedmance3e02a2011-10-11 00:13:24 +0000833 case CK_LValueBitCast:
Anders Carlssonde55f642009-10-03 16:30:22 +0000834 return Visit(E->getSubExpr());
Eli Friedmance3e02a2011-10-11 00:13:24 +0000835
Richard Smith11562c52011-10-28 17:51:58 +0000836 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
837 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlssonde55f642009-10-03 16:30:22 +0000838 }
839 }
Sebastian Redl12757ab2011-09-24 17:48:14 +0000840
Eli Friedman449fe542009-03-23 04:56:01 +0000841 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000842
Eli Friedman9a156e52008-11-12 09:44:48 +0000843};
844} // end anonymous namespace
845
Richard Smith11562c52011-10-28 17:51:58 +0000846/// Evaluate an expression as an lvalue. This can be legitimately called on
847/// expressions which are not glvalues, in a few cases:
848/// * function designators in C,
849/// * "extern void" objects,
850/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +0000851static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +0000852 assert((E->isGLValue() || E->getType()->isFunctionType() ||
853 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
854 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +0000855 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000856}
857
Peter Collingbournee9200682011-05-13 03:29:01 +0000858bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000859 if (isa<FunctionDecl>(E->getDecl()))
John McCall45d55e42010-05-07 21:00:08 +0000860 return Success(E);
Richard Smith11562c52011-10-28 17:51:58 +0000861 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
862 return VisitVarDecl(E, VD);
863 return Error(E);
864}
Richard Smith733237d2011-10-24 23:14:33 +0000865
Richard Smith11562c52011-10-28 17:51:58 +0000866bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
867 if (!VD->getType()->isReferenceType())
868 return Success(E);
Eli Friedman751aa72b72009-05-27 06:04:58 +0000869
Richard Smith254a73d2011-10-28 22:34:42 +0000870 const APValue *V = EvaluateVarDeclInit(Info, VD);
Richard Smith11562c52011-10-28 17:51:58 +0000871 if (V && !V->isUninit())
872 return Success(*V, E);
873
874 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000875}
876
Peter Collingbournee9200682011-05-13 03:29:01 +0000877bool
878LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000879 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
880 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
881 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +0000882 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000883}
884
Peter Collingbournee9200682011-05-13 03:29:01 +0000885bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000886 // Handle static data members.
887 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
888 VisitIgnoredValue(E->getBase());
889 return VisitVarDecl(E, VD);
890 }
891
Richard Smith254a73d2011-10-28 22:34:42 +0000892 // Handle static member functions.
893 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
894 if (MD->isStatic()) {
895 VisitIgnoredValue(E->getBase());
896 return Success(E);
897 }
898 }
899
Eli Friedman9a156e52008-11-12 09:44:48 +0000900 QualType Ty;
901 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000902 if (!EvaluatePointer(E->getBase(), Result, Info))
903 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000904 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000905 } else {
John McCall45d55e42010-05-07 21:00:08 +0000906 if (!Visit(E->getBase()))
907 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000908 Ty = E->getBase()->getType();
909 }
910
Peter Collingbournee9200682011-05-13 03:29:01 +0000911 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000912 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000913
Peter Collingbournee9200682011-05-13 03:29:01 +0000914 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000915 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +0000916 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000917
918 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000919 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000920
Eli Friedmana3c122d2011-07-07 01:54:01 +0000921 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +0000922 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +0000923 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000924}
925
Peter Collingbournee9200682011-05-13 03:29:01 +0000926bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000927 // FIXME: Deal with vectors as array subscript bases.
928 if (E->getBase()->getType()->isVectorType())
929 return false;
930
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000931 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +0000932 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000933
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000934 APSInt Index;
935 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +0000936 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000937
Ken Dyck40775002010-01-11 17:06:35 +0000938 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +0000939 Result.Offset += Index.getSExtValue() * ElementSize;
940 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000941}
Eli Friedman9a156e52008-11-12 09:44:48 +0000942
Peter Collingbournee9200682011-05-13 03:29:01 +0000943bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +0000944 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +0000945}
946
Eli Friedman9a156e52008-11-12 09:44:48 +0000947//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000948// Pointer Evaluation
949//===----------------------------------------------------------------------===//
950
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000951namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000952class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000953 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000954 LValue &Result;
955
Peter Collingbournee9200682011-05-13 03:29:01 +0000956 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000957 Result.Base = E;
958 Result.Offset = CharUnits::Zero();
959 return true;
960 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000961public:
Mike Stump11289f42009-09-09 15:08:12 +0000962
John McCall45d55e42010-05-07 21:00:08 +0000963 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000964 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000965
Peter Collingbournee9200682011-05-13 03:29:01 +0000966 bool Success(const APValue &V, const Expr *E) {
967 Result.setFrom(V);
968 return true;
969 }
970 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +0000971 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000972 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000973 bool ValueInitialization(const Expr *E) {
974 return Success((Expr*)0);
975 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000976
John McCall45d55e42010-05-07 21:00:08 +0000977 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000978 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +0000979 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000980 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +0000981 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000982 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000983 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000984 bool VisitCallExpr(const CallExpr *E);
985 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +0000986 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +0000987 return Success(E);
988 return false;
Mike Stumpa6703322009-02-19 22:01:56 +0000989 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000990 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +0000991 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +0000992
Eli Friedman449fe542009-03-23 04:56:01 +0000993 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000994};
Chris Lattner05706e882008-07-11 18:11:29 +0000995} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000996
John McCall45d55e42010-05-07 21:00:08 +0000997static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +0000998 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +0000999 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00001000}
1001
John McCall45d55e42010-05-07 21:00:08 +00001002bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001003 if (E->getOpcode() != BO_Add &&
1004 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +00001005 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001006
Chris Lattner05706e882008-07-11 18:11:29 +00001007 const Expr *PExp = E->getLHS();
1008 const Expr *IExp = E->getRHS();
1009 if (IExp->getType()->isPointerType())
1010 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00001011
John McCall45d55e42010-05-07 21:00:08 +00001012 if (!EvaluatePointer(PExp, Result, Info))
1013 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001014
John McCall45d55e42010-05-07 21:00:08 +00001015 llvm::APSInt Offset;
1016 if (!EvaluateInteger(IExp, Offset, Info))
1017 return false;
1018 int64_t AdditionalOffset
1019 = Offset.isSigned() ? Offset.getSExtValue()
1020 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +00001021
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001022 // Compute the new offset in the appropriate width.
1023
1024 QualType PointeeType =
1025 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +00001026 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +00001027
Anders Carlssonef56fba2009-02-19 04:55:58 +00001028 // Explicitly handle GNU void* and function pointer arithmetic extensions.
1029 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +00001030 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +00001031 else
John McCall45d55e42010-05-07 21:00:08 +00001032 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +00001033
John McCalle3027922010-08-25 11:45:40 +00001034 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +00001035 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +00001036 else
John McCall45d55e42010-05-07 21:00:08 +00001037 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +00001038
John McCall45d55e42010-05-07 21:00:08 +00001039 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001040}
Eli Friedman9a156e52008-11-12 09:44:48 +00001041
John McCall45d55e42010-05-07 21:00:08 +00001042bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1043 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001044}
Mike Stump11289f42009-09-09 15:08:12 +00001045
Chris Lattner05706e882008-07-11 18:11:29 +00001046
Peter Collingbournee9200682011-05-13 03:29:01 +00001047bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1048 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00001049
Eli Friedman847a2bc2009-12-27 05:43:15 +00001050 switch (E->getCastKind()) {
1051 default:
1052 break;
1053
John McCalle3027922010-08-25 11:45:40 +00001054 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00001055 case CK_CPointerToObjCPointerCast:
1056 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001057 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +00001058 return Visit(SubExpr);
1059
Anders Carlsson18275092010-10-31 20:41:46 +00001060 case CK_DerivedToBase:
1061 case CK_UncheckedDerivedToBase: {
1062 LValue BaseLV;
1063 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
1064 return false;
1065
1066 // Now figure out the necessary offset to add to the baseLV to get from
1067 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +00001068 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +00001069
1070 QualType Ty = E->getSubExpr()->getType();
1071 const CXXRecordDecl *DerivedDecl =
1072 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
1073
1074 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1075 PathE = E->path_end(); PathI != PathE; ++PathI) {
1076 const CXXBaseSpecifier *Base = *PathI;
1077
1078 // FIXME: If the base is virtual, we'd need to determine the type of the
1079 // most derived class and we don't support that right now.
1080 if (Base->isVirtual())
1081 return false;
1082
1083 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1084 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1085
Ken Dyck02155cb2011-01-26 02:17:08 +00001086 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +00001087 DerivedDecl = BaseDecl;
1088 }
1089
1090 Result.Base = BaseLV.getLValueBase();
Ken Dyck02155cb2011-01-26 02:17:08 +00001091 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson18275092010-10-31 20:41:46 +00001092 return true;
1093 }
1094
John McCalle84af4e2010-11-13 01:35:44 +00001095 case CK_NullToPointer: {
1096 Result.Base = 0;
1097 Result.Offset = CharUnits::Zero();
1098 return true;
1099 }
1100
John McCalle3027922010-08-25 11:45:40 +00001101 case CK_IntegralToPointer: {
John McCall45d55e42010-05-07 21:00:08 +00001102 APValue Value;
1103 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00001104 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00001105
John McCall45d55e42010-05-07 21:00:08 +00001106 if (Value.isInt()) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00001107 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCall45d55e42010-05-07 21:00:08 +00001108 Result.Base = 0;
1109 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
1110 return true;
1111 } else {
1112 // Cast is of an lvalue, no need to change value.
1113 Result.Base = Value.getLValueBase();
1114 Result.Offset = Value.getLValueOffset();
1115 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001116 }
1117 }
John McCalle3027922010-08-25 11:45:40 +00001118 case CK_ArrayToPointerDecay:
1119 case CK_FunctionToPointerDecay:
John McCall45d55e42010-05-07 21:00:08 +00001120 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001121 }
1122
Richard Smith11562c52011-10-28 17:51:58 +00001123 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00001124}
Chris Lattner05706e882008-07-11 18:11:29 +00001125
Peter Collingbournee9200682011-05-13 03:29:01 +00001126bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +00001127 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +00001128 Builtin::BI__builtin___CFStringMakeConstantString ||
1129 E->isBuiltinCall(Info.Ctx) ==
1130 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +00001131 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00001132
Peter Collingbournee9200682011-05-13 03:29:01 +00001133 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001134}
Chris Lattner05706e882008-07-11 18:11:29 +00001135
1136//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001137// Vector Evaluation
1138//===----------------------------------------------------------------------===//
1139
1140namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001141 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00001142 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1143 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001144 public:
Mike Stump11289f42009-09-09 15:08:12 +00001145
Richard Smith2d406342011-10-22 21:10:00 +00001146 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1147 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001148
Richard Smith2d406342011-10-22 21:10:00 +00001149 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1150 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1151 // FIXME: remove this APValue copy.
1152 Result = APValue(V.data(), V.size());
1153 return true;
1154 }
1155 bool Success(const APValue &V, const Expr *E) {
1156 Result = V;
1157 return true;
1158 }
1159 bool Error(const Expr *E) { return false; }
1160 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00001161
Richard Smith2d406342011-10-22 21:10:00 +00001162 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00001163 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00001164 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00001165 bool VisitInitListExpr(const InitListExpr *E);
1166 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001167 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001168 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00001169 // shufflevector, ExtVectorElementExpr
1170 // (Note that these require implementing conversions
1171 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001172 };
1173} // end anonymous namespace
1174
1175static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001176 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00001177 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001178}
1179
Richard Smith2d406342011-10-22 21:10:00 +00001180bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1181 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001182 QualType EltTy = VTy->getElementType();
1183 unsigned NElts = VTy->getNumElements();
1184 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +00001185
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001186 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00001187 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001188
Eli Friedmanc757de22011-03-25 00:43:55 +00001189 switch (E->getCastKind()) {
1190 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00001191 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00001192 if (SETy->isIntegerType()) {
1193 APSInt IntResult;
1194 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001195 return Error(E);
1196 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00001197 } else if (SETy->isRealFloatingType()) {
1198 APFloat F(0.0);
1199 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001200 return Error(E);
1201 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00001202 } else {
Richard Smith2d406342011-10-22 21:10:00 +00001203 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001204 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001205
1206 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00001207 SmallVector<APValue, 4> Elts(NElts, Val);
1208 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00001209 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001210 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +00001211 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +00001212 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +00001213 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001214
Eli Friedmanc757de22011-03-25 00:43:55 +00001215 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +00001216 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +00001217
Eli Friedmanc757de22011-03-25 00:43:55 +00001218 APSInt Init;
1219 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001220 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001221
Eli Friedmanc757de22011-03-25 00:43:55 +00001222 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1223 "Vectors must be composed of ints or floats");
1224
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001225 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +00001226 for (unsigned i = 0; i != NElts; ++i) {
1227 APSInt Tmp = Init.extOrTrunc(EltWidth);
1228
1229 if (EltTy->isIntegerType())
1230 Elts.push_back(APValue(Tmp));
1231 else
1232 Elts.push_back(APValue(APFloat(Tmp)));
1233
1234 Init >>= EltWidth;
1235 }
Richard Smith2d406342011-10-22 21:10:00 +00001236 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001237 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001238 default:
Richard Smith11562c52011-10-28 17:51:58 +00001239 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001240 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001241}
1242
Richard Smith2d406342011-10-22 21:10:00 +00001243bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001244VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00001245 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001246 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00001247 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00001248
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001249 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001250 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001251
John McCall875679e2010-06-11 17:54:15 +00001252 // If a vector is initialized with a single element, that value
1253 // becomes every element of the vector, not just the first.
1254 // This is the behavior described in the IBM AltiVec documentation.
1255 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00001256
1257 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00001258 // vector (OpenCL 6.1.6).
1259 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00001260 return Visit(E->getInit(0));
1261
John McCall875679e2010-06-11 17:54:15 +00001262 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001263 if (EltTy->isIntegerType()) {
1264 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00001265 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001266 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001267 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001268 } else {
1269 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00001270 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001271 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001272 InitValue = APValue(f);
1273 }
1274 for (unsigned i = 0; i < NumElements; i++) {
1275 Elements.push_back(InitValue);
1276 }
1277 } else {
1278 for (unsigned i = 0; i < NumElements; i++) {
1279 if (EltTy->isIntegerType()) {
1280 llvm::APSInt sInt(32);
1281 if (i < NumInits) {
1282 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001283 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001284 } else {
1285 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1286 }
1287 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00001288 } else {
John McCall875679e2010-06-11 17:54:15 +00001289 llvm::APFloat f(0.0);
1290 if (i < NumInits) {
1291 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001292 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001293 } else {
1294 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1295 }
1296 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00001297 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001298 }
1299 }
Richard Smith2d406342011-10-22 21:10:00 +00001300 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001301}
1302
Richard Smith2d406342011-10-22 21:10:00 +00001303bool
1304VectorExprEvaluator::ValueInitialization(const Expr *E) {
1305 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00001306 QualType EltTy = VT->getElementType();
1307 APValue ZeroElement;
1308 if (EltTy->isIntegerType())
1309 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1310 else
1311 ZeroElement =
1312 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1313
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001314 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00001315 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001316}
1317
Richard Smith2d406342011-10-22 21:10:00 +00001318bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00001319 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00001320 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001321}
1322
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001323//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001324// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001325//
1326// As a GNU extension, we support casting pointers to sufficiently-wide integer
1327// types and back in constant folding. Integer values are thus represented
1328// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00001329//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001330
1331namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001332class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001333 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001334 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001335public:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001336 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001337 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001338
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001339 bool Success(const llvm::APSInt &SI, const Expr *E) {
1340 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001341 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001342 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001343 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001344 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001345 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001346 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001347 return true;
1348 }
1349
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001350 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001351 assert(E->getType()->isIntegralOrEnumerationType() &&
1352 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001353 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001354 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001355 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001356 Result.getInt().setIsUnsigned(
1357 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001358 return true;
1359 }
1360
1361 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001362 assert(E->getType()->isIntegralOrEnumerationType() &&
1363 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001364 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001365 return true;
1366 }
1367
Ken Dyckdbc01912011-03-11 02:13:43 +00001368 bool Success(CharUnits Size, const Expr *E) {
1369 return Success(Size.getQuantity(), E);
1370 }
1371
1372
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001373 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001374 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001375 if (Info.EvalStatus.Diag == 0) {
1376 Info.EvalStatus.DiagLoc = L;
1377 Info.EvalStatus.Diag = D;
1378 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001379 }
Chris Lattner99415702008-07-12 00:14:42 +00001380 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001381 }
Mike Stump11289f42009-09-09 15:08:12 +00001382
Peter Collingbournee9200682011-05-13 03:29:01 +00001383 bool Success(const APValue &V, const Expr *E) {
1384 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001385 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001386 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001387 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001388 }
Mike Stump11289f42009-09-09 15:08:12 +00001389
Richard Smith4ce706a2011-10-11 21:43:33 +00001390 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1391
Peter Collingbournee9200682011-05-13 03:29:01 +00001392 //===--------------------------------------------------------------------===//
1393 // Visitor Methods
1394 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001395
Chris Lattner7174bf32008-07-12 00:38:25 +00001396 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001397 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001398 }
1399 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001400 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001401 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001402
1403 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1404 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001405 if (CheckReferencedDecl(E, E->getDecl()))
1406 return true;
1407
1408 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001409 }
1410 bool VisitMemberExpr(const MemberExpr *E) {
1411 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00001412 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001413 return true;
1414 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001415
1416 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001417 }
1418
Peter Collingbournee9200682011-05-13 03:29:01 +00001419 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001420 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001421 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001422 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001423
Peter Collingbournee9200682011-05-13 03:29:01 +00001424 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001425 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001426
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001427 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001428 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001429 }
Mike Stump11289f42009-09-09 15:08:12 +00001430
Richard Smith4ce706a2011-10-11 21:43:33 +00001431 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001432 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001433 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001434 }
1435
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001436 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001437 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001438 }
1439
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001440 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1441 return Success(E->getValue(), E);
1442 }
1443
John Wiegley6242b6a2011-04-28 00:16:57 +00001444 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1445 return Success(E->getValue(), E);
1446 }
1447
John Wiegleyf9f65842011-04-25 06:54:41 +00001448 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1449 return Success(E->getValue(), E);
1450 }
1451
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001452 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001453 bool VisitUnaryImag(const UnaryOperator *E);
1454
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001455 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001456 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001457
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001458private:
Ken Dyck160146e2010-01-27 17:10:57 +00001459 CharUnits GetAlignOfExpr(const Expr *E);
1460 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001461 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001462 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001463 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001464};
Chris Lattner05706e882008-07-11 18:11:29 +00001465} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001466
Richard Smith11562c52011-10-28 17:51:58 +00001467/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1468/// produce either the integer value or a pointer.
1469///
1470/// GCC has a heinous extension which folds casts between pointer types and
1471/// pointer-sized integral types. We support this by allowing the evaluation of
1472/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1473/// Some simple arithmetic on such values is supported (they are treated much
1474/// like char*).
Daniel Dunbarce399542009-02-20 18:22:23 +00001475static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001476 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001477 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001478}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001479
Daniel Dunbarce399542009-02-20 18:22:23 +00001480static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
1481 APValue Val;
1482 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1483 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001484 Result = Val.getInt();
1485 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001486}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001487
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001488bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001489 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001490 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001491 // Check for signedness/width mismatches between E type and ECD value.
1492 bool SameSign = (ECD->getInitVal().isSigned()
1493 == E->getType()->isSignedIntegerOrEnumerationType());
1494 bool SameWidth = (ECD->getInitVal().getBitWidth()
1495 == Info.Ctx.getIntWidth(E->getType()));
1496 if (SameSign && SameWidth)
1497 return Success(ECD->getInitVal(), E);
1498 else {
1499 // Get rid of mismatch (otherwise Success assertions will fail)
1500 // by computing a new value matching the type of E.
1501 llvm::APSInt Val = ECD->getInitVal();
1502 if (!SameSign)
1503 Val.setIsSigned(!ECD->getInitVal().isSigned());
1504 if (!SameWidth)
1505 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1506 return Success(Val, E);
1507 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001508 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001509 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001510}
1511
Chris Lattner86ee2862008-10-06 06:40:35 +00001512/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1513/// as GCC.
1514static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1515 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001516 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001517 enum gcc_type_class {
1518 no_type_class = -1,
1519 void_type_class, integer_type_class, char_type_class,
1520 enumeral_type_class, boolean_type_class,
1521 pointer_type_class, reference_type_class, offset_type_class,
1522 real_type_class, complex_type_class,
1523 function_type_class, method_type_class,
1524 record_type_class, union_type_class,
1525 array_type_class, string_type_class,
1526 lang_type_class
1527 };
Mike Stump11289f42009-09-09 15:08:12 +00001528
1529 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001530 // ideal, however it is what gcc does.
1531 if (E->getNumArgs() == 0)
1532 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001533
Chris Lattner86ee2862008-10-06 06:40:35 +00001534 QualType ArgTy = E->getArg(0)->getType();
1535 if (ArgTy->isVoidType())
1536 return void_type_class;
1537 else if (ArgTy->isEnumeralType())
1538 return enumeral_type_class;
1539 else if (ArgTy->isBooleanType())
1540 return boolean_type_class;
1541 else if (ArgTy->isCharType())
1542 return string_type_class; // gcc doesn't appear to use char_type_class
1543 else if (ArgTy->isIntegerType())
1544 return integer_type_class;
1545 else if (ArgTy->isPointerType())
1546 return pointer_type_class;
1547 else if (ArgTy->isReferenceType())
1548 return reference_type_class;
1549 else if (ArgTy->isRealType())
1550 return real_type_class;
1551 else if (ArgTy->isComplexType())
1552 return complex_type_class;
1553 else if (ArgTy->isFunctionType())
1554 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001555 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001556 return record_type_class;
1557 else if (ArgTy->isUnionType())
1558 return union_type_class;
1559 else if (ArgTy->isArrayType())
1560 return array_type_class;
1561 else if (ArgTy->isUnionType())
1562 return union_type_class;
1563 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001564 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001565 return -1;
1566}
1567
John McCall95007602010-05-10 23:27:23 +00001568/// Retrieves the "underlying object type" of the given expression,
1569/// as used by __builtin_object_size.
1570QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1571 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1572 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1573 return VD->getType();
1574 } else if (isa<CompoundLiteralExpr>(E)) {
1575 return E->getType();
1576 }
1577
1578 return QualType();
1579}
1580
Peter Collingbournee9200682011-05-13 03:29:01 +00001581bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001582 // TODO: Perhaps we should let LLVM lower this?
1583 LValue Base;
1584 if (!EvaluatePointer(E->getArg(0), Base, Info))
1585 return false;
1586
1587 // If we can prove the base is null, lower to zero now.
1588 const Expr *LVBase = Base.getLValueBase();
1589 if (!LVBase) return Success(0, E);
1590
1591 QualType T = GetObjectType(LVBase);
1592 if (T.isNull() ||
1593 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001594 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001595 T->isVariablyModifiedType() ||
1596 T->isDependentType())
1597 return false;
1598
1599 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1600 CharUnits Offset = Base.getLValueOffset();
1601
1602 if (!Offset.isNegative() && Offset <= Size)
1603 Size -= Offset;
1604 else
1605 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001606 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001607}
1608
Peter Collingbournee9200682011-05-13 03:29:01 +00001609bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001610 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001611 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001612 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001613
1614 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001615 if (TryEvaluateBuiltinObjectSize(E))
1616 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001617
Eric Christopher99469702010-01-19 22:58:35 +00001618 // If evaluating the argument has side-effects we can't determine
1619 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001620 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001621 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001622 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001623 return Success(0, E);
1624 }
Mike Stump876387b2009-10-27 22:09:17 +00001625
Mike Stump722cedf2009-10-26 18:35:08 +00001626 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1627 }
1628
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001629 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001630 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001631
Anders Carlsson4c76e932008-11-24 04:21:33 +00001632 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001633 // __builtin_constant_p always has one operand: it returns true if that
1634 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001635 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001636
1637 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001638 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001639 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001640 return Success(Operand, E);
1641 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001642
1643 case Builtin::BI__builtin_expect:
1644 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001645
1646 case Builtin::BIstrlen:
1647 case Builtin::BI__builtin_strlen:
1648 // As an extension, we support strlen() and __builtin_strlen() as constant
1649 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001650 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001651 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1652 // The string literal may have embedded null characters. Find the first
1653 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001654 StringRef Str = S->getString();
1655 StringRef::size_type Pos = Str.find(0);
1656 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001657 Str = Str.substr(0, Pos);
1658
1659 return Success(Str.size(), E);
1660 }
1661
1662 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001663
1664 case Builtin::BI__atomic_is_lock_free: {
1665 APSInt SizeVal;
1666 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1667 return false;
1668
1669 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1670 // of two less than the maximum inline atomic width, we know it is
1671 // lock-free. If the size isn't a power of two, or greater than the
1672 // maximum alignment where we promote atomics, we know it is not lock-free
1673 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1674 // the answer can only be determined at runtime; for example, 16-byte
1675 // atomics have lock-free implementations on some, but not all,
1676 // x86-64 processors.
1677
1678 // Check power-of-two.
1679 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1680 if (!Size.isPowerOfTwo())
1681#if 0
1682 // FIXME: Suppress this folding until the ABI for the promotion width
1683 // settles.
1684 return Success(0, E);
1685#else
1686 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1687#endif
1688
1689#if 0
1690 // Check against promotion width.
1691 // FIXME: Suppress this folding until the ABI for the promotion width
1692 // settles.
1693 unsigned PromoteWidthBits =
1694 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1695 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1696 return Success(0, E);
1697#endif
1698
1699 // Check against inlining width.
1700 unsigned InlineWidthBits =
1701 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1702 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1703 return Success(1, E);
1704
1705 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1706 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001707 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001708}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001709
Chris Lattnere13042c2008-07-11 19:10:17 +00001710bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001711 if (E->isAssignmentOp())
1712 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1713
John McCalle3027922010-08-25 11:45:40 +00001714 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00001715 VisitIgnoredValue(E->getLHS());
1716 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00001717 }
1718
1719 if (E->isLogicalOp()) {
1720 // These need to be handled specially because the operands aren't
1721 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001722 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001723
Richard Smith11562c52011-10-28 17:51:58 +00001724 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001725 // We were able to evaluate the LHS, see if we can get away with not
1726 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001727 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001728 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001729
Richard Smith11562c52011-10-28 17:51:58 +00001730 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001731 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001732 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001733 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001734 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001735 }
1736 } else {
Richard Smith11562c52011-10-28 17:51:58 +00001737 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001738 // We can't evaluate the LHS; however, sometimes the result
1739 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001740 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1741 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001742 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001743 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00001744 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001745
1746 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001747 }
1748 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001749 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001750
Eli Friedman5a332ea2008-11-13 06:09:17 +00001751 return false;
1752 }
1753
Anders Carlssonacc79812008-11-16 07:17:21 +00001754 QualType LHSTy = E->getLHS()->getType();
1755 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001756
1757 if (LHSTy->isAnyComplexType()) {
1758 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001759 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001760
1761 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1762 return false;
1763
1764 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1765 return false;
1766
1767 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001768 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001769 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001770 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001771 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1772
John McCalle3027922010-08-25 11:45:40 +00001773 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001774 return Success((CR_r == APFloat::cmpEqual &&
1775 CR_i == APFloat::cmpEqual), E);
1776 else {
John McCalle3027922010-08-25 11:45:40 +00001777 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001778 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001779 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001780 CR_r == APFloat::cmpLessThan ||
1781 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001782 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001783 CR_i == APFloat::cmpLessThan ||
1784 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001785 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001786 } else {
John McCalle3027922010-08-25 11:45:40 +00001787 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001788 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1789 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1790 else {
John McCalle3027922010-08-25 11:45:40 +00001791 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001792 "Invalid compex comparison.");
1793 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1794 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1795 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001796 }
1797 }
Mike Stump11289f42009-09-09 15:08:12 +00001798
Anders Carlssonacc79812008-11-16 07:17:21 +00001799 if (LHSTy->isRealFloatingType() &&
1800 RHSTy->isRealFloatingType()) {
1801 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001802
Anders Carlssonacc79812008-11-16 07:17:21 +00001803 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1804 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001805
Anders Carlssonacc79812008-11-16 07:17:21 +00001806 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1807 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001808
Anders Carlssonacc79812008-11-16 07:17:21 +00001809 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001810
Anders Carlssonacc79812008-11-16 07:17:21 +00001811 switch (E->getOpcode()) {
1812 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001813 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001814 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001815 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001816 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001817 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001818 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001819 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001820 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001821 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001822 E);
John McCalle3027922010-08-25 11:45:40 +00001823 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001824 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001825 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001826 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001827 || CR == APFloat::cmpLessThan
1828 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001829 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001830 }
Mike Stump11289f42009-09-09 15:08:12 +00001831
Eli Friedmana38da572009-04-28 19:17:36 +00001832 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001833 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001834 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001835 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1836 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001837
John McCall45d55e42010-05-07 21:00:08 +00001838 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001839 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1840 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001841
Eli Friedman334046a2009-06-14 02:17:33 +00001842 // Reject any bases from the normal codepath; we special-case comparisons
1843 // to null.
1844 if (LHSValue.getLValueBase()) {
1845 if (!E->isEqualityOp())
1846 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001847 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001848 return false;
1849 bool bres;
1850 if (!EvalPointerValueAsBool(LHSValue, bres))
1851 return false;
John McCalle3027922010-08-25 11:45:40 +00001852 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001853 } else if (RHSValue.getLValueBase()) {
1854 if (!E->isEqualityOp())
1855 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001856 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001857 return false;
1858 bool bres;
1859 if (!EvalPointerValueAsBool(RHSValue, bres))
1860 return false;
John McCalle3027922010-08-25 11:45:40 +00001861 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001862 }
Eli Friedman64004332009-03-23 04:38:34 +00001863
John McCalle3027922010-08-25 11:45:40 +00001864 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001865 QualType Type = E->getLHS()->getType();
1866 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001867
Ken Dyck02990832010-01-15 12:37:54 +00001868 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001869 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001870 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001871
Ken Dyck02990832010-01-15 12:37:54 +00001872 CharUnits Diff = LHSValue.getLValueOffset() -
1873 RHSValue.getLValueOffset();
1874 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001875 }
1876 bool Result;
John McCalle3027922010-08-25 11:45:40 +00001877 if (E->getOpcode() == BO_EQ) {
Eli Friedmana38da572009-04-28 19:17:36 +00001878 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman8b171f62009-04-29 20:29:43 +00001879 } else {
Eli Friedmana38da572009-04-28 19:17:36 +00001880 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1881 }
1882 return Success(Result, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001883 }
1884 }
Douglas Gregorb90df602010-06-16 00:17:44 +00001885 if (!LHSTy->isIntegralOrEnumerationType() ||
1886 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001887 // We can't continue from here for non-integral types, and they
1888 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001889 return false;
1890 }
1891
Anders Carlsson9c181652008-07-08 14:35:21 +00001892 // The LHS of a constant expr is always evaluated and needed.
Richard Smith11562c52011-10-28 17:51:58 +00001893 APValue LHSVal;
1894 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00001895 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001896
Richard Smith11562c52011-10-28 17:51:58 +00001897 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001898 return false;
Richard Smith11562c52011-10-28 17:51:58 +00001899 APValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00001900
1901 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00001902 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
1903 CharUnits Offset = LHSVal.getLValueOffset();
Ken Dyck02990832010-01-15 12:37:54 +00001904 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1905 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00001906 if (E->getOpcode() == BO_Add)
Ken Dyck02990832010-01-15 12:37:54 +00001907 Offset += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001908 else
Ken Dyck02990832010-01-15 12:37:54 +00001909 Offset -= AdditionalOffset;
Richard Smith11562c52011-10-28 17:51:58 +00001910 Result = APValue(LHSVal.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001911 return true;
1912 }
1913
1914 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00001915 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00001916 RHSVal.isLValue() && LHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001917 CharUnits Offset = RHSVal.getLValueOffset();
Richard Smith11562c52011-10-28 17:51:58 +00001918 Offset += CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Ken Dyck02990832010-01-15 12:37:54 +00001919 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001920 return true;
1921 }
1922
1923 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00001924 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00001925 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001926
Richard Smith11562c52011-10-28 17:51:58 +00001927 APSInt &LHS = LHSVal.getInt();
1928 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00001929
Anders Carlsson9c181652008-07-08 14:35:21 +00001930 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001931 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001932 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00001933 case BO_Mul: return Success(LHS * RHS, E);
1934 case BO_Add: return Success(LHS + RHS, E);
1935 case BO_Sub: return Success(LHS - RHS, E);
1936 case BO_And: return Success(LHS & RHS, E);
1937 case BO_Xor: return Success(LHS ^ RHS, E);
1938 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001939 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00001940 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001941 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00001942 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001943 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00001944 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001945 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00001946 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001947 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00001948 // During constant-folding, a negative shift is an opposite shift.
1949 if (RHS.isSigned() && RHS.isNegative()) {
1950 RHS = -RHS;
1951 goto shift_right;
1952 }
1953
1954 shift_left:
1955 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00001956 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1957 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001958 }
John McCalle3027922010-08-25 11:45:40 +00001959 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00001960 // During constant-folding, a negative shift is an opposite shift.
1961 if (RHS.isSigned() && RHS.isNegative()) {
1962 RHS = -RHS;
1963 goto shift_left;
1964 }
1965
1966 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00001967 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00001968 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1969 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001970 }
Mike Stump11289f42009-09-09 15:08:12 +00001971
Richard Smith11562c52011-10-28 17:51:58 +00001972 case BO_LT: return Success(LHS < RHS, E);
1973 case BO_GT: return Success(LHS > RHS, E);
1974 case BO_LE: return Success(LHS <= RHS, E);
1975 case BO_GE: return Success(LHS >= RHS, E);
1976 case BO_EQ: return Success(LHS == RHS, E);
1977 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00001978 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001979}
1980
Ken Dyck160146e2010-01-27 17:10:57 +00001981CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001982 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1983 // the result is the size of the referenced type."
1984 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1985 // result shall be the alignment of the referenced type."
1986 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1987 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00001988
1989 // __alignof is defined to return the preferred alignment.
1990 return Info.Ctx.toCharUnitsFromBits(
1991 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00001992}
1993
Ken Dyck160146e2010-01-27 17:10:57 +00001994CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00001995 E = E->IgnoreParens();
1996
1997 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00001998 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00001999 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002000 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2001 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00002002
Chris Lattner68061312009-01-24 21:53:27 +00002003 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002004 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2005 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00002006
Chris Lattner24aeeab2009-01-24 21:09:06 +00002007 return GetAlignOfType(E->getType());
2008}
2009
2010
Peter Collingbournee190dee2011-03-11 19:24:49 +00002011/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2012/// a result as the expression's type.
2013bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2014 const UnaryExprOrTypeTraitExpr *E) {
2015 switch(E->getKind()) {
2016 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00002017 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00002018 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002019 else
Ken Dyckdbc01912011-03-11 02:13:43 +00002020 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002021 }
Eli Friedman64004332009-03-23 04:38:34 +00002022
Peter Collingbournee190dee2011-03-11 19:24:49 +00002023 case UETT_VecStep: {
2024 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00002025
Peter Collingbournee190dee2011-03-11 19:24:49 +00002026 if (Ty->isVectorType()) {
2027 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00002028
Peter Collingbournee190dee2011-03-11 19:24:49 +00002029 // The vec_step built-in functions that take a 3-component
2030 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2031 if (n == 3)
2032 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002033
Peter Collingbournee190dee2011-03-11 19:24:49 +00002034 return Success(n, E);
2035 } else
2036 return Success(1, E);
2037 }
2038
2039 case UETT_SizeOf: {
2040 QualType SrcTy = E->getTypeOfArgument();
2041 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2042 // the result is the size of the referenced type."
2043 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2044 // result shall be the alignment of the referenced type."
2045 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2046 SrcTy = Ref->getPointeeType();
2047
2048 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2049 // extension.
2050 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
2051 return Success(1, E);
2052
2053 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2054 if (!SrcTy->isConstantSizeType())
2055 return false;
2056
2057 // Get information about the size.
2058 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
2059 }
2060 }
2061
2062 llvm_unreachable("unknown expr/type trait");
2063 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002064}
2065
Peter Collingbournee9200682011-05-13 03:29:01 +00002066bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00002067 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00002068 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00002069 if (n == 0)
2070 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002071 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00002072 for (unsigned i = 0; i != n; ++i) {
2073 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
2074 switch (ON.getKind()) {
2075 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00002076 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00002077 APSInt IdxResult;
2078 if (!EvaluateInteger(Idx, IdxResult, Info))
2079 return false;
2080 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
2081 if (!AT)
2082 return false;
2083 CurrentType = AT->getElementType();
2084 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
2085 Result += IdxResult.getSExtValue() * ElementSize;
2086 break;
2087 }
2088
2089 case OffsetOfExpr::OffsetOfNode::Field: {
2090 FieldDecl *MemberDecl = ON.getField();
2091 const RecordType *RT = CurrentType->getAs<RecordType>();
2092 if (!RT)
2093 return false;
2094 RecordDecl *RD = RT->getDecl();
2095 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00002096 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00002097 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002098 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00002099 CurrentType = MemberDecl->getType().getNonReferenceType();
2100 break;
2101 }
2102
2103 case OffsetOfExpr::OffsetOfNode::Identifier:
2104 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00002105 return false;
2106
2107 case OffsetOfExpr::OffsetOfNode::Base: {
2108 CXXBaseSpecifier *BaseSpec = ON.getBase();
2109 if (BaseSpec->isVirtual())
2110 return false;
2111
2112 // Find the layout of the class whose base we are looking into.
2113 const RecordType *RT = CurrentType->getAs<RecordType>();
2114 if (!RT)
2115 return false;
2116 RecordDecl *RD = RT->getDecl();
2117 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
2118
2119 // Find the base class itself.
2120 CurrentType = BaseSpec->getType();
2121 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2122 if (!BaseRT)
2123 return false;
2124
2125 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00002126 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00002127 break;
2128 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002129 }
2130 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002131 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00002132}
2133
Chris Lattnere13042c2008-07-11 19:10:17 +00002134bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002135 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002136 // LNot's operand isn't necessarily an integer, so we handle it specially.
2137 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00002138 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00002139 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002140 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00002141 }
2142
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002143 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00002144 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002145 return false;
2146
Richard Smith11562c52011-10-28 17:51:58 +00002147 // Get the operand value.
2148 APValue Val;
2149 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00002150 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002151
Chris Lattnerf09ad162008-07-11 22:15:16 +00002152 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002153 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00002154 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2155 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002156 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00002157 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00002158 // FIXME: Should extension allow i-c-e extension expressions in its scope?
2159 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00002160 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002161 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00002162 // The result is just the value.
2163 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002164 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00002165 if (!Val.isInt()) return false;
2166 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00002167 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00002168 if (!Val.isInt()) return false;
2169 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00002170 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002171}
Mike Stump11289f42009-09-09 15:08:12 +00002172
Chris Lattner477c4be2008-07-12 01:15:53 +00002173/// HandleCast - This is used to evaluate implicit or explicit casts where the
2174/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00002175bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
2176 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002177 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00002178 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002179
Eli Friedmanc757de22011-03-25 00:43:55 +00002180 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00002181 case CK_BaseToDerived:
2182 case CK_DerivedToBase:
2183 case CK_UncheckedDerivedToBase:
2184 case CK_Dynamic:
2185 case CK_ToUnion:
2186 case CK_ArrayToPointerDecay:
2187 case CK_FunctionToPointerDecay:
2188 case CK_NullToPointer:
2189 case CK_NullToMemberPointer:
2190 case CK_BaseToDerivedMemberPointer:
2191 case CK_DerivedToBaseMemberPointer:
2192 case CK_ConstructorConversion:
2193 case CK_IntegralToPointer:
2194 case CK_ToVoid:
2195 case CK_VectorSplat:
2196 case CK_IntegralToFloating:
2197 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002198 case CK_CPointerToObjCPointerCast:
2199 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002200 case CK_AnyPointerToBlockPointerCast:
2201 case CK_ObjCObjectLValueCast:
2202 case CK_FloatingRealToComplex:
2203 case CK_FloatingComplexToReal:
2204 case CK_FloatingComplexCast:
2205 case CK_FloatingComplexToIntegralComplex:
2206 case CK_IntegralRealToComplex:
2207 case CK_IntegralComplexCast:
2208 case CK_IntegralComplexToFloatingComplex:
2209 llvm_unreachable("invalid cast kind for integral value");
2210
Eli Friedman9faf2f92011-03-25 19:07:11 +00002211 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002212 case CK_Dependent:
2213 case CK_GetObjCProperty:
2214 case CK_LValueBitCast:
2215 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00002216 case CK_ARCProduceObject:
2217 case CK_ARCConsumeObject:
2218 case CK_ARCReclaimReturnedObject:
2219 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00002220 return false;
2221
2222 case CK_LValueToRValue:
2223 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002224 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002225
2226 case CK_MemberPointerToBoolean:
2227 case CK_PointerToBoolean:
2228 case CK_IntegralToBoolean:
2229 case CK_FloatingToBoolean:
2230 case CK_FloatingComplexToBoolean:
2231 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002232 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002233 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002234 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002235 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002236 }
2237
Eli Friedmanc757de22011-03-25 00:43:55 +00002238 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00002239 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00002240 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002241
Eli Friedman742421e2009-02-20 01:15:07 +00002242 if (!Result.isInt()) {
2243 // Only allow casts of lvalues if they are lossless.
2244 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2245 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002246
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002247 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002248 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00002249 }
Mike Stump11289f42009-09-09 15:08:12 +00002250
Eli Friedmanc757de22011-03-25 00:43:55 +00002251 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00002252 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00002253 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00002254 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002255
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002256 if (LV.getLValueBase()) {
2257 // Only allow based lvalue casts if they are lossless.
2258 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2259 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002260
John McCall45d55e42010-05-07 21:00:08 +00002261 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002262 return true;
2263 }
2264
Ken Dyck02990832010-01-15 12:37:54 +00002265 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2266 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002267 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002268 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002269
Eli Friedmanc757de22011-03-25 00:43:55 +00002270 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00002271 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002272 if (!EvaluateComplex(SubExpr, C, Info))
2273 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00002274 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002275 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00002276
Eli Friedmanc757de22011-03-25 00:43:55 +00002277 case CK_FloatingToIntegral: {
2278 APFloat F(0.0);
2279 if (!EvaluateFloat(SubExpr, F, Info))
2280 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00002281
Eli Friedmanc757de22011-03-25 00:43:55 +00002282 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2283 }
2284 }
Mike Stump11289f42009-09-09 15:08:12 +00002285
Eli Friedmanc757de22011-03-25 00:43:55 +00002286 llvm_unreachable("unknown cast resulting in integral value");
2287 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002288}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002289
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002290bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2291 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002292 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002293 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2294 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2295 return Success(LV.getComplexIntReal(), E);
2296 }
2297
2298 return Visit(E->getSubExpr());
2299}
2300
Eli Friedman4e7a2412009-02-27 04:45:43 +00002301bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002302 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002303 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002304 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2305 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2306 return Success(LV.getComplexIntImag(), E);
2307 }
2308
Richard Smith4a678122011-10-24 18:44:57 +00002309 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00002310 return Success(0, E);
2311}
2312
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002313bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2314 return Success(E->getPackLength(), E);
2315}
2316
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002317bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2318 return Success(E->getValue(), E);
2319}
2320
Chris Lattner05706e882008-07-11 18:11:29 +00002321//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002322// Float Evaluation
2323//===----------------------------------------------------------------------===//
2324
2325namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002326class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002327 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002328 APFloat &Result;
2329public:
2330 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002331 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002332
Peter Collingbournee9200682011-05-13 03:29:01 +00002333 bool Success(const APValue &V, const Expr *e) {
2334 Result = V.getFloat();
2335 return true;
2336 }
2337 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002338 return false;
2339 }
2340
Richard Smith4ce706a2011-10-11 21:43:33 +00002341 bool ValueInitialization(const Expr *E) {
2342 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2343 return true;
2344 }
2345
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002346 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002347
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002348 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002349 bool VisitBinaryOperator(const BinaryOperator *E);
2350 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002351 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002352
John McCallb1fb0d32010-05-07 22:08:54 +00002353 bool VisitUnaryReal(const UnaryOperator *E);
2354 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002355
John McCallb1fb0d32010-05-07 22:08:54 +00002356 // FIXME: Missing: array subscript of vector, member of vector,
2357 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002358};
2359} // end anonymous namespace
2360
2361static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002362 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002363 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002364}
2365
Jay Foad39c79802011-01-12 09:06:06 +00002366static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002367 QualType ResultTy,
2368 const Expr *Arg,
2369 bool SNaN,
2370 llvm::APFloat &Result) {
2371 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2372 if (!S) return false;
2373
2374 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2375
2376 llvm::APInt fill;
2377
2378 // Treat empty strings as if they were zero.
2379 if (S->getString().empty())
2380 fill = llvm::APInt(32, 0);
2381 else if (S->getString().getAsInteger(0, fill))
2382 return false;
2383
2384 if (SNaN)
2385 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2386 else
2387 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2388 return true;
2389}
2390
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002391bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002392 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002393 default:
2394 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2395
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002396 case Builtin::BI__builtin_huge_val:
2397 case Builtin::BI__builtin_huge_valf:
2398 case Builtin::BI__builtin_huge_vall:
2399 case Builtin::BI__builtin_inf:
2400 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002401 case Builtin::BI__builtin_infl: {
2402 const llvm::fltSemantics &Sem =
2403 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002404 Result = llvm::APFloat::getInf(Sem);
2405 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002406 }
Mike Stump11289f42009-09-09 15:08:12 +00002407
John McCall16291492010-02-28 13:00:19 +00002408 case Builtin::BI__builtin_nans:
2409 case Builtin::BI__builtin_nansf:
2410 case Builtin::BI__builtin_nansl:
2411 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2412 true, Result);
2413
Chris Lattner0b7282e2008-10-06 06:31:58 +00002414 case Builtin::BI__builtin_nan:
2415 case Builtin::BI__builtin_nanf:
2416 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002417 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002418 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002419 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2420 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002421
2422 case Builtin::BI__builtin_fabs:
2423 case Builtin::BI__builtin_fabsf:
2424 case Builtin::BI__builtin_fabsl:
2425 if (!EvaluateFloat(E->getArg(0), Result, Info))
2426 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002427
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002428 if (Result.isNegative())
2429 Result.changeSign();
2430 return true;
2431
Mike Stump11289f42009-09-09 15:08:12 +00002432 case Builtin::BI__builtin_copysign:
2433 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002434 case Builtin::BI__builtin_copysignl: {
2435 APFloat RHS(0.);
2436 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2437 !EvaluateFloat(E->getArg(1), RHS, Info))
2438 return false;
2439 Result.copySign(RHS);
2440 return true;
2441 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002442 }
2443}
2444
John McCallb1fb0d32010-05-07 22:08:54 +00002445bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002446 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2447 ComplexValue CV;
2448 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2449 return false;
2450 Result = CV.FloatReal;
2451 return true;
2452 }
2453
2454 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002455}
2456
2457bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002458 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2459 ComplexValue CV;
2460 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2461 return false;
2462 Result = CV.FloatImag;
2463 return true;
2464 }
2465
Richard Smith4a678122011-10-24 18:44:57 +00002466 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00002467 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2468 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002469 return true;
2470}
2471
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002472bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002473 if (E->getOpcode() == UO_Deref)
Nuno Lopes0e33c682008-11-19 17:44:31 +00002474 return false;
2475
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002476 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2477 return false;
2478
2479 switch (E->getOpcode()) {
2480 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002481 case UO_Plus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002482 return true;
John McCalle3027922010-08-25 11:45:40 +00002483 case UO_Minus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002484 Result.changeSign();
2485 return true;
2486 }
2487}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002488
Eli Friedman24c01542008-08-22 00:06:13 +00002489bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002490 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002491 VisitIgnoredValue(E->getLHS());
2492 return Visit(E->getRHS());
Eli Friedman141fbf32009-11-16 04:25:37 +00002493 }
2494
Richard Smith472d4952011-10-28 23:26:52 +00002495 // We can't evaluate pointer-to-member operations or assignments.
2496 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlssona5df61a2010-10-31 01:21:47 +00002497 return false;
2498
Eli Friedman24c01542008-08-22 00:06:13 +00002499 // FIXME: Diagnostics? I really don't understand how the warnings
2500 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002501 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002502 if (!EvaluateFloat(E->getLHS(), Result, Info))
2503 return false;
2504 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2505 return false;
2506
2507 switch (E->getOpcode()) {
2508 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002509 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002510 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2511 return true;
John McCalle3027922010-08-25 11:45:40 +00002512 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002513 Result.add(RHS, APFloat::rmNearestTiesToEven);
2514 return true;
John McCalle3027922010-08-25 11:45:40 +00002515 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002516 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2517 return true;
John McCalle3027922010-08-25 11:45:40 +00002518 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002519 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2520 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002521 }
2522}
2523
2524bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2525 Result = E->getValue();
2526 return true;
2527}
2528
Peter Collingbournee9200682011-05-13 03:29:01 +00002529bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2530 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002531
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002532 switch (E->getCastKind()) {
2533 default:
Richard Smith11562c52011-10-28 17:51:58 +00002534 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002535
2536 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002537 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002538 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002539 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002540 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002541 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002542 return true;
2543 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002544
2545 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002546 if (!Visit(SubExpr))
2547 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002548 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2549 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002550 return true;
2551 }
John McCalld7646252010-11-14 08:17:51 +00002552
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002553 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002554 ComplexValue V;
2555 if (!EvaluateComplex(SubExpr, V, Info))
2556 return false;
2557 Result = V.getComplexFloatReal();
2558 return true;
2559 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002560 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002561
2562 return false;
2563}
2564
Eli Friedman24c01542008-08-22 00:06:13 +00002565//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002566// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002567//===----------------------------------------------------------------------===//
2568
2569namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002570class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002571 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002572 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002573
Anders Carlsson537969c2008-11-16 20:27:53 +00002574public:
John McCall93d91dc2010-05-07 17:22:02 +00002575 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002576 : ExprEvaluatorBaseTy(info), Result(Result) {}
2577
2578 bool Success(const APValue &V, const Expr *e) {
2579 Result.setFrom(V);
2580 return true;
2581 }
2582 bool Error(const Expr *E) {
2583 return false;
2584 }
Mike Stump11289f42009-09-09 15:08:12 +00002585
Anders Carlsson537969c2008-11-16 20:27:53 +00002586 //===--------------------------------------------------------------------===//
2587 // Visitor Methods
2588 //===--------------------------------------------------------------------===//
2589
Peter Collingbournee9200682011-05-13 03:29:01 +00002590 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002591
Peter Collingbournee9200682011-05-13 03:29:01 +00002592 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002593
John McCall93d91dc2010-05-07 17:22:02 +00002594 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002595 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002596 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002597};
2598} // end anonymous namespace
2599
John McCall93d91dc2010-05-07 17:22:02 +00002600static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2601 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002602 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002603 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002604}
2605
Peter Collingbournee9200682011-05-13 03:29:01 +00002606bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2607 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002608
2609 if (SubExpr->getType()->isRealFloatingType()) {
2610 Result.makeComplexFloat();
2611 APFloat &Imag = Result.FloatImag;
2612 if (!EvaluateFloat(SubExpr, Imag, Info))
2613 return false;
2614
2615 Result.FloatReal = APFloat(Imag.getSemantics());
2616 return true;
2617 } else {
2618 assert(SubExpr->getType()->isIntegerType() &&
2619 "Unexpected imaginary literal.");
2620
2621 Result.makeComplexInt();
2622 APSInt &Imag = Result.IntImag;
2623 if (!EvaluateInteger(SubExpr, Imag, Info))
2624 return false;
2625
2626 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2627 return true;
2628 }
2629}
2630
Peter Collingbournee9200682011-05-13 03:29:01 +00002631bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002632
John McCallfcef3cf2010-12-14 17:51:41 +00002633 switch (E->getCastKind()) {
2634 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002635 case CK_BaseToDerived:
2636 case CK_DerivedToBase:
2637 case CK_UncheckedDerivedToBase:
2638 case CK_Dynamic:
2639 case CK_ToUnion:
2640 case CK_ArrayToPointerDecay:
2641 case CK_FunctionToPointerDecay:
2642 case CK_NullToPointer:
2643 case CK_NullToMemberPointer:
2644 case CK_BaseToDerivedMemberPointer:
2645 case CK_DerivedToBaseMemberPointer:
2646 case CK_MemberPointerToBoolean:
2647 case CK_ConstructorConversion:
2648 case CK_IntegralToPointer:
2649 case CK_PointerToIntegral:
2650 case CK_PointerToBoolean:
2651 case CK_ToVoid:
2652 case CK_VectorSplat:
2653 case CK_IntegralCast:
2654 case CK_IntegralToBoolean:
2655 case CK_IntegralToFloating:
2656 case CK_FloatingToIntegral:
2657 case CK_FloatingToBoolean:
2658 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002659 case CK_CPointerToObjCPointerCast:
2660 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002661 case CK_AnyPointerToBlockPointerCast:
2662 case CK_ObjCObjectLValueCast:
2663 case CK_FloatingComplexToReal:
2664 case CK_FloatingComplexToBoolean:
2665 case CK_IntegralComplexToReal:
2666 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002667 case CK_ARCProduceObject:
2668 case CK_ARCConsumeObject:
2669 case CK_ARCReclaimReturnedObject:
2670 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002671 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002672
John McCallfcef3cf2010-12-14 17:51:41 +00002673 case CK_LValueToRValue:
2674 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002675 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00002676
2677 case CK_Dependent:
2678 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002679 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002680 case CK_UserDefinedConversion:
2681 return false;
2682
2683 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002684 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002685 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002686 return false;
2687
John McCallfcef3cf2010-12-14 17:51:41 +00002688 Result.makeComplexFloat();
2689 Result.FloatImag = APFloat(Real.getSemantics());
2690 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002691 }
2692
John McCallfcef3cf2010-12-14 17:51:41 +00002693 case CK_FloatingComplexCast: {
2694 if (!Visit(E->getSubExpr()))
2695 return false;
2696
2697 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2698 QualType From
2699 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2700
2701 Result.FloatReal
2702 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2703 Result.FloatImag
2704 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2705 return true;
2706 }
2707
2708 case CK_FloatingComplexToIntegralComplex: {
2709 if (!Visit(E->getSubExpr()))
2710 return false;
2711
2712 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2713 QualType From
2714 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2715 Result.makeComplexInt();
2716 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2717 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2718 return true;
2719 }
2720
2721 case CK_IntegralRealToComplex: {
2722 APSInt &Real = Result.IntReal;
2723 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2724 return false;
2725
2726 Result.makeComplexInt();
2727 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2728 return true;
2729 }
2730
2731 case CK_IntegralComplexCast: {
2732 if (!Visit(E->getSubExpr()))
2733 return false;
2734
2735 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2736 QualType From
2737 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2738
2739 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2740 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2741 return true;
2742 }
2743
2744 case CK_IntegralComplexToFloatingComplex: {
2745 if (!Visit(E->getSubExpr()))
2746 return false;
2747
2748 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2749 QualType From
2750 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2751 Result.makeComplexFloat();
2752 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2753 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2754 return true;
2755 }
2756 }
2757
2758 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002759 return false;
2760}
2761
John McCall93d91dc2010-05-07 17:22:02 +00002762bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002763 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002764 VisitIgnoredValue(E->getLHS());
2765 return Visit(E->getRHS());
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002766 }
John McCall93d91dc2010-05-07 17:22:02 +00002767 if (!Visit(E->getLHS()))
2768 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002769
John McCall93d91dc2010-05-07 17:22:02 +00002770 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002771 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002772 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002773
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002774 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2775 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002776 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002777 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002778 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002779 if (Result.isComplexFloat()) {
2780 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2781 APFloat::rmNearestTiesToEven);
2782 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2783 APFloat::rmNearestTiesToEven);
2784 } else {
2785 Result.getComplexIntReal() += RHS.getComplexIntReal();
2786 Result.getComplexIntImag() += RHS.getComplexIntImag();
2787 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002788 break;
John McCalle3027922010-08-25 11:45:40 +00002789 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002790 if (Result.isComplexFloat()) {
2791 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2792 APFloat::rmNearestTiesToEven);
2793 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2794 APFloat::rmNearestTiesToEven);
2795 } else {
2796 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2797 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2798 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002799 break;
John McCalle3027922010-08-25 11:45:40 +00002800 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002801 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002802 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002803 APFloat &LHS_r = LHS.getComplexFloatReal();
2804 APFloat &LHS_i = LHS.getComplexFloatImag();
2805 APFloat &RHS_r = RHS.getComplexFloatReal();
2806 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002807
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002808 APFloat Tmp = LHS_r;
2809 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2810 Result.getComplexFloatReal() = Tmp;
2811 Tmp = LHS_i;
2812 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2813 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2814
2815 Tmp = LHS_r;
2816 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2817 Result.getComplexFloatImag() = Tmp;
2818 Tmp = LHS_i;
2819 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2820 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2821 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002822 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002823 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002824 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2825 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002826 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002827 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2828 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2829 }
2830 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002831 case BO_Div:
2832 if (Result.isComplexFloat()) {
2833 ComplexValue LHS = Result;
2834 APFloat &LHS_r = LHS.getComplexFloatReal();
2835 APFloat &LHS_i = LHS.getComplexFloatImag();
2836 APFloat &RHS_r = RHS.getComplexFloatReal();
2837 APFloat &RHS_i = RHS.getComplexFloatImag();
2838 APFloat &Res_r = Result.getComplexFloatReal();
2839 APFloat &Res_i = Result.getComplexFloatImag();
2840
2841 APFloat Den = RHS_r;
2842 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2843 APFloat Tmp = RHS_i;
2844 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2845 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2846
2847 Res_r = LHS_r;
2848 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2849 Tmp = LHS_i;
2850 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2851 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2852 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2853
2854 Res_i = LHS_i;
2855 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2856 Tmp = LHS_r;
2857 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2858 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2859 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2860 } else {
2861 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2862 // FIXME: what about diagnostics?
2863 return false;
2864 }
2865 ComplexValue LHS = Result;
2866 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2867 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2868 Result.getComplexIntReal() =
2869 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2870 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2871 Result.getComplexIntImag() =
2872 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2873 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2874 }
2875 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002876 }
2877
John McCall93d91dc2010-05-07 17:22:02 +00002878 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002879}
2880
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002881bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2882 // Get the operand value into 'Result'.
2883 if (!Visit(E->getSubExpr()))
2884 return false;
2885
2886 switch (E->getOpcode()) {
2887 default:
2888 // FIXME: what about diagnostics?
2889 return false;
2890 case UO_Extension:
2891 return true;
2892 case UO_Plus:
2893 // The result is always just the subexpr.
2894 return true;
2895 case UO_Minus:
2896 if (Result.isComplexFloat()) {
2897 Result.getComplexFloatReal().changeSign();
2898 Result.getComplexFloatImag().changeSign();
2899 }
2900 else {
2901 Result.getComplexIntReal() = -Result.getComplexIntReal();
2902 Result.getComplexIntImag() = -Result.getComplexIntImag();
2903 }
2904 return true;
2905 case UO_Not:
2906 if (Result.isComplexFloat())
2907 Result.getComplexFloatImag().changeSign();
2908 else
2909 Result.getComplexIntImag() = -Result.getComplexIntImag();
2910 return true;
2911 }
2912}
2913
Anders Carlsson537969c2008-11-16 20:27:53 +00002914//===----------------------------------------------------------------------===//
Chris Lattner67d7b922008-11-16 21:24:15 +00002915// Top level Expr::Evaluate method.
Chris Lattner05706e882008-07-11 18:11:29 +00002916//===----------------------------------------------------------------------===//
2917
Richard Smith725810a2011-10-16 21:26:27 +00002918static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002919 // In C, function designators are not lvalues, but we evaluate them as if they
2920 // are.
2921 if (E->isGLValue() || E->getType()->isFunctionType()) {
2922 LValue LV;
2923 if (!EvaluateLValue(E, LV, Info))
2924 return false;
2925 LV.moveInto(Result);
2926 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00002927 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002928 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002929 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00002930 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002931 return false;
John McCall45d55e42010-05-07 21:00:08 +00002932 } else if (E->getType()->hasPointerRepresentation()) {
2933 LValue LV;
2934 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002935 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002936 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00002937 } else if (E->getType()->isRealFloatingType()) {
2938 llvm::APFloat F(0.0);
2939 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002940 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002941 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00002942 } else if (E->getType()->isAnyComplexType()) {
2943 ComplexValue C;
2944 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002945 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002946 C.moveInto(Result);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002947 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00002948 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002949
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002950 return true;
2951}
2952
Richard Smith11562c52011-10-28 17:51:58 +00002953
John McCallc07a0c72011-02-17 10:25:35 +00002954/// Evaluate - Return true if this is a constant which we can fold using
2955/// any crazy technique (that has nothing to do with language standards) that
2956/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00002957/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
2958/// will be applied to the result.
John McCallc07a0c72011-02-17 10:25:35 +00002959bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2960 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00002961
2962 if (!::Evaluate(Result.Val, Info, this))
2963 return false;
2964
2965 if (isGLValue()) {
2966 LValue LV;
2967 LV.setFrom(Result.Val);
2968 return HandleLValueToRValueConversion(Info, getType(), LV, Result.Val);
2969 }
2970
2971 // FIXME: We don't allow expressions to fold to pointers or references to
2972 // locals. Code which calls Evaluate() isn't ready for that yet.
2973 return !Result.Val.isLValue() || IsGlobalLValue(Result.Val.getLValueBase());
John McCallc07a0c72011-02-17 10:25:35 +00002974}
2975
Jay Foad39c79802011-01-12 09:06:06 +00002976bool Expr::EvaluateAsBooleanCondition(bool &Result,
2977 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00002978 EvalResult Scratch;
2979 return Evaluate(Scratch, Ctx) && HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00002980}
2981
Richard Smithcaf33902011-10-10 18:28:20 +00002982bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00002983 EvalResult ExprResult;
2984 if (!Evaluate(ExprResult, Ctx) || ExprResult.HasSideEffects ||
2985 !ExprResult.Val.isInt()) {
2986 return false;
2987 }
2988 Result = ExprResult.Val.getInt();
2989 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00002990}
2991
Jay Foad39c79802011-01-12 09:06:06 +00002992bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00002993 EvalInfo Info(Ctx, Result);
2994
John McCall45d55e42010-05-07 21:00:08 +00002995 LValue LV;
Richard Smith11562c52011-10-28 17:51:58 +00002996 if (EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002997 IsGlobalLValue(LV.Base)) {
2998 LV.moveInto(Result.Val);
2999 return true;
3000 }
3001 return false;
3002}
3003
Jay Foad39c79802011-01-12 09:06:06 +00003004bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
3005 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003006 EvalInfo Info(Ctx, Result);
3007
3008 LValue LV;
3009 if (EvaluateLValue(this, LV, Info)) {
John McCall45d55e42010-05-07 21:00:08 +00003010 LV.moveInto(Result.Val);
3011 return true;
3012 }
3013 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00003014}
3015
Chris Lattner67d7b922008-11-16 21:24:15 +00003016/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattnercb136912008-10-06 06:49:02 +00003017/// folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00003018bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00003019 EvalResult Result;
3020 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00003021}
Anders Carlsson59689ed2008-11-22 21:04:56 +00003022
Jay Foad39c79802011-01-12 09:06:06 +00003023bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00003024 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003025}
3026
Richard Smithcaf33902011-10-10 18:28:20 +00003027APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003028 EvalResult EvalResult;
3029 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00003030 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00003031 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003032 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00003033
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003034 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00003035}
John McCall864e3962010-05-07 05:32:02 +00003036
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003037 bool Expr::EvalResult::isGlobalLValue() const {
3038 assert(Val.isLValue());
3039 return IsGlobalLValue(Val.getLValueBase());
3040 }
3041
3042
John McCall864e3962010-05-07 05:32:02 +00003043/// isIntegerConstantExpr - this recursive routine will test if an expression is
3044/// an integer constant expression.
3045
3046/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
3047/// comma, etc
3048///
3049/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
3050/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
3051/// cast+dereference.
3052
3053// CheckICE - This function does the fundamental ICE checking: the returned
3054// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
3055// Note that to reduce code duplication, this helper does no evaluation
3056// itself; the caller checks whether the expression is evaluatable, and
3057// in the rare cases where CheckICE actually cares about the evaluated
3058// value, it calls into Evalute.
3059//
3060// Meanings of Val:
3061// 0: This expression is an ICE if it can be evaluated by Evaluate.
3062// 1: This expression is not an ICE, but if it isn't evaluated, it's
3063// a legal subexpression for an ICE. This return value is used to handle
3064// the comma operator in C99 mode.
3065// 2: This expression is not an ICE, and is not a legal subexpression for one.
3066
Dan Gohman28ade552010-07-26 21:25:24 +00003067namespace {
3068
John McCall864e3962010-05-07 05:32:02 +00003069struct ICEDiag {
3070 unsigned Val;
3071 SourceLocation Loc;
3072
3073 public:
3074 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
3075 ICEDiag() : Val(0) {}
3076};
3077
Dan Gohman28ade552010-07-26 21:25:24 +00003078}
3079
3080static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00003081
3082static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
3083 Expr::EvalResult EVResult;
3084 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3085 !EVResult.Val.isInt()) {
3086 return ICEDiag(2, E->getLocStart());
3087 }
3088 return NoDiag();
3089}
3090
3091static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
3092 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00003093 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00003094 return ICEDiag(2, E->getLocStart());
3095 }
3096
3097 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00003098#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00003099#define STMT(Node, Base) case Expr::Node##Class:
3100#define EXPR(Node, Base)
3101#include "clang/AST/StmtNodes.inc"
3102 case Expr::PredefinedExprClass:
3103 case Expr::FloatingLiteralClass:
3104 case Expr::ImaginaryLiteralClass:
3105 case Expr::StringLiteralClass:
3106 case Expr::ArraySubscriptExprClass:
3107 case Expr::MemberExprClass:
3108 case Expr::CompoundAssignOperatorClass:
3109 case Expr::CompoundLiteralExprClass:
3110 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00003111 case Expr::DesignatedInitExprClass:
3112 case Expr::ImplicitValueInitExprClass:
3113 case Expr::ParenListExprClass:
3114 case Expr::VAArgExprClass:
3115 case Expr::AddrLabelExprClass:
3116 case Expr::StmtExprClass:
3117 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00003118 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00003119 case Expr::CXXDynamicCastExprClass:
3120 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00003121 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00003122 case Expr::CXXNullPtrLiteralExprClass:
3123 case Expr::CXXThisExprClass:
3124 case Expr::CXXThrowExprClass:
3125 case Expr::CXXNewExprClass:
3126 case Expr::CXXDeleteExprClass:
3127 case Expr::CXXPseudoDestructorExprClass:
3128 case Expr::UnresolvedLookupExprClass:
3129 case Expr::DependentScopeDeclRefExprClass:
3130 case Expr::CXXConstructExprClass:
3131 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00003132 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00003133 case Expr::CXXTemporaryObjectExprClass:
3134 case Expr::CXXUnresolvedConstructExprClass:
3135 case Expr::CXXDependentScopeMemberExprClass:
3136 case Expr::UnresolvedMemberExprClass:
3137 case Expr::ObjCStringLiteralClass:
3138 case Expr::ObjCEncodeExprClass:
3139 case Expr::ObjCMessageExprClass:
3140 case Expr::ObjCSelectorExprClass:
3141 case Expr::ObjCProtocolExprClass:
3142 case Expr::ObjCIvarRefExprClass:
3143 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00003144 case Expr::ObjCIsaExprClass:
3145 case Expr::ShuffleVectorExprClass:
3146 case Expr::BlockExprClass:
3147 case Expr::BlockDeclRefExprClass:
3148 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00003149 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00003150 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00003151 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00003152 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00003153 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00003154 case Expr::MaterializeTemporaryExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003155 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00003156 return ICEDiag(2, E->getLocStart());
3157
Sebastian Redl12757ab2011-09-24 17:48:14 +00003158 case Expr::InitListExprClass:
3159 if (Ctx.getLangOptions().CPlusPlus0x) {
3160 const InitListExpr *ILE = cast<InitListExpr>(E);
3161 if (ILE->getNumInits() == 0)
3162 return NoDiag();
3163 if (ILE->getNumInits() == 1)
3164 return CheckICE(ILE->getInit(0), Ctx);
3165 // Fall through for more than 1 expression.
3166 }
3167 return ICEDiag(2, E->getLocStart());
3168
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003169 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00003170 case Expr::GNUNullExprClass:
3171 // GCC considers the GNU __null value to be an integral constant expression.
3172 return NoDiag();
3173
John McCall7c454bb2011-07-15 05:09:51 +00003174 case Expr::SubstNonTypeTemplateParmExprClass:
3175 return
3176 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
3177
John McCall864e3962010-05-07 05:32:02 +00003178 case Expr::ParenExprClass:
3179 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00003180 case Expr::GenericSelectionExprClass:
3181 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003182 case Expr::IntegerLiteralClass:
3183 case Expr::CharacterLiteralClass:
3184 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00003185 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00003186 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003187 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00003188 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00003189 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003190 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00003191 return NoDiag();
3192 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00003193 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00003194 // C99 6.6/3 allows function calls within unevaluated subexpressions of
3195 // constant expressions, but they can never be ICEs because an ICE cannot
3196 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00003197 const CallExpr *CE = cast<CallExpr>(E);
3198 if (CE->isBuiltinCall(Ctx))
3199 return CheckEvalInICE(E, Ctx);
3200 return ICEDiag(2, E->getLocStart());
3201 }
3202 case Expr::DeclRefExprClass:
3203 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
3204 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00003205 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00003206 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3207
3208 // Parameter variables are never constants. Without this check,
3209 // getAnyInitializer() can find a default argument, which leads
3210 // to chaos.
3211 if (isa<ParmVarDecl>(D))
3212 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3213
3214 // C++ 7.1.5.1p2
3215 // A variable of non-volatile const-qualified integral or enumeration
3216 // type initialized by an ICE can be used in ICEs.
3217 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCall864e3962010-05-07 05:32:02 +00003218 // Look for a declaration of this variable that has an initializer.
3219 const VarDecl *ID = 0;
3220 const Expr *Init = Dcl->getAnyInitializer(ID);
3221 if (Init) {
3222 if (ID->isInitKnownICE()) {
3223 // We have already checked whether this subexpression is an
3224 // integral constant expression.
3225 if (ID->isInitICE())
3226 return NoDiag();
3227 else
3228 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3229 }
3230
3231 // It's an ICE whether or not the definition we found is
3232 // out-of-line. See DR 721 and the discussion in Clang PR
3233 // 6206 for details.
3234
3235 if (Dcl->isCheckingICE()) {
3236 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3237 }
3238
3239 Dcl->setCheckingICE();
3240 ICEDiag Result = CheckICE(Init, Ctx);
3241 // Cache the result of the ICE test.
3242 Dcl->setInitKnownICE(Result.Val == 0);
3243 return Result;
3244 }
3245 }
3246 }
3247 return ICEDiag(2, E->getLocStart());
3248 case Expr::UnaryOperatorClass: {
3249 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3250 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003251 case UO_PostInc:
3252 case UO_PostDec:
3253 case UO_PreInc:
3254 case UO_PreDec:
3255 case UO_AddrOf:
3256 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00003257 // C99 6.6/3 allows increment and decrement within unevaluated
3258 // subexpressions of constant expressions, but they can never be ICEs
3259 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003260 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00003261 case UO_Extension:
3262 case UO_LNot:
3263 case UO_Plus:
3264 case UO_Minus:
3265 case UO_Not:
3266 case UO_Real:
3267 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003268 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003269 }
3270
3271 // OffsetOf falls through here.
3272 }
3273 case Expr::OffsetOfExprClass: {
3274 // Note that per C99, offsetof must be an ICE. And AFAIK, using
3275 // Evaluate matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00003276 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00003277 // compliance: we should warn earlier for offsetof expressions with
3278 // array subscripts that aren't ICEs, and if the array subscripts
3279 // are ICEs, the value of the offsetof must be an integer constant.
3280 return CheckEvalInICE(E, Ctx);
3281 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003282 case Expr::UnaryExprOrTypeTraitExprClass: {
3283 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3284 if ((Exp->getKind() == UETT_SizeOf) &&
3285 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003286 return ICEDiag(2, E->getLocStart());
3287 return NoDiag();
3288 }
3289 case Expr::BinaryOperatorClass: {
3290 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3291 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003292 case BO_PtrMemD:
3293 case BO_PtrMemI:
3294 case BO_Assign:
3295 case BO_MulAssign:
3296 case BO_DivAssign:
3297 case BO_RemAssign:
3298 case BO_AddAssign:
3299 case BO_SubAssign:
3300 case BO_ShlAssign:
3301 case BO_ShrAssign:
3302 case BO_AndAssign:
3303 case BO_XorAssign:
3304 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00003305 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3306 // constant expressions, but they can never be ICEs because an ICE cannot
3307 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003308 return ICEDiag(2, E->getLocStart());
3309
John McCalle3027922010-08-25 11:45:40 +00003310 case BO_Mul:
3311 case BO_Div:
3312 case BO_Rem:
3313 case BO_Add:
3314 case BO_Sub:
3315 case BO_Shl:
3316 case BO_Shr:
3317 case BO_LT:
3318 case BO_GT:
3319 case BO_LE:
3320 case BO_GE:
3321 case BO_EQ:
3322 case BO_NE:
3323 case BO_And:
3324 case BO_Xor:
3325 case BO_Or:
3326 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003327 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3328 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003329 if (Exp->getOpcode() == BO_Div ||
3330 Exp->getOpcode() == BO_Rem) {
John McCall864e3962010-05-07 05:32:02 +00003331 // Evaluate gives an error for undefined Div/Rem, so make sure
3332 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003333 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003334 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003335 if (REval == 0)
3336 return ICEDiag(1, E->getLocStart());
3337 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003338 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003339 if (LEval.isMinSignedValue())
3340 return ICEDiag(1, E->getLocStart());
3341 }
3342 }
3343 }
John McCalle3027922010-08-25 11:45:40 +00003344 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003345 if (Ctx.getLangOptions().C99) {
3346 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3347 // if it isn't evaluated.
3348 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3349 return ICEDiag(1, E->getLocStart());
3350 } else {
3351 // In both C89 and C++, commas in ICEs are illegal.
3352 return ICEDiag(2, E->getLocStart());
3353 }
3354 }
3355 if (LHSResult.Val >= RHSResult.Val)
3356 return LHSResult;
3357 return RHSResult;
3358 }
John McCalle3027922010-08-25 11:45:40 +00003359 case BO_LAnd:
3360 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003361 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003362
3363 // C++0x [expr.const]p2:
3364 // [...] subexpressions of logical AND (5.14), logical OR
3365 // (5.15), and condi- tional (5.16) operations that are not
3366 // evaluated are not considered.
3367 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3368 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003369 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003370 return LHSResult;
3371
3372 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003373 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003374 return LHSResult;
3375 }
3376
John McCall864e3962010-05-07 05:32:02 +00003377 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3378 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3379 // Rare case where the RHS has a comma "side-effect"; we need
3380 // to actually check the condition to see whether the side
3381 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003382 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003383 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003384 return RHSResult;
3385 return NoDiag();
3386 }
3387
3388 if (LHSResult.Val >= RHSResult.Val)
3389 return LHSResult;
3390 return RHSResult;
3391 }
3392 }
3393 }
3394 case Expr::ImplicitCastExprClass:
3395 case Expr::CStyleCastExprClass:
3396 case Expr::CXXFunctionalCastExprClass:
3397 case Expr::CXXStaticCastExprClass:
3398 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00003399 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003400 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003401 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00003402 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00003403 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3404 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00003405 switch (cast<CastExpr>(E)->getCastKind()) {
3406 case CK_LValueToRValue:
3407 case CK_NoOp:
3408 case CK_IntegralToBoolean:
3409 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003410 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003411 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00003412 return ICEDiag(2, E->getLocStart());
3413 }
John McCall864e3962010-05-07 05:32:02 +00003414 }
John McCallc07a0c72011-02-17 10:25:35 +00003415 case Expr::BinaryConditionalOperatorClass: {
3416 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3417 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3418 if (CommonResult.Val == 2) return CommonResult;
3419 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3420 if (FalseResult.Val == 2) return FalseResult;
3421 if (CommonResult.Val == 1) return CommonResult;
3422 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003423 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003424 return FalseResult;
3425 }
John McCall864e3962010-05-07 05:32:02 +00003426 case Expr::ConditionalOperatorClass: {
3427 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3428 // If the condition (ignoring parens) is a __builtin_constant_p call,
3429 // then only the true side is actually considered in an integer constant
3430 // expression, and it is fully evaluated. This is an important GNU
3431 // extension. See GCC PR38377 for discussion.
3432 if (const CallExpr *CallCE
3433 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3434 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3435 Expr::EvalResult EVResult;
3436 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3437 !EVResult.Val.isInt()) {
3438 return ICEDiag(2, E->getLocStart());
3439 }
3440 return NoDiag();
3441 }
3442 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003443 if (CondResult.Val == 2)
3444 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003445
3446 // C++0x [expr.const]p2:
3447 // subexpressions of [...] conditional (5.16) operations that
3448 // are not evaluated are not considered
3449 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003450 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003451 : false;
3452 ICEDiag TrueResult = NoDiag();
3453 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3454 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3455 ICEDiag FalseResult = NoDiag();
3456 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3457 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3458
John McCall864e3962010-05-07 05:32:02 +00003459 if (TrueResult.Val == 2)
3460 return TrueResult;
3461 if (FalseResult.Val == 2)
3462 return FalseResult;
3463 if (CondResult.Val == 1)
3464 return CondResult;
3465 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3466 return NoDiag();
3467 // Rare case where the diagnostics depend on which side is evaluated
3468 // Note that if we get here, CondResult is 0, and at least one of
3469 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003470 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003471 return FalseResult;
3472 }
3473 return TrueResult;
3474 }
3475 case Expr::CXXDefaultArgExprClass:
3476 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3477 case Expr::ChooseExprClass: {
3478 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3479 }
3480 }
3481
3482 // Silence a GCC warning
3483 return ICEDiag(2, E->getLocStart());
3484}
3485
3486bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3487 SourceLocation *Loc, bool isEvaluated) const {
3488 ICEDiag d = CheckICE(this, Ctx);
3489 if (d.Val != 0) {
3490 if (Loc) *Loc = d.Loc;
3491 return false;
3492 }
Richard Smith11562c52011-10-28 17:51:58 +00003493 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00003494 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00003495 return true;
3496}