blob: e5bff359f8504d847015f4a85832396504d82d41 [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
Richard Smith0b0a0b62011-10-29 20:57:55 +000031static bool IsParamLValue(const Expr *E);
32
Chris Lattnercdf34e72008-07-11 22:52:41 +000033/// EvalInfo - This is a private struct used by the evaluator to capture
34/// information about a subexpression as it is folded. It retains information
35/// about the AST context, but also maintains information about the folded
36/// expression.
37///
38/// If an expression could be evaluated, it is still possible it is not a C
39/// "integer constant expression" or constant expression. If not, this struct
40/// captures information about how and why not.
41///
42/// One bit of information passed *into* the request for constant folding
43/// indicates whether the subexpression is "evaluated" or not according to C
44/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
45/// evaluate the expression regardless of what the RHS is, but C only allows
46/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000047namespace {
Richard Smith254a73d2011-10-28 22:34:42 +000048 struct CallStackFrame;
49
Richard Smith0b0a0b62011-10-29 20:57:55 +000050 /// A core constant value. This can be the value of any constant expression,
51 /// or a pointer or reference to a non-static object or function parameter.
52 class CCValue : public APValue {
53 typedef llvm::APSInt APSInt;
54 typedef llvm::APFloat APFloat;
55 /// If the value is a DeclRefExpr lvalue referring to a ParmVarDecl, this is
56 /// the index of the corresponding function call.
57 unsigned CallIndex;
58 public:
59 CCValue() {}
60 explicit CCValue(const APSInt &I) : APValue(I) {}
61 explicit CCValue(const APFloat &F) : APValue(F) {}
62 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
63 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
64 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
65 CCValue(const CCValue &V) : APValue(V), CallIndex(V.CallIndex) {}
66 CCValue(const Expr *B, const CharUnits &O, unsigned I) :
67 APValue(B, O), CallIndex(I) {}
68 CCValue(const APValue &V, unsigned CallIndex) :
69 APValue(V), CallIndex(CallIndex) {}
70
71 enum { NoCallIndex = (unsigned)-1 };
72
73 unsigned getLValueCallIndex() const {
74 assert(getKind() == LValue);
75 return CallIndex;
76 }
77 };
78
Benjamin Kramer024e6192011-03-04 13:12:48 +000079 struct EvalInfo {
80 const ASTContext &Ctx;
81
Richard Smith725810a2011-10-16 21:26:27 +000082 /// EvalStatus - Contains information about the evaluation.
83 Expr::EvalStatus &EvalStatus;
Benjamin Kramer024e6192011-03-04 13:12:48 +000084
Richard Smith254a73d2011-10-28 22:34:42 +000085 /// CurrentCall - The top of the constexpr call stack.
86 const CallStackFrame *CurrentCall;
87
88 /// NumCalls - The number of calls we've evaluated so far.
89 unsigned NumCalls;
90
91 /// CallStackDepth - The number of calls in the call stack right now.
92 unsigned CallStackDepth;
93
Richard Smith0b0a0b62011-10-29 20:57:55 +000094 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
Benjamin Kramer024e6192011-03-04 13:12:48 +000095 MapTy OpaqueValues;
Richard Smith0b0a0b62011-10-29 20:57:55 +000096 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
Benjamin Kramer024e6192011-03-04 13:12:48 +000097 MapTy::const_iterator i = OpaqueValues.find(e);
98 if (i == OpaqueValues.end()) return 0;
99 return &i->second;
100 }
101
Richard Smith0b0a0b62011-10-29 20:57:55 +0000102 unsigned getCurrentCallIndex() const;
103 const CCValue *getCallValue(unsigned CallIndex, unsigned ArgIndex) const;
104
Richard Smith725810a2011-10-16 21:26:27 +0000105 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith254a73d2011-10-28 22:34:42 +0000106 : Ctx(C), EvalStatus(S), CurrentCall(0), NumCalls(0), CallStackDepth(0) {}
Richard Smith4ce706a2011-10-11 21:43:33 +0000107
108 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
Benjamin Kramer024e6192011-03-04 13:12:48 +0000109 };
110
Richard Smith254a73d2011-10-28 22:34:42 +0000111 /// A stack frame in the constexpr call stack.
112 struct CallStackFrame {
113 EvalInfo &Info;
114
115 /// Parent - The caller of this stack frame.
116 const CallStackFrame *Caller;
117
118 /// ParmBindings - Parameter bindings for this function call, indexed by
119 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000120 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000121
122 /// CallIndex - The index of the current call. This is used to match lvalues
123 /// referring to parameters up with the corresponding stack frame, and to
124 /// detect when the parameter is no longer in scope.
125 unsigned CallIndex;
126
Richard Smith0b0a0b62011-10-29 20:57:55 +0000127 CallStackFrame(EvalInfo &Info, const CCValue *Arguments)
Richard Smith254a73d2011-10-28 22:34:42 +0000128 : Info(Info), Caller(Info.CurrentCall), Arguments(Arguments),
129 CallIndex(Info.NumCalls++) {
130 Info.CurrentCall = this;
131 ++Info.CallStackDepth;
132 }
133 ~CallStackFrame() {
134 assert(Info.CurrentCall == this && "calls retired out of order");
135 --Info.CallStackDepth;
136 Info.CurrentCall = Caller;
137 }
138 };
139
Richard Smith0b0a0b62011-10-29 20:57:55 +0000140 unsigned EvalInfo::getCurrentCallIndex() const {
141 return CurrentCall ? CurrentCall->CallIndex : CCValue::NoCallIndex;
142 }
143
144 const CCValue *EvalInfo::getCallValue(unsigned CallIndex,
145 unsigned ArgIndex) const {
146 for (const CallStackFrame *Frame = CurrentCall;
147 Frame && Frame->CallIndex >= CallIndex; Frame = Frame->Caller)
148 if (Frame->CallIndex == CallIndex)
149 return Frame->Arguments + ArgIndex;
150 return 0;
151 }
152
John McCall93d91dc2010-05-07 17:22:02 +0000153 struct ComplexValue {
154 private:
155 bool IsInt;
156
157 public:
158 APSInt IntReal, IntImag;
159 APFloat FloatReal, FloatImag;
160
161 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
162
163 void makeComplexFloat() { IsInt = false; }
164 bool isComplexFloat() const { return !IsInt; }
165 APFloat &getComplexFloatReal() { return FloatReal; }
166 APFloat &getComplexFloatImag() { return FloatImag; }
167
168 void makeComplexInt() { IsInt = true; }
169 bool isComplexInt() const { return IsInt; }
170 APSInt &getComplexIntReal() { return IntReal; }
171 APSInt &getComplexIntImag() { return IntImag; }
172
Richard Smith0b0a0b62011-10-29 20:57:55 +0000173 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000174 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000175 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000176 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000177 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000178 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000179 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000180 assert(v.isComplexFloat() || v.isComplexInt());
181 if (v.isComplexFloat()) {
182 makeComplexFloat();
183 FloatReal = v.getComplexFloatReal();
184 FloatImag = v.getComplexFloatImag();
185 } else {
186 makeComplexInt();
187 IntReal = v.getComplexIntReal();
188 IntImag = v.getComplexIntImag();
189 }
190 }
John McCall93d91dc2010-05-07 17:22:02 +0000191 };
John McCall45d55e42010-05-07 21:00:08 +0000192
193 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000194 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000195 CharUnits Offset;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000196 unsigned CallIndex;
John McCall45d55e42010-05-07 21:00:08 +0000197
Peter Collingbournee9200682011-05-13 03:29:01 +0000198 const Expr *getLValueBase() { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000199 CharUnits &getLValueOffset() { return Offset; }
200 unsigned getLValueCallIndex() { return CallIndex; }
John McCall45d55e42010-05-07 21:00:08 +0000201
Richard Smith0b0a0b62011-10-29 20:57:55 +0000202 void moveInto(CCValue &V) const {
203 V = CCValue(Base, Offset, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000204 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000205 void setFrom(const CCValue &V) {
206 assert(V.isLValue());
207 Base = V.getLValueBase();
208 Offset = V.getLValueOffset();
209 CallIndex = V.getLValueCallIndex();
John McCallc07a0c72011-02-17 10:25:35 +0000210 }
John McCall45d55e42010-05-07 21:00:08 +0000211 };
John McCall93d91dc2010-05-07 17:22:02 +0000212}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000213
Richard Smith0b0a0b62011-10-29 20:57:55 +0000214static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000215static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
216static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000217static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000218static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000219 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000220static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000221static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000222
223//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000224// Misc utilities
225//===----------------------------------------------------------------------===//
226
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000227static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000228 if (!E) return true;
229
230 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
231 if (isa<FunctionDecl>(DRE->getDecl()))
232 return true;
233 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
234 return VD->hasGlobalStorage();
235 return false;
236 }
237
238 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
239 return CLE->isFileScope();
240
Richard Smith11562c52011-10-28 17:51:58 +0000241 if (isa<MemberExpr>(E))
242 return false;
243
John McCall95007602010-05-10 23:27:23 +0000244 return true;
245}
246
Richard Smith0b0a0b62011-10-29 20:57:55 +0000247static bool IsParamLValue(const Expr *E) {
248 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
249 return isa<ParmVarDecl>(DRE->getDecl());
250 return false;
251}
252
253/// Check that this core constant expression value is a valid value for a
254/// constant expression.
255static bool CheckConstantExpression(const CCValue &Value) {
256 return !Value.isLValue() || IsGlobalLValue(Value.getLValueBase());
257}
258
Richard Smith11562c52011-10-28 17:51:58 +0000259static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCall45d55e42010-05-07 21:00:08 +0000260 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000261
John McCalleb3e4f32010-05-07 21:34:32 +0000262 // A null base expression indicates a null pointer. These are always
263 // evaluatable, and they are false unless the offset is zero.
264 if (!Base) {
265 Result = !Value.Offset.isZero();
266 return true;
267 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000268
John McCall95007602010-05-10 23:27:23 +0000269 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000270 // FIXME: C++11 requires such conversions. Remove this check.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000271 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000272
John McCalleb3e4f32010-05-07 21:34:32 +0000273 // We have a non-null base expression. These are generally known to
274 // be true, but if it'a decl-ref to a weak symbol it can be null at
275 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000276 Result = true;
277
278 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000279 if (!DeclRef)
280 return true;
281
John McCalleb3e4f32010-05-07 21:34:32 +0000282 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000283 const ValueDecl* Decl = DeclRef->getDecl();
284 if (Decl->hasAttr<WeakAttr>() ||
285 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000286 Decl->isWeakImported())
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000287 return false;
288
Eli Friedman334046a2009-06-14 02:17:33 +0000289 return true;
290}
291
Richard Smith0b0a0b62011-10-29 20:57:55 +0000292static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000293 switch (Val.getKind()) {
294 case APValue::Uninitialized:
295 return false;
296 case APValue::Int:
297 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000298 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000299 case APValue::Float:
300 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000301 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000302 case APValue::ComplexInt:
303 Result = Val.getComplexIntReal().getBoolValue() ||
304 Val.getComplexIntImag().getBoolValue();
305 return true;
306 case APValue::ComplexFloat:
307 Result = !Val.getComplexFloatReal().isZero() ||
308 !Val.getComplexFloatImag().isZero();
309 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000310 case APValue::LValue: {
311 LValue PointerResult;
312 PointerResult.setFrom(Val);
313 return EvalPointerValueAsBool(PointerResult, Result);
314 }
Richard Smith11562c52011-10-28 17:51:58 +0000315 case APValue::Vector:
316 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000317 }
318
Richard Smith11562c52011-10-28 17:51:58 +0000319 llvm_unreachable("unknown APValue kind");
320}
321
322static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
323 EvalInfo &Info) {
324 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000325 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000326 if (!Evaluate(Val, Info, E))
327 return false;
328 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000329}
330
Mike Stump11289f42009-09-09 15:08:12 +0000331static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000332 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000333 unsigned DestWidth = Ctx.getIntWidth(DestType);
334 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000335 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000336
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000337 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000338 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000339 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000340 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
341 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000342}
343
Mike Stump11289f42009-09-09 15:08:12 +0000344static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000345 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000346 bool ignored;
347 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000348 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000349 APFloat::rmNearestTiesToEven, &ignored);
350 return Result;
351}
352
Mike Stump11289f42009-09-09 15:08:12 +0000353static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000354 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000355 unsigned DestWidth = Ctx.getIntWidth(DestType);
356 APSInt Result = Value;
357 // Figure out if this is a truncate, extend or noop cast.
358 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000359 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000360 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000361 return Result;
362}
363
Mike Stump11289f42009-09-09 15:08:12 +0000364static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000365 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000366
367 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
368 Result.convertFromAPInt(Value, Value.isSigned(),
369 APFloat::rmNearestTiesToEven);
370 return Result;
371}
372
Richard Smith27908702011-10-24 17:54:18 +0000373/// Try to evaluate the initializer for a variable declaration.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000374static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD,
375 unsigned CallIndex, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000376 // If this is a parameter to an active constexpr function call, perform
377 // argument substitution.
378 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000379 if (const CCValue *ArgValue =
380 Info.getCallValue(CallIndex, PVD->getFunctionScopeIndex())) {
381 Result = *ArgValue;
382 return true;
383 }
384 return false;
Richard Smith254a73d2011-10-28 22:34:42 +0000385 }
Richard Smith27908702011-10-24 17:54:18 +0000386
387 const Expr *Init = VD->getAnyInitializer();
388 if (!Init)
Richard Smith0b0a0b62011-10-29 20:57:55 +0000389 return false;
Richard Smith27908702011-10-24 17:54:18 +0000390
Richard Smith0b0a0b62011-10-29 20:57:55 +0000391 if (APValue *V = VD->getEvaluatedValue()) {
392 Result = CCValue(*V, CCValue::NoCallIndex);
393 return !Result.isUninit();
394 }
Richard Smith27908702011-10-24 17:54:18 +0000395
396 if (VD->isEvaluatingValue())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000397 return false;
Richard Smith27908702011-10-24 17:54:18 +0000398
399 VD->setEvaluatingValue();
400
Richard Smith0b0a0b62011-10-29 20:57:55 +0000401 Expr::EvalStatus EStatus;
402 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith11562c52011-10-28 17:51:58 +0000403 // FIXME: The caller will need to know whether the value was a constant
404 // expression. If not, we should propagate up a diagnostic.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000405 if (!Evaluate(Result, InitInfo, Init) || !CheckConstantExpression(Result)) {
Richard Smith27908702011-10-24 17:54:18 +0000406 VD->setEvaluatedValue(APValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000407 return false;
408 }
Richard Smith27908702011-10-24 17:54:18 +0000409
Richard Smith0b0a0b62011-10-29 20:57:55 +0000410 VD->setEvaluatedValue(Result);
411 return true;
Richard Smith27908702011-10-24 17:54:18 +0000412}
413
Richard Smith11562c52011-10-28 17:51:58 +0000414static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000415 Qualifiers Quals = T.getQualifiers();
416 return Quals.hasConst() && !Quals.hasVolatile();
417}
418
Richard Smith11562c52011-10-28 17:51:58 +0000419bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000420 const LValue &LVal, CCValue &RVal) {
Richard Smith11562c52011-10-28 17:51:58 +0000421 const Expr *Base = LVal.Base;
422
423 // FIXME: Indirection through a null pointer deserves a diagnostic.
424 if (!Base)
425 return false;
426
427 // FIXME: Support accessing subobjects of objects of literal types. A simple
428 // byte offset is insufficient for C++11 semantics: we need to know how the
429 // reference was formed (which union member was named, for instance).
430 // FIXME: Support subobjects of StringLiteral and PredefinedExpr.
431 if (!LVal.Offset.isZero())
432 return false;
433
434 const Decl *D = 0;
435
436 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
437 // If the lvalue has been cast to some other type, don't try to read it.
438 // FIXME: Could simulate a bitcast here.
439 if (!Info.Ctx.hasSameUnqualifiedType(Type, DRE->getType()))
440 return false;
441 D = DRE->getDecl();
442 }
443
444 // FIXME: Static data members accessed via a MemberExpr are represented as
445 // that MemberExpr. We should use the Decl directly instead.
446 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
447 if (!Info.Ctx.hasSameUnqualifiedType(Type, ME->getType()))
448 return false;
449 D = ME->getMemberDecl();
450 assert(!isa<FieldDecl>(D) && "shouldn't see fields here");
451 }
452
453 if (D) {
454 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
455 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +0000456 // expressions are constant expressions too. Inside constexpr functions,
457 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +0000458 // In C, such things can also be folded, although they are not ICEs.
459 //
Richard Smith254a73d2011-10-28 22:34:42 +0000460 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
461 // interpretation of C++11 suggests that volatile parameters are OK if
462 // they're never read (there's no prohibition against constructing volatile
463 // objects in constant expressions), but lvalue-to-rvalue conversions on
464 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +0000465 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith254a73d2011-10-28 22:34:42 +0000466 if (!VD || !(IsConstNonVolatile(VD->getType()) || isa<ParmVarDecl>(VD)) ||
Richard Smith35a1f852011-10-29 21:53:17 +0000467 !Type->isLiteralType() ||
Richard Smith0b0a0b62011-10-29 20:57:55 +0000468 !EvaluateVarDeclInit(Info, VD, LVal.CallIndex, RVal))
Richard Smith11562c52011-10-28 17:51:58 +0000469 return false;
470
Richard Smith0b0a0b62011-10-29 20:57:55 +0000471 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smith11562c52011-10-28 17:51:58 +0000472 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000473
474 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
475 // conversion. This happens when the declaration and the lvalue should be
476 // considered synonymous, for instance when initializing an array of char
477 // from a string literal. Continue as if the initializer lvalue was the
478 // value we were originally given.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000479 if (!RVal.getLValueOffset().isZero())
Richard Smith11562c52011-10-28 17:51:58 +0000480 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000481 Base = RVal.getLValueBase();
Richard Smith11562c52011-10-28 17:51:58 +0000482 }
483
484 // FIXME: C++11: Support MaterializeTemporaryExpr in LValueExprEvaluator and
485 // here.
486
487 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
488 // initializer until now for such expressions. Such an expression can't be
489 // an ICE in C, so this only matters for fold.
490 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
491 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
492 return Evaluate(RVal, Info, CLE->getInitializer());
493 }
494
495 return false;
496}
497
Mike Stump876387b2009-10-27 22:09:17 +0000498namespace {
Richard Smith254a73d2011-10-28 22:34:42 +0000499enum EvalStmtResult {
500 /// Evaluation failed.
501 ESR_Failed,
502 /// Hit a 'return' statement.
503 ESR_Returned,
504 /// Evaluation succeeded.
505 ESR_Succeeded
506};
507}
508
509// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000510static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +0000511 const Stmt *S) {
512 switch (S->getStmtClass()) {
513 default:
514 return ESR_Failed;
515
516 case Stmt::NullStmtClass:
517 case Stmt::DeclStmtClass:
518 return ESR_Succeeded;
519
520 case Stmt::ReturnStmtClass:
521 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
522 return ESR_Returned;
523 return ESR_Failed;
524
525 case Stmt::CompoundStmtClass: {
526 const CompoundStmt *CS = cast<CompoundStmt>(S);
527 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
528 BE = CS->body_end(); BI != BE; ++BI) {
529 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
530 if (ESR != ESR_Succeeded)
531 return ESR;
532 }
533 return ESR_Succeeded;
534 }
535 }
536}
537
538/// Evaluate a function call.
539static bool HandleFunctionCall(ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000540 EvalInfo &Info, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000541 // FIXME: Implement a proper call limit, along with a command-line flag.
542 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
543 return false;
544
Richard Smith0b0a0b62011-10-29 20:57:55 +0000545 SmallVector<CCValue, 16> ArgValues(Args.size());
Richard Smith254a73d2011-10-28 22:34:42 +0000546 // FIXME: Deal with default arguments and 'this'.
547 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
548 I != E; ++I)
549 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
550 return false;
551
552 CallStackFrame Frame(Info, ArgValues.data());
553 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
554}
555
556namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000557class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000558 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000559 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000560public:
561
Richard Smith725810a2011-10-16 21:26:27 +0000562 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000563
564 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000565 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000566 return true;
567 }
568
Peter Collingbournee9200682011-05-13 03:29:01 +0000569 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
570 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000571 return Visit(E->getResultExpr());
572 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000573 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000574 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000575 return true;
576 return false;
577 }
John McCall31168b02011-06-15 23:02:42 +0000578 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000579 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000580 return true;
581 return false;
582 }
583 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000584 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000585 return true;
586 return false;
587 }
588
Mike Stump876387b2009-10-27 22:09:17 +0000589 // We don't want to evaluate BlockExprs multiple times, as they generate
590 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000591 bool VisitBlockExpr(const BlockExpr *E) { return true; }
592 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
593 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000594 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000595 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
596 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
597 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
598 bool VisitStringLiteral(const StringLiteral *E) { return false; }
599 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
600 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000601 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000602 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000603 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000604 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000605 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000606 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
607 bool VisitBinAssign(const BinaryOperator *E) { return true; }
608 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
609 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000610 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000611 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
612 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
613 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
614 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
615 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000616 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000617 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000618 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000619 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000620 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000621
622 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000623 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000624 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
625 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000626 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000627 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000628 return false;
629 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000630
Peter Collingbournee9200682011-05-13 03:29:01 +0000631 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000632};
633
John McCallc07a0c72011-02-17 10:25:35 +0000634class OpaqueValueEvaluation {
635 EvalInfo &info;
636 OpaqueValueExpr *opaqueValue;
637
638public:
639 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
640 Expr *value)
641 : info(info), opaqueValue(opaqueValue) {
642
643 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000644 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000645 this->opaqueValue = 0;
646 return;
647 }
John McCallc07a0c72011-02-17 10:25:35 +0000648 }
649
650 bool hasError() const { return opaqueValue == 0; }
651
652 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000653 // FIXME: This will not work for recursive constexpr functions using opaque
654 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000655 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
656 }
657};
658
Mike Stump876387b2009-10-27 22:09:17 +0000659} // end anonymous namespace
660
Eli Friedman9a156e52008-11-12 09:44:48 +0000661//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000662// Generic Evaluation
663//===----------------------------------------------------------------------===//
664namespace {
665
666template <class Derived, typename RetTy=void>
667class ExprEvaluatorBase
668 : public ConstStmtVisitor<Derived, RetTy> {
669private:
Richard Smith0b0a0b62011-10-29 20:57:55 +0000670 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000671 return static_cast<Derived*>(this)->Success(V, E);
672 }
673 RetTy DerivedError(const Expr *E) {
674 return static_cast<Derived*>(this)->Error(E);
675 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000676 RetTy DerivedValueInitialization(const Expr *E) {
677 return static_cast<Derived*>(this)->ValueInitialization(E);
678 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000679
680protected:
681 EvalInfo &Info;
682 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
683 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
684
Richard Smith4ce706a2011-10-11 21:43:33 +0000685 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
686
Peter Collingbournee9200682011-05-13 03:29:01 +0000687public:
688 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
689
690 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000691 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000692 }
693 RetTy VisitExpr(const Expr *E) {
694 return DerivedError(E);
695 }
696
697 RetTy VisitParenExpr(const ParenExpr *E)
698 { return StmtVisitorTy::Visit(E->getSubExpr()); }
699 RetTy VisitUnaryExtension(const UnaryOperator *E)
700 { return StmtVisitorTy::Visit(E->getSubExpr()); }
701 RetTy VisitUnaryPlus(const UnaryOperator *E)
702 { return StmtVisitorTy::Visit(E->getSubExpr()); }
703 RetTy VisitChooseExpr(const ChooseExpr *E)
704 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
705 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
706 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000707 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
708 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000709
710 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
711 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
712 if (opaque.hasError())
713 return DerivedError(E);
714
715 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +0000716 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000717 return DerivedError(E);
718
719 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
720 }
721
722 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
723 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +0000724 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000725 return DerivedError(E);
726
Richard Smith11562c52011-10-28 17:51:58 +0000727 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +0000728 return StmtVisitorTy::Visit(EvalExpr);
729 }
730
731 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000732 const CCValue *Value = Info.getOpaqueValue(E);
733 if (!Value)
Peter Collingbournee9200682011-05-13 03:29:01 +0000734 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
735 : DerivedError(E));
Richard Smith0b0a0b62011-10-29 20:57:55 +0000736 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000737 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000738
Richard Smith254a73d2011-10-28 22:34:42 +0000739 RetTy VisitCallExpr(const CallExpr *E) {
740 const Expr *Callee = E->getCallee();
741 QualType CalleeType = Callee->getType();
742
743 // FIXME: Handle the case where Callee is a (parenthesized) MemberExpr for a
744 // non-static member function.
745 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember))
746 return DerivedError(E);
747
748 if (!CalleeType->isFunctionType() && !CalleeType->isFunctionPointerType())
749 return DerivedError(E);
750
Richard Smith0b0a0b62011-10-29 20:57:55 +0000751 CCValue Call;
Richard Smith254a73d2011-10-28 22:34:42 +0000752 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
753 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
754 return DerivedError(Callee);
755
756 const FunctionDecl *FD = 0;
757 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Call.getLValueBase()))
758 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
759 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Call.getLValueBase()))
760 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
761 if (!FD)
762 return DerivedError(Callee);
763
764 // Don't call function pointers which have been cast to some other type.
765 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
766 return DerivedError(E);
767
768 const FunctionDecl *Definition;
769 Stmt *Body = FD->getBody(Definition);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000770 CCValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +0000771 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
772
773 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
774 HandleFunctionCall(Args, Body, Info, Result))
775 return DerivedSuccess(Result, E);
776
777 return DerivedError(E);
778 }
779
Richard Smith11562c52011-10-28 17:51:58 +0000780 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
781 return StmtVisitorTy::Visit(E->getInitializer());
782 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000783 RetTy VisitInitListExpr(const InitListExpr *E) {
784 if (Info.getLangOpts().CPlusPlus0x) {
785 if (E->getNumInits() == 0)
786 return DerivedValueInitialization(E);
787 if (E->getNumInits() == 1)
788 return StmtVisitorTy::Visit(E->getInit(0));
789 }
790 return DerivedError(E);
791 }
792 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
793 return DerivedValueInitialization(E);
794 }
795 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
796 return DerivedValueInitialization(E);
797 }
798
Richard Smith11562c52011-10-28 17:51:58 +0000799 RetTy VisitCastExpr(const CastExpr *E) {
800 switch (E->getCastKind()) {
801 default:
802 break;
803
804 case CK_NoOp:
805 return StmtVisitorTy::Visit(E->getSubExpr());
806
807 case CK_LValueToRValue: {
808 LValue LVal;
809 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000810 CCValue RVal;
Richard Smith11562c52011-10-28 17:51:58 +0000811 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
812 return DerivedSuccess(RVal, E);
813 }
814 break;
815 }
816 }
817
818 return DerivedError(E);
819 }
820
Richard Smith4a678122011-10-24 18:44:57 +0000821 /// Visit a value which is evaluated, but whose value is ignored.
822 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000823 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +0000824 if (!Evaluate(Scratch, Info, E))
825 Info.EvalStatus.HasSideEffects = true;
826 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000827};
828
829}
830
831//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000832// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +0000833//
834// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
835// function designators (in C), decl references to void objects (in C), and
836// temporaries (if building with -Wno-address-of-temporary).
837//
838// LValue evaluation produces values comprising a base expression of one of the
839// following types:
840// * DeclRefExpr
841// * MemberExpr for a static member
842// * CompoundLiteralExpr in C
843// * StringLiteral
844// * PredefinedExpr
845// * ObjCEncodeExpr
846// * AddrLabelExpr
847// * BlockExpr
848// * CallExpr for a MakeStringConstant builtin
849// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +0000850//===----------------------------------------------------------------------===//
851namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000852class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000853 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000854 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000855 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000856
Peter Collingbournee9200682011-05-13 03:29:01 +0000857 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000858 Result.Base = E;
859 Result.Offset = CharUnits::Zero();
Richard Smith0b0a0b62011-10-29 20:57:55 +0000860 Result.CallIndex = Info.getCurrentCallIndex();
John McCall45d55e42010-05-07 21:00:08 +0000861 return true;
862 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000863public:
Mike Stump11289f42009-09-09 15:08:12 +0000864
John McCall45d55e42010-05-07 21:00:08 +0000865 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000866 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000867
Richard Smith0b0a0b62011-10-29 20:57:55 +0000868 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000869 Result.setFrom(V);
870 return true;
871 }
872 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000873 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000874 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000875
Richard Smith11562c52011-10-28 17:51:58 +0000876 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
877
Peter Collingbournee9200682011-05-13 03:29:01 +0000878 bool VisitDeclRefExpr(const DeclRefExpr *E);
879 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
880 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
881 bool VisitMemberExpr(const MemberExpr *E);
882 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
883 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
884 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
885 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000886
Peter Collingbournee9200682011-05-13 03:29:01 +0000887 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000888 switch (E->getCastKind()) {
889 default:
Richard Smith11562c52011-10-28 17:51:58 +0000890 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000891
Eli Friedmance3e02a2011-10-11 00:13:24 +0000892 case CK_LValueBitCast:
Anders Carlssonde55f642009-10-03 16:30:22 +0000893 return Visit(E->getSubExpr());
Eli Friedmance3e02a2011-10-11 00:13:24 +0000894
Richard Smith11562c52011-10-28 17:51:58 +0000895 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
896 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlssonde55f642009-10-03 16:30:22 +0000897 }
898 }
Sebastian Redl12757ab2011-09-24 17:48:14 +0000899
Eli Friedman449fe542009-03-23 04:56:01 +0000900 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000901
Eli Friedman9a156e52008-11-12 09:44:48 +0000902};
903} // end anonymous namespace
904
Richard Smith11562c52011-10-28 17:51:58 +0000905/// Evaluate an expression as an lvalue. This can be legitimately called on
906/// expressions which are not glvalues, in a few cases:
907/// * function designators in C,
908/// * "extern void" objects,
909/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +0000910static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +0000911 assert((E->isGLValue() || E->getType()->isFunctionType() ||
912 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
913 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +0000914 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000915}
916
Peter Collingbournee9200682011-05-13 03:29:01 +0000917bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000918 if (isa<FunctionDecl>(E->getDecl()))
John McCall45d55e42010-05-07 21:00:08 +0000919 return Success(E);
Richard Smith11562c52011-10-28 17:51:58 +0000920 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
921 return VisitVarDecl(E, VD);
922 return Error(E);
923}
Richard Smith733237d2011-10-24 23:14:33 +0000924
Richard Smith11562c52011-10-28 17:51:58 +0000925bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
926 if (!VD->getType()->isReferenceType())
927 return Success(E);
Eli Friedman751aa72b72009-05-27 06:04:58 +0000928
Richard Smith0b0a0b62011-10-29 20:57:55 +0000929 CCValue V;
930 if (EvaluateVarDeclInit(Info, VD, Info.getCurrentCallIndex(), V))
931 return Success(V, E);
Richard Smith11562c52011-10-28 17:51:58 +0000932
933 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000934}
935
Peter Collingbournee9200682011-05-13 03:29:01 +0000936bool
937LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000938 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
939 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
940 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +0000941 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000942}
943
Peter Collingbournee9200682011-05-13 03:29:01 +0000944bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000945 // Handle static data members.
946 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
947 VisitIgnoredValue(E->getBase());
948 return VisitVarDecl(E, VD);
949 }
950
Richard Smith254a73d2011-10-28 22:34:42 +0000951 // Handle static member functions.
952 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
953 if (MD->isStatic()) {
954 VisitIgnoredValue(E->getBase());
955 return Success(E);
956 }
957 }
958
Eli Friedman9a156e52008-11-12 09:44:48 +0000959 QualType Ty;
960 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000961 if (!EvaluatePointer(E->getBase(), Result, Info))
962 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000963 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000964 } else {
John McCall45d55e42010-05-07 21:00:08 +0000965 if (!Visit(E->getBase()))
966 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000967 Ty = E->getBase()->getType();
968 }
969
Peter Collingbournee9200682011-05-13 03:29:01 +0000970 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000971 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000972
Peter Collingbournee9200682011-05-13 03:29:01 +0000973 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000974 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +0000975 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000976
977 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000978 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000979
Eli Friedmana3c122d2011-07-07 01:54:01 +0000980 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +0000981 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +0000982 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000983}
984
Peter Collingbournee9200682011-05-13 03:29:01 +0000985bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000986 // FIXME: Deal with vectors as array subscript bases.
987 if (E->getBase()->getType()->isVectorType())
988 return false;
989
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000990 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +0000991 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000992
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000993 APSInt Index;
994 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +0000995 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000996
Ken Dyck40775002010-01-11 17:06:35 +0000997 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +0000998 Result.Offset += Index.getSExtValue() * ElementSize;
999 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001000}
Eli Friedman9a156e52008-11-12 09:44:48 +00001001
Peter Collingbournee9200682011-05-13 03:29:01 +00001002bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00001003 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00001004}
1005
Eli Friedman9a156e52008-11-12 09:44:48 +00001006//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001007// Pointer Evaluation
1008//===----------------------------------------------------------------------===//
1009
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001010namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001011class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001012 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001013 LValue &Result;
1014
Peter Collingbournee9200682011-05-13 03:29:01 +00001015 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00001016 Result.Base = E;
1017 Result.Offset = CharUnits::Zero();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001018 Result.CallIndex = Info.getCurrentCallIndex();
John McCall45d55e42010-05-07 21:00:08 +00001019 return true;
1020 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001021public:
Mike Stump11289f42009-09-09 15:08:12 +00001022
John McCall45d55e42010-05-07 21:00:08 +00001023 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001024 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001025
Richard Smith0b0a0b62011-10-29 20:57:55 +00001026 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001027 Result.setFrom(V);
1028 return true;
1029 }
1030 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +00001031 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001032 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001033 bool ValueInitialization(const Expr *E) {
1034 return Success((Expr*)0);
1035 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001036
John McCall45d55e42010-05-07 21:00:08 +00001037 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001038 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00001039 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001040 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00001041 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001042 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00001043 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001044 bool VisitCallExpr(const CallExpr *E);
1045 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00001046 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00001047 return Success(E);
1048 return false;
Mike Stumpa6703322009-02-19 22:01:56 +00001049 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001050 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +00001051 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +00001052
Eli Friedman449fe542009-03-23 04:56:01 +00001053 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001054};
Chris Lattner05706e882008-07-11 18:11:29 +00001055} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001056
John McCall45d55e42010-05-07 21:00:08 +00001057static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001058 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00001059 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00001060}
1061
John McCall45d55e42010-05-07 21:00:08 +00001062bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001063 if (E->getOpcode() != BO_Add &&
1064 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +00001065 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001066
Chris Lattner05706e882008-07-11 18:11:29 +00001067 const Expr *PExp = E->getLHS();
1068 const Expr *IExp = E->getRHS();
1069 if (IExp->getType()->isPointerType())
1070 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00001071
John McCall45d55e42010-05-07 21:00:08 +00001072 if (!EvaluatePointer(PExp, Result, Info))
1073 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001074
John McCall45d55e42010-05-07 21:00:08 +00001075 llvm::APSInt Offset;
1076 if (!EvaluateInteger(IExp, Offset, Info))
1077 return false;
1078 int64_t AdditionalOffset
1079 = Offset.isSigned() ? Offset.getSExtValue()
1080 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +00001081
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001082 // Compute the new offset in the appropriate width.
1083
1084 QualType PointeeType =
1085 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +00001086 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +00001087
Anders Carlssonef56fba2009-02-19 04:55:58 +00001088 // Explicitly handle GNU void* and function pointer arithmetic extensions.
1089 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +00001090 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +00001091 else
John McCall45d55e42010-05-07 21:00:08 +00001092 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +00001093
John McCalle3027922010-08-25 11:45:40 +00001094 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +00001095 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +00001096 else
John McCall45d55e42010-05-07 21:00:08 +00001097 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +00001098
John McCall45d55e42010-05-07 21:00:08 +00001099 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001100}
Eli Friedman9a156e52008-11-12 09:44:48 +00001101
John McCall45d55e42010-05-07 21:00:08 +00001102bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1103 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001104}
Mike Stump11289f42009-09-09 15:08:12 +00001105
Chris Lattner05706e882008-07-11 18:11:29 +00001106
Peter Collingbournee9200682011-05-13 03:29:01 +00001107bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1108 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00001109
Eli Friedman847a2bc2009-12-27 05:43:15 +00001110 switch (E->getCastKind()) {
1111 default:
1112 break;
1113
John McCalle3027922010-08-25 11:45:40 +00001114 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00001115 case CK_CPointerToObjCPointerCast:
1116 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001117 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +00001118 return Visit(SubExpr);
1119
Anders Carlsson18275092010-10-31 20:41:46 +00001120 case CK_DerivedToBase:
1121 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001122 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00001123 return false;
1124
1125 // Now figure out the necessary offset to add to the baseLV to get from
1126 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +00001127 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +00001128
1129 QualType Ty = E->getSubExpr()->getType();
1130 const CXXRecordDecl *DerivedDecl =
1131 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
1132
1133 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1134 PathE = E->path_end(); PathI != PathE; ++PathI) {
1135 const CXXBaseSpecifier *Base = *PathI;
1136
1137 // FIXME: If the base is virtual, we'd need to determine the type of the
1138 // most derived class and we don't support that right now.
1139 if (Base->isVirtual())
1140 return false;
1141
1142 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1143 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1144
Richard Smith0b0a0b62011-10-29 20:57:55 +00001145 Result.getLValueOffset() += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +00001146 DerivedDecl = BaseDecl;
1147 }
1148
Anders Carlsson18275092010-10-31 20:41:46 +00001149 return true;
1150 }
1151
Richard Smith0b0a0b62011-10-29 20:57:55 +00001152 case CK_NullToPointer:
1153 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00001154
John McCalle3027922010-08-25 11:45:40 +00001155 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001156 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00001157 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00001158 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00001159
John McCall45d55e42010-05-07 21:00:08 +00001160 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001161 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1162 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
John McCall45d55e42010-05-07 21:00:08 +00001163 Result.Base = 0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001164 Result.Offset = CharUnits::fromQuantity(N);
1165 Result.CallIndex = CCValue::NoCallIndex;
John McCall45d55e42010-05-07 21:00:08 +00001166 return true;
1167 } else {
1168 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001169 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00001170 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001171 }
1172 }
John McCalle3027922010-08-25 11:45:40 +00001173 case CK_ArrayToPointerDecay:
1174 case CK_FunctionToPointerDecay:
John McCall45d55e42010-05-07 21:00:08 +00001175 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001176 }
1177
Richard Smith11562c52011-10-28 17:51:58 +00001178 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00001179}
Chris Lattner05706e882008-07-11 18:11:29 +00001180
Peter Collingbournee9200682011-05-13 03:29:01 +00001181bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +00001182 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +00001183 Builtin::BI__builtin___CFStringMakeConstantString ||
1184 E->isBuiltinCall(Info.Ctx) ==
1185 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +00001186 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00001187
Peter Collingbournee9200682011-05-13 03:29:01 +00001188 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001189}
Chris Lattner05706e882008-07-11 18:11:29 +00001190
1191//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001192// Vector Evaluation
1193//===----------------------------------------------------------------------===//
1194
1195namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001196 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00001197 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1198 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001199 public:
Mike Stump11289f42009-09-09 15:08:12 +00001200
Richard Smith2d406342011-10-22 21:10:00 +00001201 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1202 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001203
Richard Smith2d406342011-10-22 21:10:00 +00001204 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1205 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1206 // FIXME: remove this APValue copy.
1207 Result = APValue(V.data(), V.size());
1208 return true;
1209 }
1210 bool Success(const APValue &V, const Expr *E) {
1211 Result = V;
1212 return true;
1213 }
1214 bool Error(const Expr *E) { return false; }
1215 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00001216
Richard Smith2d406342011-10-22 21:10:00 +00001217 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00001218 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00001219 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00001220 bool VisitInitListExpr(const InitListExpr *E);
1221 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001222 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001223 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00001224 // shufflevector, ExtVectorElementExpr
1225 // (Note that these require implementing conversions
1226 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001227 };
1228} // end anonymous namespace
1229
1230static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001231 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00001232 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001233}
1234
Richard Smith2d406342011-10-22 21:10:00 +00001235bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1236 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001237 QualType EltTy = VTy->getElementType();
1238 unsigned NElts = VTy->getNumElements();
1239 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +00001240
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001241 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00001242 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001243
Eli Friedmanc757de22011-03-25 00:43:55 +00001244 switch (E->getCastKind()) {
1245 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00001246 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00001247 if (SETy->isIntegerType()) {
1248 APSInt IntResult;
1249 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001250 return Error(E);
1251 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00001252 } else if (SETy->isRealFloatingType()) {
1253 APFloat F(0.0);
1254 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001255 return Error(E);
1256 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00001257 } else {
Richard Smith2d406342011-10-22 21:10:00 +00001258 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001259 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001260
1261 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00001262 SmallVector<APValue, 4> Elts(NElts, Val);
1263 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00001264 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001265 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +00001266 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +00001267 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +00001268 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001269
Eli Friedmanc757de22011-03-25 00:43:55 +00001270 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +00001271 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +00001272
Eli Friedmanc757de22011-03-25 00:43:55 +00001273 APSInt Init;
1274 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001275 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001276
Eli Friedmanc757de22011-03-25 00:43:55 +00001277 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1278 "Vectors must be composed of ints or floats");
1279
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001280 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +00001281 for (unsigned i = 0; i != NElts; ++i) {
1282 APSInt Tmp = Init.extOrTrunc(EltWidth);
1283
1284 if (EltTy->isIntegerType())
1285 Elts.push_back(APValue(Tmp));
1286 else
1287 Elts.push_back(APValue(APFloat(Tmp)));
1288
1289 Init >>= EltWidth;
1290 }
Richard Smith2d406342011-10-22 21:10:00 +00001291 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001292 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001293 default:
Richard Smith11562c52011-10-28 17:51:58 +00001294 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001295 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001296}
1297
Richard Smith2d406342011-10-22 21:10:00 +00001298bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001299VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00001300 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001301 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00001302 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00001303
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001304 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001305 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001306
John McCall875679e2010-06-11 17:54:15 +00001307 // If a vector is initialized with a single element, that value
1308 // becomes every element of the vector, not just the first.
1309 // This is the behavior described in the IBM AltiVec documentation.
1310 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00001311
1312 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00001313 // vector (OpenCL 6.1.6).
1314 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00001315 return Visit(E->getInit(0));
1316
John McCall875679e2010-06-11 17:54:15 +00001317 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001318 if (EltTy->isIntegerType()) {
1319 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00001320 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001321 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001322 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001323 } else {
1324 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00001325 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001326 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001327 InitValue = APValue(f);
1328 }
1329 for (unsigned i = 0; i < NumElements; i++) {
1330 Elements.push_back(InitValue);
1331 }
1332 } else {
1333 for (unsigned i = 0; i < NumElements; i++) {
1334 if (EltTy->isIntegerType()) {
1335 llvm::APSInt sInt(32);
1336 if (i < NumInits) {
1337 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001338 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001339 } else {
1340 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1341 }
1342 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00001343 } else {
John McCall875679e2010-06-11 17:54:15 +00001344 llvm::APFloat f(0.0);
1345 if (i < NumInits) {
1346 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001347 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001348 } else {
1349 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1350 }
1351 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00001352 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001353 }
1354 }
Richard Smith2d406342011-10-22 21:10:00 +00001355 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001356}
1357
Richard Smith2d406342011-10-22 21:10:00 +00001358bool
1359VectorExprEvaluator::ValueInitialization(const Expr *E) {
1360 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00001361 QualType EltTy = VT->getElementType();
1362 APValue ZeroElement;
1363 if (EltTy->isIntegerType())
1364 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1365 else
1366 ZeroElement =
1367 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1368
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001369 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00001370 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001371}
1372
Richard Smith2d406342011-10-22 21:10:00 +00001373bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00001374 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00001375 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001376}
1377
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001378//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001379// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001380//
1381// As a GNU extension, we support casting pointers to sufficiently-wide integer
1382// types and back in constant folding. Integer values are thus represented
1383// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00001384//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001385
1386namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001387class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001388 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001389 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001390public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001391 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001392 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001393
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001394 bool Success(const llvm::APSInt &SI, const Expr *E) {
1395 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001396 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001397 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001398 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001399 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001400 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001401 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001402 return true;
1403 }
1404
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001405 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001406 assert(E->getType()->isIntegralOrEnumerationType() &&
1407 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001408 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001409 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001410 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001411 Result.getInt().setIsUnsigned(
1412 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001413 return true;
1414 }
1415
1416 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001417 assert(E->getType()->isIntegralOrEnumerationType() &&
1418 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001419 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001420 return true;
1421 }
1422
Ken Dyckdbc01912011-03-11 02:13:43 +00001423 bool Success(CharUnits Size, const Expr *E) {
1424 return Success(Size.getQuantity(), E);
1425 }
1426
1427
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001428 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001429 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001430 if (Info.EvalStatus.Diag == 0) {
1431 Info.EvalStatus.DiagLoc = L;
1432 Info.EvalStatus.Diag = D;
1433 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001434 }
Chris Lattner99415702008-07-12 00:14:42 +00001435 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001436 }
Mike Stump11289f42009-09-09 15:08:12 +00001437
Richard Smith0b0a0b62011-10-29 20:57:55 +00001438 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001439 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001440 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001441 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001442 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001443 }
Mike Stump11289f42009-09-09 15:08:12 +00001444
Richard Smith4ce706a2011-10-11 21:43:33 +00001445 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1446
Peter Collingbournee9200682011-05-13 03:29:01 +00001447 //===--------------------------------------------------------------------===//
1448 // Visitor Methods
1449 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001450
Chris Lattner7174bf32008-07-12 00:38:25 +00001451 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001452 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001453 }
1454 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001455 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001456 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001457
1458 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1459 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001460 if (CheckReferencedDecl(E, E->getDecl()))
1461 return true;
1462
1463 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001464 }
1465 bool VisitMemberExpr(const MemberExpr *E) {
1466 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00001467 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001468 return true;
1469 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001470
1471 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001472 }
1473
Peter Collingbournee9200682011-05-13 03:29:01 +00001474 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001475 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001476 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001477 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001478
Peter Collingbournee9200682011-05-13 03:29:01 +00001479 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001480 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001481
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001482 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001483 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001484 }
Mike Stump11289f42009-09-09 15:08:12 +00001485
Richard Smith4ce706a2011-10-11 21:43:33 +00001486 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001487 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001488 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001489 }
1490
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001491 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001492 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001493 }
1494
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001495 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1496 return Success(E->getValue(), E);
1497 }
1498
John Wiegley6242b6a2011-04-28 00:16:57 +00001499 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1500 return Success(E->getValue(), E);
1501 }
1502
John Wiegleyf9f65842011-04-25 06:54:41 +00001503 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1504 return Success(E->getValue(), E);
1505 }
1506
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001507 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001508 bool VisitUnaryImag(const UnaryOperator *E);
1509
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001510 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001511 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001512
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001513private:
Ken Dyck160146e2010-01-27 17:10:57 +00001514 CharUnits GetAlignOfExpr(const Expr *E);
1515 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001516 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001517 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001518 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001519};
Chris Lattner05706e882008-07-11 18:11:29 +00001520} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001521
Richard Smith11562c52011-10-28 17:51:58 +00001522/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1523/// produce either the integer value or a pointer.
1524///
1525/// GCC has a heinous extension which folds casts between pointer types and
1526/// pointer-sized integral types. We support this by allowing the evaluation of
1527/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1528/// Some simple arithmetic on such values is supported (they are treated much
1529/// like char*).
Richard Smith0b0a0b62011-10-29 20:57:55 +00001530static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
1531 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001532 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001533 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001534}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001535
Daniel Dunbarce399542009-02-20 18:22:23 +00001536static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001537 CCValue Val;
Daniel Dunbarce399542009-02-20 18:22:23 +00001538 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1539 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001540 Result = Val.getInt();
1541 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001542}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001543
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001544bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001545 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001546 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001547 // Check for signedness/width mismatches between E type and ECD value.
1548 bool SameSign = (ECD->getInitVal().isSigned()
1549 == E->getType()->isSignedIntegerOrEnumerationType());
1550 bool SameWidth = (ECD->getInitVal().getBitWidth()
1551 == Info.Ctx.getIntWidth(E->getType()));
1552 if (SameSign && SameWidth)
1553 return Success(ECD->getInitVal(), E);
1554 else {
1555 // Get rid of mismatch (otherwise Success assertions will fail)
1556 // by computing a new value matching the type of E.
1557 llvm::APSInt Val = ECD->getInitVal();
1558 if (!SameSign)
1559 Val.setIsSigned(!ECD->getInitVal().isSigned());
1560 if (!SameWidth)
1561 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1562 return Success(Val, E);
1563 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001564 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001565 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001566}
1567
Chris Lattner86ee2862008-10-06 06:40:35 +00001568/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1569/// as GCC.
1570static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1571 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001572 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001573 enum gcc_type_class {
1574 no_type_class = -1,
1575 void_type_class, integer_type_class, char_type_class,
1576 enumeral_type_class, boolean_type_class,
1577 pointer_type_class, reference_type_class, offset_type_class,
1578 real_type_class, complex_type_class,
1579 function_type_class, method_type_class,
1580 record_type_class, union_type_class,
1581 array_type_class, string_type_class,
1582 lang_type_class
1583 };
Mike Stump11289f42009-09-09 15:08:12 +00001584
1585 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001586 // ideal, however it is what gcc does.
1587 if (E->getNumArgs() == 0)
1588 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001589
Chris Lattner86ee2862008-10-06 06:40:35 +00001590 QualType ArgTy = E->getArg(0)->getType();
1591 if (ArgTy->isVoidType())
1592 return void_type_class;
1593 else if (ArgTy->isEnumeralType())
1594 return enumeral_type_class;
1595 else if (ArgTy->isBooleanType())
1596 return boolean_type_class;
1597 else if (ArgTy->isCharType())
1598 return string_type_class; // gcc doesn't appear to use char_type_class
1599 else if (ArgTy->isIntegerType())
1600 return integer_type_class;
1601 else if (ArgTy->isPointerType())
1602 return pointer_type_class;
1603 else if (ArgTy->isReferenceType())
1604 return reference_type_class;
1605 else if (ArgTy->isRealType())
1606 return real_type_class;
1607 else if (ArgTy->isComplexType())
1608 return complex_type_class;
1609 else if (ArgTy->isFunctionType())
1610 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001611 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001612 return record_type_class;
1613 else if (ArgTy->isUnionType())
1614 return union_type_class;
1615 else if (ArgTy->isArrayType())
1616 return array_type_class;
1617 else if (ArgTy->isUnionType())
1618 return union_type_class;
1619 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001620 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001621 return -1;
1622}
1623
John McCall95007602010-05-10 23:27:23 +00001624/// Retrieves the "underlying object type" of the given expression,
1625/// as used by __builtin_object_size.
1626QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1627 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1628 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1629 return VD->getType();
1630 } else if (isa<CompoundLiteralExpr>(E)) {
1631 return E->getType();
1632 }
1633
1634 return QualType();
1635}
1636
Peter Collingbournee9200682011-05-13 03:29:01 +00001637bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001638 // TODO: Perhaps we should let LLVM lower this?
1639 LValue Base;
1640 if (!EvaluatePointer(E->getArg(0), Base, Info))
1641 return false;
1642
1643 // If we can prove the base is null, lower to zero now.
1644 const Expr *LVBase = Base.getLValueBase();
1645 if (!LVBase) return Success(0, E);
1646
1647 QualType T = GetObjectType(LVBase);
1648 if (T.isNull() ||
1649 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001650 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001651 T->isVariablyModifiedType() ||
1652 T->isDependentType())
1653 return false;
1654
1655 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1656 CharUnits Offset = Base.getLValueOffset();
1657
1658 if (!Offset.isNegative() && Offset <= Size)
1659 Size -= Offset;
1660 else
1661 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001662 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001663}
1664
Peter Collingbournee9200682011-05-13 03:29:01 +00001665bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001666 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001667 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001668 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001669
1670 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001671 if (TryEvaluateBuiltinObjectSize(E))
1672 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001673
Eric Christopher99469702010-01-19 22:58:35 +00001674 // If evaluating the argument has side-effects we can't determine
1675 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001676 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001677 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001678 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001679 return Success(0, E);
1680 }
Mike Stump876387b2009-10-27 22:09:17 +00001681
Mike Stump722cedf2009-10-26 18:35:08 +00001682 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1683 }
1684
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001685 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001686 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001687
Anders Carlsson4c76e932008-11-24 04:21:33 +00001688 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001689 // __builtin_constant_p always has one operand: it returns true if that
1690 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001691 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001692
1693 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001694 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001695 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001696 return Success(Operand, E);
1697 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001698
1699 case Builtin::BI__builtin_expect:
1700 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001701
1702 case Builtin::BIstrlen:
1703 case Builtin::BI__builtin_strlen:
1704 // As an extension, we support strlen() and __builtin_strlen() as constant
1705 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001706 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001707 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1708 // The string literal may have embedded null characters. Find the first
1709 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001710 StringRef Str = S->getString();
1711 StringRef::size_type Pos = Str.find(0);
1712 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001713 Str = Str.substr(0, Pos);
1714
1715 return Success(Str.size(), E);
1716 }
1717
1718 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001719
1720 case Builtin::BI__atomic_is_lock_free: {
1721 APSInt SizeVal;
1722 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1723 return false;
1724
1725 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1726 // of two less than the maximum inline atomic width, we know it is
1727 // lock-free. If the size isn't a power of two, or greater than the
1728 // maximum alignment where we promote atomics, we know it is not lock-free
1729 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1730 // the answer can only be determined at runtime; for example, 16-byte
1731 // atomics have lock-free implementations on some, but not all,
1732 // x86-64 processors.
1733
1734 // Check power-of-two.
1735 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1736 if (!Size.isPowerOfTwo())
1737#if 0
1738 // FIXME: Suppress this folding until the ABI for the promotion width
1739 // settles.
1740 return Success(0, E);
1741#else
1742 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1743#endif
1744
1745#if 0
1746 // Check against promotion width.
1747 // FIXME: Suppress this folding until the ABI for the promotion width
1748 // settles.
1749 unsigned PromoteWidthBits =
1750 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1751 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1752 return Success(0, E);
1753#endif
1754
1755 // Check against inlining width.
1756 unsigned InlineWidthBits =
1757 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1758 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1759 return Success(1, E);
1760
1761 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1762 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001763 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001764}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001765
Chris Lattnere13042c2008-07-11 19:10:17 +00001766bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001767 if (E->isAssignmentOp())
1768 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1769
John McCalle3027922010-08-25 11:45:40 +00001770 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00001771 VisitIgnoredValue(E->getLHS());
1772 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00001773 }
1774
1775 if (E->isLogicalOp()) {
1776 // These need to be handled specially because the operands aren't
1777 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001778 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001779
Richard Smith11562c52011-10-28 17:51:58 +00001780 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001781 // We were able to evaluate the LHS, see if we can get away with not
1782 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001783 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001784 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001785
Richard Smith11562c52011-10-28 17:51:58 +00001786 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001787 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001788 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001789 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001790 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001791 }
1792 } else {
Richard Smith11562c52011-10-28 17:51:58 +00001793 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001794 // We can't evaluate the LHS; however, sometimes the result
1795 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001796 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1797 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001798 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001799 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00001800 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001801
1802 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001803 }
1804 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001805 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001806
Eli Friedman5a332ea2008-11-13 06:09:17 +00001807 return false;
1808 }
1809
Anders Carlssonacc79812008-11-16 07:17:21 +00001810 QualType LHSTy = E->getLHS()->getType();
1811 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001812
1813 if (LHSTy->isAnyComplexType()) {
1814 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001815 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001816
1817 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1818 return false;
1819
1820 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1821 return false;
1822
1823 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001824 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001825 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001826 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001827 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1828
John McCalle3027922010-08-25 11:45:40 +00001829 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001830 return Success((CR_r == APFloat::cmpEqual &&
1831 CR_i == APFloat::cmpEqual), E);
1832 else {
John McCalle3027922010-08-25 11:45:40 +00001833 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001834 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001835 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001836 CR_r == APFloat::cmpLessThan ||
1837 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001838 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001839 CR_i == APFloat::cmpLessThan ||
1840 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001841 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001842 } else {
John McCalle3027922010-08-25 11:45:40 +00001843 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001844 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1845 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1846 else {
John McCalle3027922010-08-25 11:45:40 +00001847 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001848 "Invalid compex comparison.");
1849 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1850 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1851 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001852 }
1853 }
Mike Stump11289f42009-09-09 15:08:12 +00001854
Anders Carlssonacc79812008-11-16 07:17:21 +00001855 if (LHSTy->isRealFloatingType() &&
1856 RHSTy->isRealFloatingType()) {
1857 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001858
Anders Carlssonacc79812008-11-16 07:17:21 +00001859 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1860 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001861
Anders Carlssonacc79812008-11-16 07:17:21 +00001862 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1863 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001864
Anders Carlssonacc79812008-11-16 07:17:21 +00001865 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001866
Anders Carlssonacc79812008-11-16 07:17:21 +00001867 switch (E->getOpcode()) {
1868 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001869 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001870 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001871 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001872 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001873 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001874 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001875 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001876 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001877 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001878 E);
John McCalle3027922010-08-25 11:45:40 +00001879 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001880 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001881 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001882 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001883 || CR == APFloat::cmpLessThan
1884 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001885 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001886 }
Mike Stump11289f42009-09-09 15:08:12 +00001887
Eli Friedmana38da572009-04-28 19:17:36 +00001888 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001889 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001890 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001891 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1892 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001893
John McCall45d55e42010-05-07 21:00:08 +00001894 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001895 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1896 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001897
Eli Friedman334046a2009-06-14 02:17:33 +00001898 // Reject any bases from the normal codepath; we special-case comparisons
1899 // to null.
1900 if (LHSValue.getLValueBase()) {
1901 if (!E->isEqualityOp())
1902 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001903 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001904 return false;
1905 bool bres;
1906 if (!EvalPointerValueAsBool(LHSValue, bres))
1907 return false;
John McCalle3027922010-08-25 11:45:40 +00001908 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001909 } else if (RHSValue.getLValueBase()) {
1910 if (!E->isEqualityOp())
1911 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001912 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001913 return false;
1914 bool bres;
1915 if (!EvalPointerValueAsBool(RHSValue, bres))
1916 return false;
John McCalle3027922010-08-25 11:45:40 +00001917 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001918 }
Eli Friedman64004332009-03-23 04:38:34 +00001919
John McCalle3027922010-08-25 11:45:40 +00001920 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001921 QualType Type = E->getLHS()->getType();
1922 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001923
Ken Dyck02990832010-01-15 12:37:54 +00001924 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001925 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001926 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001927
Ken Dyck02990832010-01-15 12:37:54 +00001928 CharUnits Diff = LHSValue.getLValueOffset() -
1929 RHSValue.getLValueOffset();
1930 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001931 }
1932 bool Result;
John McCalle3027922010-08-25 11:45:40 +00001933 if (E->getOpcode() == BO_EQ) {
Eli Friedmana38da572009-04-28 19:17:36 +00001934 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman8b171f62009-04-29 20:29:43 +00001935 } else {
Eli Friedmana38da572009-04-28 19:17:36 +00001936 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1937 }
1938 return Success(Result, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001939 }
1940 }
Douglas Gregorb90df602010-06-16 00:17:44 +00001941 if (!LHSTy->isIntegralOrEnumerationType() ||
1942 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001943 // We can't continue from here for non-integral types, and they
1944 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001945 return false;
1946 }
1947
Anders Carlsson9c181652008-07-08 14:35:21 +00001948 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001949 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00001950 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00001951 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001952
Richard Smith11562c52011-10-28 17:51:58 +00001953 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001954 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001955 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00001956
1957 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00001958 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001959 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1960 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00001961 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00001962 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001963 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00001964 LHSVal.getLValueOffset() -= AdditionalOffset;
1965 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00001966 return true;
1967 }
1968
1969 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00001970 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00001971 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001972 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
1973 LHSVal.getInt().getZExtValue());
1974 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00001975 return true;
1976 }
1977
1978 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00001979 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00001980 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001981
Richard Smith11562c52011-10-28 17:51:58 +00001982 APSInt &LHS = LHSVal.getInt();
1983 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00001984
Anders Carlsson9c181652008-07-08 14:35:21 +00001985 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001986 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001987 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00001988 case BO_Mul: return Success(LHS * RHS, E);
1989 case BO_Add: return Success(LHS + RHS, E);
1990 case BO_Sub: return Success(LHS - RHS, E);
1991 case BO_And: return Success(LHS & RHS, E);
1992 case BO_Xor: return Success(LHS ^ RHS, E);
1993 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001994 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00001995 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001996 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00001997 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001998 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00001999 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002000 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002001 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002002 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00002003 // During constant-folding, a negative shift is an opposite shift.
2004 if (RHS.isSigned() && RHS.isNegative()) {
2005 RHS = -RHS;
2006 goto shift_right;
2007 }
2008
2009 shift_left:
2010 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00002011 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2012 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002013 }
John McCalle3027922010-08-25 11:45:40 +00002014 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00002015 // During constant-folding, a negative shift is an opposite shift.
2016 if (RHS.isSigned() && RHS.isNegative()) {
2017 RHS = -RHS;
2018 goto shift_left;
2019 }
2020
2021 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00002022 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00002023 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2024 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002025 }
Mike Stump11289f42009-09-09 15:08:12 +00002026
Richard Smith11562c52011-10-28 17:51:58 +00002027 case BO_LT: return Success(LHS < RHS, E);
2028 case BO_GT: return Success(LHS > RHS, E);
2029 case BO_LE: return Success(LHS <= RHS, E);
2030 case BO_GE: return Success(LHS >= RHS, E);
2031 case BO_EQ: return Success(LHS == RHS, E);
2032 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00002033 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002034}
2035
Ken Dyck160146e2010-01-27 17:10:57 +00002036CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002037 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2038 // the result is the size of the referenced type."
2039 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2040 // result shall be the alignment of the referenced type."
2041 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2042 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00002043
2044 // __alignof is defined to return the preferred alignment.
2045 return Info.Ctx.toCharUnitsFromBits(
2046 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00002047}
2048
Ken Dyck160146e2010-01-27 17:10:57 +00002049CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00002050 E = E->IgnoreParens();
2051
2052 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00002053 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00002054 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002055 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2056 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00002057
Chris Lattner68061312009-01-24 21:53:27 +00002058 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002059 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2060 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00002061
Chris Lattner24aeeab2009-01-24 21:09:06 +00002062 return GetAlignOfType(E->getType());
2063}
2064
2065
Peter Collingbournee190dee2011-03-11 19:24:49 +00002066/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2067/// a result as the expression's type.
2068bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2069 const UnaryExprOrTypeTraitExpr *E) {
2070 switch(E->getKind()) {
2071 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00002072 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00002073 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002074 else
Ken Dyckdbc01912011-03-11 02:13:43 +00002075 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002076 }
Eli Friedman64004332009-03-23 04:38:34 +00002077
Peter Collingbournee190dee2011-03-11 19:24:49 +00002078 case UETT_VecStep: {
2079 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00002080
Peter Collingbournee190dee2011-03-11 19:24:49 +00002081 if (Ty->isVectorType()) {
2082 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00002083
Peter Collingbournee190dee2011-03-11 19:24:49 +00002084 // The vec_step built-in functions that take a 3-component
2085 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2086 if (n == 3)
2087 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002088
Peter Collingbournee190dee2011-03-11 19:24:49 +00002089 return Success(n, E);
2090 } else
2091 return Success(1, E);
2092 }
2093
2094 case UETT_SizeOf: {
2095 QualType SrcTy = E->getTypeOfArgument();
2096 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2097 // the result is the size of the referenced type."
2098 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2099 // result shall be the alignment of the referenced type."
2100 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2101 SrcTy = Ref->getPointeeType();
2102
2103 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2104 // extension.
2105 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
2106 return Success(1, E);
2107
2108 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2109 if (!SrcTy->isConstantSizeType())
2110 return false;
2111
2112 // Get information about the size.
2113 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
2114 }
2115 }
2116
2117 llvm_unreachable("unknown expr/type trait");
2118 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002119}
2120
Peter Collingbournee9200682011-05-13 03:29:01 +00002121bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00002122 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00002123 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00002124 if (n == 0)
2125 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002126 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00002127 for (unsigned i = 0; i != n; ++i) {
2128 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
2129 switch (ON.getKind()) {
2130 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00002131 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00002132 APSInt IdxResult;
2133 if (!EvaluateInteger(Idx, IdxResult, Info))
2134 return false;
2135 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
2136 if (!AT)
2137 return false;
2138 CurrentType = AT->getElementType();
2139 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
2140 Result += IdxResult.getSExtValue() * ElementSize;
2141 break;
2142 }
2143
2144 case OffsetOfExpr::OffsetOfNode::Field: {
2145 FieldDecl *MemberDecl = ON.getField();
2146 const RecordType *RT = CurrentType->getAs<RecordType>();
2147 if (!RT)
2148 return false;
2149 RecordDecl *RD = RT->getDecl();
2150 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00002151 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00002152 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002153 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00002154 CurrentType = MemberDecl->getType().getNonReferenceType();
2155 break;
2156 }
2157
2158 case OffsetOfExpr::OffsetOfNode::Identifier:
2159 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00002160 return false;
2161
2162 case OffsetOfExpr::OffsetOfNode::Base: {
2163 CXXBaseSpecifier *BaseSpec = ON.getBase();
2164 if (BaseSpec->isVirtual())
2165 return false;
2166
2167 // Find the layout of the class whose base we are looking into.
2168 const RecordType *RT = CurrentType->getAs<RecordType>();
2169 if (!RT)
2170 return false;
2171 RecordDecl *RD = RT->getDecl();
2172 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
2173
2174 // Find the base class itself.
2175 CurrentType = BaseSpec->getType();
2176 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2177 if (!BaseRT)
2178 return false;
2179
2180 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00002181 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00002182 break;
2183 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002184 }
2185 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002186 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00002187}
2188
Chris Lattnere13042c2008-07-11 19:10:17 +00002189bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002190 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002191 // LNot's operand isn't necessarily an integer, so we handle it specially.
2192 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00002193 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00002194 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002195 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00002196 }
2197
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002198 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00002199 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002200 return false;
2201
Richard Smith11562c52011-10-28 17:51:58 +00002202 // Get the operand value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002203 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00002204 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00002205 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002206
Chris Lattnerf09ad162008-07-11 22:15:16 +00002207 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002208 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00002209 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2210 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002211 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00002212 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00002213 // FIXME: Should extension allow i-c-e extension expressions in its scope?
2214 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00002215 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002216 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00002217 // The result is just the value.
2218 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002219 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00002220 if (!Val.isInt()) return false;
2221 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00002222 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00002223 if (!Val.isInt()) return false;
2224 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00002225 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002226}
Mike Stump11289f42009-09-09 15:08:12 +00002227
Chris Lattner477c4be2008-07-12 01:15:53 +00002228/// HandleCast - This is used to evaluate implicit or explicit casts where the
2229/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00002230bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
2231 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002232 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00002233 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002234
Eli Friedmanc757de22011-03-25 00:43:55 +00002235 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00002236 case CK_BaseToDerived:
2237 case CK_DerivedToBase:
2238 case CK_UncheckedDerivedToBase:
2239 case CK_Dynamic:
2240 case CK_ToUnion:
2241 case CK_ArrayToPointerDecay:
2242 case CK_FunctionToPointerDecay:
2243 case CK_NullToPointer:
2244 case CK_NullToMemberPointer:
2245 case CK_BaseToDerivedMemberPointer:
2246 case CK_DerivedToBaseMemberPointer:
2247 case CK_ConstructorConversion:
2248 case CK_IntegralToPointer:
2249 case CK_ToVoid:
2250 case CK_VectorSplat:
2251 case CK_IntegralToFloating:
2252 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002253 case CK_CPointerToObjCPointerCast:
2254 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002255 case CK_AnyPointerToBlockPointerCast:
2256 case CK_ObjCObjectLValueCast:
2257 case CK_FloatingRealToComplex:
2258 case CK_FloatingComplexToReal:
2259 case CK_FloatingComplexCast:
2260 case CK_FloatingComplexToIntegralComplex:
2261 case CK_IntegralRealToComplex:
2262 case CK_IntegralComplexCast:
2263 case CK_IntegralComplexToFloatingComplex:
2264 llvm_unreachable("invalid cast kind for integral value");
2265
Eli Friedman9faf2f92011-03-25 19:07:11 +00002266 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002267 case CK_Dependent:
2268 case CK_GetObjCProperty:
2269 case CK_LValueBitCast:
2270 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00002271 case CK_ARCProduceObject:
2272 case CK_ARCConsumeObject:
2273 case CK_ARCReclaimReturnedObject:
2274 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00002275 return false;
2276
2277 case CK_LValueToRValue:
2278 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002279 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002280
2281 case CK_MemberPointerToBoolean:
2282 case CK_PointerToBoolean:
2283 case CK_IntegralToBoolean:
2284 case CK_FloatingToBoolean:
2285 case CK_FloatingComplexToBoolean:
2286 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002287 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002288 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002289 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002290 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002291 }
2292
Eli Friedmanc757de22011-03-25 00:43:55 +00002293 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00002294 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00002295 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002296
Eli Friedman742421e2009-02-20 01:15:07 +00002297 if (!Result.isInt()) {
2298 // Only allow casts of lvalues if they are lossless.
2299 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2300 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002301
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002302 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002303 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00002304 }
Mike Stump11289f42009-09-09 15:08:12 +00002305
Eli Friedmanc757de22011-03-25 00:43:55 +00002306 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00002307 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00002308 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00002309 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002310
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002311 if (LV.getLValueBase()) {
2312 // Only allow based lvalue casts if they are lossless.
2313 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2314 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002315
John McCall45d55e42010-05-07 21:00:08 +00002316 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002317 return true;
2318 }
2319
Ken Dyck02990832010-01-15 12:37:54 +00002320 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2321 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002322 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002323 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002324
Eli Friedmanc757de22011-03-25 00:43:55 +00002325 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00002326 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002327 if (!EvaluateComplex(SubExpr, C, Info))
2328 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00002329 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002330 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00002331
Eli Friedmanc757de22011-03-25 00:43:55 +00002332 case CK_FloatingToIntegral: {
2333 APFloat F(0.0);
2334 if (!EvaluateFloat(SubExpr, F, Info))
2335 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00002336
Eli Friedmanc757de22011-03-25 00:43:55 +00002337 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2338 }
2339 }
Mike Stump11289f42009-09-09 15:08:12 +00002340
Eli Friedmanc757de22011-03-25 00:43:55 +00002341 llvm_unreachable("unknown cast resulting in integral value");
2342 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002343}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002344
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002345bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2346 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002347 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002348 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2349 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2350 return Success(LV.getComplexIntReal(), E);
2351 }
2352
2353 return Visit(E->getSubExpr());
2354}
2355
Eli Friedman4e7a2412009-02-27 04:45:43 +00002356bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002357 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002358 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002359 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2360 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2361 return Success(LV.getComplexIntImag(), E);
2362 }
2363
Richard Smith4a678122011-10-24 18:44:57 +00002364 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00002365 return Success(0, E);
2366}
2367
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002368bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2369 return Success(E->getPackLength(), E);
2370}
2371
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002372bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2373 return Success(E->getValue(), E);
2374}
2375
Chris Lattner05706e882008-07-11 18:11:29 +00002376//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002377// Float Evaluation
2378//===----------------------------------------------------------------------===//
2379
2380namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002381class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002382 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002383 APFloat &Result;
2384public:
2385 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002386 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002387
Richard Smith0b0a0b62011-10-29 20:57:55 +00002388 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002389 Result = V.getFloat();
2390 return true;
2391 }
2392 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002393 return false;
2394 }
2395
Richard Smith4ce706a2011-10-11 21:43:33 +00002396 bool ValueInitialization(const Expr *E) {
2397 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2398 return true;
2399 }
2400
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002401 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002402
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002403 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002404 bool VisitBinaryOperator(const BinaryOperator *E);
2405 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002406 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002407
John McCallb1fb0d32010-05-07 22:08:54 +00002408 bool VisitUnaryReal(const UnaryOperator *E);
2409 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002410
John McCallb1fb0d32010-05-07 22:08:54 +00002411 // FIXME: Missing: array subscript of vector, member of vector,
2412 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002413};
2414} // end anonymous namespace
2415
2416static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002417 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002418 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002419}
2420
Jay Foad39c79802011-01-12 09:06:06 +00002421static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002422 QualType ResultTy,
2423 const Expr *Arg,
2424 bool SNaN,
2425 llvm::APFloat &Result) {
2426 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2427 if (!S) return false;
2428
2429 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2430
2431 llvm::APInt fill;
2432
2433 // Treat empty strings as if they were zero.
2434 if (S->getString().empty())
2435 fill = llvm::APInt(32, 0);
2436 else if (S->getString().getAsInteger(0, fill))
2437 return false;
2438
2439 if (SNaN)
2440 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2441 else
2442 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2443 return true;
2444}
2445
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002446bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002447 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002448 default:
2449 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2450
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002451 case Builtin::BI__builtin_huge_val:
2452 case Builtin::BI__builtin_huge_valf:
2453 case Builtin::BI__builtin_huge_vall:
2454 case Builtin::BI__builtin_inf:
2455 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002456 case Builtin::BI__builtin_infl: {
2457 const llvm::fltSemantics &Sem =
2458 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002459 Result = llvm::APFloat::getInf(Sem);
2460 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002461 }
Mike Stump11289f42009-09-09 15:08:12 +00002462
John McCall16291492010-02-28 13:00:19 +00002463 case Builtin::BI__builtin_nans:
2464 case Builtin::BI__builtin_nansf:
2465 case Builtin::BI__builtin_nansl:
2466 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2467 true, Result);
2468
Chris Lattner0b7282e2008-10-06 06:31:58 +00002469 case Builtin::BI__builtin_nan:
2470 case Builtin::BI__builtin_nanf:
2471 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002472 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002473 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002474 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2475 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002476
2477 case Builtin::BI__builtin_fabs:
2478 case Builtin::BI__builtin_fabsf:
2479 case Builtin::BI__builtin_fabsl:
2480 if (!EvaluateFloat(E->getArg(0), Result, Info))
2481 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002482
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002483 if (Result.isNegative())
2484 Result.changeSign();
2485 return true;
2486
Mike Stump11289f42009-09-09 15:08:12 +00002487 case Builtin::BI__builtin_copysign:
2488 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002489 case Builtin::BI__builtin_copysignl: {
2490 APFloat RHS(0.);
2491 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2492 !EvaluateFloat(E->getArg(1), RHS, Info))
2493 return false;
2494 Result.copySign(RHS);
2495 return true;
2496 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002497 }
2498}
2499
John McCallb1fb0d32010-05-07 22:08:54 +00002500bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002501 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2502 ComplexValue CV;
2503 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2504 return false;
2505 Result = CV.FloatReal;
2506 return true;
2507 }
2508
2509 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002510}
2511
2512bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002513 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2514 ComplexValue CV;
2515 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2516 return false;
2517 Result = CV.FloatImag;
2518 return true;
2519 }
2520
Richard Smith4a678122011-10-24 18:44:57 +00002521 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00002522 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2523 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002524 return true;
2525}
2526
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002527bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002528 if (E->getOpcode() == UO_Deref)
Nuno Lopes0e33c682008-11-19 17:44:31 +00002529 return false;
2530
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002531 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2532 return false;
2533
2534 switch (E->getOpcode()) {
2535 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002536 case UO_Plus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002537 return true;
John McCalle3027922010-08-25 11:45:40 +00002538 case UO_Minus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002539 Result.changeSign();
2540 return true;
2541 }
2542}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002543
Eli Friedman24c01542008-08-22 00:06:13 +00002544bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002545 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002546 VisitIgnoredValue(E->getLHS());
2547 return Visit(E->getRHS());
Eli Friedman141fbf32009-11-16 04:25:37 +00002548 }
2549
Richard Smith472d4952011-10-28 23:26:52 +00002550 // We can't evaluate pointer-to-member operations or assignments.
2551 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlssona5df61a2010-10-31 01:21:47 +00002552 return false;
2553
Eli Friedman24c01542008-08-22 00:06:13 +00002554 // FIXME: Diagnostics? I really don't understand how the warnings
2555 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002556 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002557 if (!EvaluateFloat(E->getLHS(), Result, Info))
2558 return false;
2559 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2560 return false;
2561
2562 switch (E->getOpcode()) {
2563 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002564 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002565 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2566 return true;
John McCalle3027922010-08-25 11:45:40 +00002567 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002568 Result.add(RHS, APFloat::rmNearestTiesToEven);
2569 return true;
John McCalle3027922010-08-25 11:45:40 +00002570 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002571 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2572 return true;
John McCalle3027922010-08-25 11:45:40 +00002573 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002574 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2575 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002576 }
2577}
2578
2579bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2580 Result = E->getValue();
2581 return true;
2582}
2583
Peter Collingbournee9200682011-05-13 03:29:01 +00002584bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2585 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002586
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002587 switch (E->getCastKind()) {
2588 default:
Richard Smith11562c52011-10-28 17:51:58 +00002589 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002590
2591 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002592 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002593 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002594 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002595 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002596 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002597 return true;
2598 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002599
2600 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002601 if (!Visit(SubExpr))
2602 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002603 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2604 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002605 return true;
2606 }
John McCalld7646252010-11-14 08:17:51 +00002607
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002608 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002609 ComplexValue V;
2610 if (!EvaluateComplex(SubExpr, V, Info))
2611 return false;
2612 Result = V.getComplexFloatReal();
2613 return true;
2614 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002615 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002616
2617 return false;
2618}
2619
Eli Friedman24c01542008-08-22 00:06:13 +00002620//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002621// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002622//===----------------------------------------------------------------------===//
2623
2624namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002625class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002626 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002627 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002628
Anders Carlsson537969c2008-11-16 20:27:53 +00002629public:
John McCall93d91dc2010-05-07 17:22:02 +00002630 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002631 : ExprEvaluatorBaseTy(info), Result(Result) {}
2632
Richard Smith0b0a0b62011-10-29 20:57:55 +00002633 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002634 Result.setFrom(V);
2635 return true;
2636 }
2637 bool Error(const Expr *E) {
2638 return false;
2639 }
Mike Stump11289f42009-09-09 15:08:12 +00002640
Anders Carlsson537969c2008-11-16 20:27:53 +00002641 //===--------------------------------------------------------------------===//
2642 // Visitor Methods
2643 //===--------------------------------------------------------------------===//
2644
Peter Collingbournee9200682011-05-13 03:29:01 +00002645 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002646
Peter Collingbournee9200682011-05-13 03:29:01 +00002647 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002648
John McCall93d91dc2010-05-07 17:22:02 +00002649 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002650 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002651 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002652};
2653} // end anonymous namespace
2654
John McCall93d91dc2010-05-07 17:22:02 +00002655static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2656 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002657 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002658 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002659}
2660
Peter Collingbournee9200682011-05-13 03:29:01 +00002661bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2662 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002663
2664 if (SubExpr->getType()->isRealFloatingType()) {
2665 Result.makeComplexFloat();
2666 APFloat &Imag = Result.FloatImag;
2667 if (!EvaluateFloat(SubExpr, Imag, Info))
2668 return false;
2669
2670 Result.FloatReal = APFloat(Imag.getSemantics());
2671 return true;
2672 } else {
2673 assert(SubExpr->getType()->isIntegerType() &&
2674 "Unexpected imaginary literal.");
2675
2676 Result.makeComplexInt();
2677 APSInt &Imag = Result.IntImag;
2678 if (!EvaluateInteger(SubExpr, Imag, Info))
2679 return false;
2680
2681 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2682 return true;
2683 }
2684}
2685
Peter Collingbournee9200682011-05-13 03:29:01 +00002686bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002687
John McCallfcef3cf2010-12-14 17:51:41 +00002688 switch (E->getCastKind()) {
2689 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002690 case CK_BaseToDerived:
2691 case CK_DerivedToBase:
2692 case CK_UncheckedDerivedToBase:
2693 case CK_Dynamic:
2694 case CK_ToUnion:
2695 case CK_ArrayToPointerDecay:
2696 case CK_FunctionToPointerDecay:
2697 case CK_NullToPointer:
2698 case CK_NullToMemberPointer:
2699 case CK_BaseToDerivedMemberPointer:
2700 case CK_DerivedToBaseMemberPointer:
2701 case CK_MemberPointerToBoolean:
2702 case CK_ConstructorConversion:
2703 case CK_IntegralToPointer:
2704 case CK_PointerToIntegral:
2705 case CK_PointerToBoolean:
2706 case CK_ToVoid:
2707 case CK_VectorSplat:
2708 case CK_IntegralCast:
2709 case CK_IntegralToBoolean:
2710 case CK_IntegralToFloating:
2711 case CK_FloatingToIntegral:
2712 case CK_FloatingToBoolean:
2713 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002714 case CK_CPointerToObjCPointerCast:
2715 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002716 case CK_AnyPointerToBlockPointerCast:
2717 case CK_ObjCObjectLValueCast:
2718 case CK_FloatingComplexToReal:
2719 case CK_FloatingComplexToBoolean:
2720 case CK_IntegralComplexToReal:
2721 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002722 case CK_ARCProduceObject:
2723 case CK_ARCConsumeObject:
2724 case CK_ARCReclaimReturnedObject:
2725 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002726 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002727
John McCallfcef3cf2010-12-14 17:51:41 +00002728 case CK_LValueToRValue:
2729 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002730 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00002731
2732 case CK_Dependent:
2733 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002734 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002735 case CK_UserDefinedConversion:
2736 return false;
2737
2738 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002739 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002740 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002741 return false;
2742
John McCallfcef3cf2010-12-14 17:51:41 +00002743 Result.makeComplexFloat();
2744 Result.FloatImag = APFloat(Real.getSemantics());
2745 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002746 }
2747
John McCallfcef3cf2010-12-14 17:51:41 +00002748 case CK_FloatingComplexCast: {
2749 if (!Visit(E->getSubExpr()))
2750 return false;
2751
2752 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2753 QualType From
2754 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2755
2756 Result.FloatReal
2757 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2758 Result.FloatImag
2759 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2760 return true;
2761 }
2762
2763 case CK_FloatingComplexToIntegralComplex: {
2764 if (!Visit(E->getSubExpr()))
2765 return false;
2766
2767 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2768 QualType From
2769 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2770 Result.makeComplexInt();
2771 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2772 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2773 return true;
2774 }
2775
2776 case CK_IntegralRealToComplex: {
2777 APSInt &Real = Result.IntReal;
2778 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2779 return false;
2780
2781 Result.makeComplexInt();
2782 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2783 return true;
2784 }
2785
2786 case CK_IntegralComplexCast: {
2787 if (!Visit(E->getSubExpr()))
2788 return false;
2789
2790 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2791 QualType From
2792 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2793
2794 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2795 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2796 return true;
2797 }
2798
2799 case CK_IntegralComplexToFloatingComplex: {
2800 if (!Visit(E->getSubExpr()))
2801 return false;
2802
2803 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2804 QualType From
2805 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2806 Result.makeComplexFloat();
2807 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2808 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2809 return true;
2810 }
2811 }
2812
2813 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002814 return false;
2815}
2816
John McCall93d91dc2010-05-07 17:22:02 +00002817bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002818 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002819 VisitIgnoredValue(E->getLHS());
2820 return Visit(E->getRHS());
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002821 }
John McCall93d91dc2010-05-07 17:22:02 +00002822 if (!Visit(E->getLHS()))
2823 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002824
John McCall93d91dc2010-05-07 17:22:02 +00002825 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002826 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002827 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002828
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002829 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2830 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002831 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002832 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002833 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002834 if (Result.isComplexFloat()) {
2835 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2836 APFloat::rmNearestTiesToEven);
2837 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2838 APFloat::rmNearestTiesToEven);
2839 } else {
2840 Result.getComplexIntReal() += RHS.getComplexIntReal();
2841 Result.getComplexIntImag() += RHS.getComplexIntImag();
2842 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002843 break;
John McCalle3027922010-08-25 11:45:40 +00002844 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002845 if (Result.isComplexFloat()) {
2846 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2847 APFloat::rmNearestTiesToEven);
2848 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2849 APFloat::rmNearestTiesToEven);
2850 } else {
2851 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2852 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2853 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002854 break;
John McCalle3027922010-08-25 11:45:40 +00002855 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002856 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002857 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002858 APFloat &LHS_r = LHS.getComplexFloatReal();
2859 APFloat &LHS_i = LHS.getComplexFloatImag();
2860 APFloat &RHS_r = RHS.getComplexFloatReal();
2861 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002862
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002863 APFloat Tmp = LHS_r;
2864 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2865 Result.getComplexFloatReal() = Tmp;
2866 Tmp = LHS_i;
2867 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2868 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2869
2870 Tmp = LHS_r;
2871 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2872 Result.getComplexFloatImag() = Tmp;
2873 Tmp = LHS_i;
2874 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2875 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2876 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002877 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002878 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002879 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2880 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002881 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002882 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2883 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2884 }
2885 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002886 case BO_Div:
2887 if (Result.isComplexFloat()) {
2888 ComplexValue LHS = Result;
2889 APFloat &LHS_r = LHS.getComplexFloatReal();
2890 APFloat &LHS_i = LHS.getComplexFloatImag();
2891 APFloat &RHS_r = RHS.getComplexFloatReal();
2892 APFloat &RHS_i = RHS.getComplexFloatImag();
2893 APFloat &Res_r = Result.getComplexFloatReal();
2894 APFloat &Res_i = Result.getComplexFloatImag();
2895
2896 APFloat Den = RHS_r;
2897 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2898 APFloat Tmp = RHS_i;
2899 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2900 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2901
2902 Res_r = LHS_r;
2903 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2904 Tmp = LHS_i;
2905 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2906 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2907 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2908
2909 Res_i = LHS_i;
2910 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2911 Tmp = LHS_r;
2912 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2913 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2914 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2915 } else {
2916 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2917 // FIXME: what about diagnostics?
2918 return false;
2919 }
2920 ComplexValue LHS = Result;
2921 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2922 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2923 Result.getComplexIntReal() =
2924 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2925 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2926 Result.getComplexIntImag() =
2927 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2928 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2929 }
2930 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002931 }
2932
John McCall93d91dc2010-05-07 17:22:02 +00002933 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002934}
2935
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002936bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2937 // Get the operand value into 'Result'.
2938 if (!Visit(E->getSubExpr()))
2939 return false;
2940
2941 switch (E->getOpcode()) {
2942 default:
2943 // FIXME: what about diagnostics?
2944 return false;
2945 case UO_Extension:
2946 return true;
2947 case UO_Plus:
2948 // The result is always just the subexpr.
2949 return true;
2950 case UO_Minus:
2951 if (Result.isComplexFloat()) {
2952 Result.getComplexFloatReal().changeSign();
2953 Result.getComplexFloatImag().changeSign();
2954 }
2955 else {
2956 Result.getComplexIntReal() = -Result.getComplexIntReal();
2957 Result.getComplexIntImag() = -Result.getComplexIntImag();
2958 }
2959 return true;
2960 case UO_Not:
2961 if (Result.isComplexFloat())
2962 Result.getComplexFloatImag().changeSign();
2963 else
2964 Result.getComplexIntImag() = -Result.getComplexIntImag();
2965 return true;
2966 }
2967}
2968
Anders Carlsson537969c2008-11-16 20:27:53 +00002969//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00002970// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00002971//===----------------------------------------------------------------------===//
2972
Richard Smith0b0a0b62011-10-29 20:57:55 +00002973static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002974 // In C, function designators are not lvalues, but we evaluate them as if they
2975 // are.
2976 if (E->isGLValue() || E->getType()->isFunctionType()) {
2977 LValue LV;
2978 if (!EvaluateLValue(E, LV, Info))
2979 return false;
2980 LV.moveInto(Result);
2981 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00002982 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002983 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002984 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00002985 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002986 return false;
John McCall45d55e42010-05-07 21:00:08 +00002987 } else if (E->getType()->hasPointerRepresentation()) {
2988 LValue LV;
2989 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002990 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002991 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00002992 } else if (E->getType()->isRealFloatingType()) {
2993 llvm::APFloat F(0.0);
2994 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002995 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002996 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00002997 } else if (E->getType()->isAnyComplexType()) {
2998 ComplexValue C;
2999 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003000 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003001 C.moveInto(Result);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003002 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00003003 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003004
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00003005 return true;
3006}
3007
Richard Smith11562c52011-10-28 17:51:58 +00003008
Richard Smith7b553f12011-10-29 00:50:52 +00003009/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00003010/// any crazy technique (that has nothing to do with language standards) that
3011/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00003012/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3013/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00003014bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
John McCallc07a0c72011-02-17 10:25:35 +00003015 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00003016
Richard Smith0b0a0b62011-10-29 20:57:55 +00003017 CCValue Value;
3018 if (!::Evaluate(Value, Info, this))
Richard Smith11562c52011-10-28 17:51:58 +00003019 return false;
3020
3021 if (isGLValue()) {
3022 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003023 LV.setFrom(Value);
3024 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3025 return false;
Richard Smith11562c52011-10-28 17:51:58 +00003026 }
3027
Richard Smith0b0a0b62011-10-29 20:57:55 +00003028 // Check this core constant expression is a constant expression, and if so,
3029 // slice it down to one.
3030 if (!CheckConstantExpression(Value))
3031 return false;
3032 Result.Val = Value;
3033 return true;
John McCallc07a0c72011-02-17 10:25:35 +00003034}
3035
Jay Foad39c79802011-01-12 09:06:06 +00003036bool Expr::EvaluateAsBooleanCondition(bool &Result,
3037 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003038 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00003039 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith0b0a0b62011-10-29 20:57:55 +00003040 HandleConversionToBool(CCValue(Scratch.Val, CCValue::NoCallIndex),
3041 Result);
John McCall1be1c632010-01-05 23:42:56 +00003042}
3043
Richard Smithcaf33902011-10-10 18:28:20 +00003044bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003045 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003046 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smith11562c52011-10-28 17:51:58 +00003047 !ExprResult.Val.isInt()) {
3048 return false;
3049 }
3050 Result = ExprResult.Val.getInt();
3051 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00003052}
3053
Jay Foad39c79802011-01-12 09:06:06 +00003054bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00003055 EvalInfo Info(Ctx, Result);
3056
John McCall45d55e42010-05-07 21:00:08 +00003057 LValue LV;
Richard Smith11562c52011-10-28 17:51:58 +00003058 if (EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003059 IsGlobalLValue(LV.Base)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003060 Result.Val = APValue(LV.Base, LV.Offset);
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003061 return true;
3062 }
3063 return false;
3064}
3065
Jay Foad39c79802011-01-12 09:06:06 +00003066bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
3067 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003068 EvalInfo Info(Ctx, Result);
3069
3070 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003071 // Don't allow references to out-of-scope function parameters to escape.
3072 if (EvaluateLValue(this, LV, Info) &&
3073 (!IsParamLValue(LV.Base) || LV.CallIndex == CCValue::NoCallIndex)) {
3074 Result.Val = APValue(LV.Base, LV.Offset);
John McCall45d55e42010-05-07 21:00:08 +00003075 return true;
3076 }
3077 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00003078}
3079
Richard Smith7b553f12011-10-29 00:50:52 +00003080/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3081/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00003082bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00003083 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00003084 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00003085}
Anders Carlsson59689ed2008-11-22 21:04:56 +00003086
Jay Foad39c79802011-01-12 09:06:06 +00003087bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00003088 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003089}
3090
Richard Smithcaf33902011-10-10 18:28:20 +00003091APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003092 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003093 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00003094 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00003095 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003096 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00003097
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003098 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00003099}
John McCall864e3962010-05-07 05:32:02 +00003100
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003101 bool Expr::EvalResult::isGlobalLValue() const {
3102 assert(Val.isLValue());
3103 return IsGlobalLValue(Val.getLValueBase());
3104 }
3105
3106
John McCall864e3962010-05-07 05:32:02 +00003107/// isIntegerConstantExpr - this recursive routine will test if an expression is
3108/// an integer constant expression.
3109
3110/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
3111/// comma, etc
3112///
3113/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
3114/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
3115/// cast+dereference.
3116
3117// CheckICE - This function does the fundamental ICE checking: the returned
3118// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
3119// Note that to reduce code duplication, this helper does no evaluation
3120// itself; the caller checks whether the expression is evaluatable, and
3121// in the rare cases where CheckICE actually cares about the evaluated
3122// value, it calls into Evalute.
3123//
3124// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00003125// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00003126// 1: This expression is not an ICE, but if it isn't evaluated, it's
3127// a legal subexpression for an ICE. This return value is used to handle
3128// the comma operator in C99 mode.
3129// 2: This expression is not an ICE, and is not a legal subexpression for one.
3130
Dan Gohman28ade552010-07-26 21:25:24 +00003131namespace {
3132
John McCall864e3962010-05-07 05:32:02 +00003133struct ICEDiag {
3134 unsigned Val;
3135 SourceLocation Loc;
3136
3137 public:
3138 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
3139 ICEDiag() : Val(0) {}
3140};
3141
Dan Gohman28ade552010-07-26 21:25:24 +00003142}
3143
3144static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00003145
3146static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
3147 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003148 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003149 !EVResult.Val.isInt()) {
3150 return ICEDiag(2, E->getLocStart());
3151 }
3152 return NoDiag();
3153}
3154
3155static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
3156 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00003157 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00003158 return ICEDiag(2, E->getLocStart());
3159 }
3160
3161 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00003162#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00003163#define STMT(Node, Base) case Expr::Node##Class:
3164#define EXPR(Node, Base)
3165#include "clang/AST/StmtNodes.inc"
3166 case Expr::PredefinedExprClass:
3167 case Expr::FloatingLiteralClass:
3168 case Expr::ImaginaryLiteralClass:
3169 case Expr::StringLiteralClass:
3170 case Expr::ArraySubscriptExprClass:
3171 case Expr::MemberExprClass:
3172 case Expr::CompoundAssignOperatorClass:
3173 case Expr::CompoundLiteralExprClass:
3174 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00003175 case Expr::DesignatedInitExprClass:
3176 case Expr::ImplicitValueInitExprClass:
3177 case Expr::ParenListExprClass:
3178 case Expr::VAArgExprClass:
3179 case Expr::AddrLabelExprClass:
3180 case Expr::StmtExprClass:
3181 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00003182 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00003183 case Expr::CXXDynamicCastExprClass:
3184 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00003185 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00003186 case Expr::CXXNullPtrLiteralExprClass:
3187 case Expr::CXXThisExprClass:
3188 case Expr::CXXThrowExprClass:
3189 case Expr::CXXNewExprClass:
3190 case Expr::CXXDeleteExprClass:
3191 case Expr::CXXPseudoDestructorExprClass:
3192 case Expr::UnresolvedLookupExprClass:
3193 case Expr::DependentScopeDeclRefExprClass:
3194 case Expr::CXXConstructExprClass:
3195 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00003196 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00003197 case Expr::CXXTemporaryObjectExprClass:
3198 case Expr::CXXUnresolvedConstructExprClass:
3199 case Expr::CXXDependentScopeMemberExprClass:
3200 case Expr::UnresolvedMemberExprClass:
3201 case Expr::ObjCStringLiteralClass:
3202 case Expr::ObjCEncodeExprClass:
3203 case Expr::ObjCMessageExprClass:
3204 case Expr::ObjCSelectorExprClass:
3205 case Expr::ObjCProtocolExprClass:
3206 case Expr::ObjCIvarRefExprClass:
3207 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00003208 case Expr::ObjCIsaExprClass:
3209 case Expr::ShuffleVectorExprClass:
3210 case Expr::BlockExprClass:
3211 case Expr::BlockDeclRefExprClass:
3212 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00003213 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00003214 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00003215 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00003216 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00003217 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00003218 case Expr::MaterializeTemporaryExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003219 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00003220 return ICEDiag(2, E->getLocStart());
3221
Sebastian Redl12757ab2011-09-24 17:48:14 +00003222 case Expr::InitListExprClass:
3223 if (Ctx.getLangOptions().CPlusPlus0x) {
3224 const InitListExpr *ILE = cast<InitListExpr>(E);
3225 if (ILE->getNumInits() == 0)
3226 return NoDiag();
3227 if (ILE->getNumInits() == 1)
3228 return CheckICE(ILE->getInit(0), Ctx);
3229 // Fall through for more than 1 expression.
3230 }
3231 return ICEDiag(2, E->getLocStart());
3232
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003233 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00003234 case Expr::GNUNullExprClass:
3235 // GCC considers the GNU __null value to be an integral constant expression.
3236 return NoDiag();
3237
John McCall7c454bb2011-07-15 05:09:51 +00003238 case Expr::SubstNonTypeTemplateParmExprClass:
3239 return
3240 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
3241
John McCall864e3962010-05-07 05:32:02 +00003242 case Expr::ParenExprClass:
3243 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00003244 case Expr::GenericSelectionExprClass:
3245 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003246 case Expr::IntegerLiteralClass:
3247 case Expr::CharacterLiteralClass:
3248 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00003249 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00003250 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003251 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00003252 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00003253 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003254 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00003255 return NoDiag();
3256 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00003257 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00003258 // C99 6.6/3 allows function calls within unevaluated subexpressions of
3259 // constant expressions, but they can never be ICEs because an ICE cannot
3260 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00003261 const CallExpr *CE = cast<CallExpr>(E);
3262 if (CE->isBuiltinCall(Ctx))
3263 return CheckEvalInICE(E, Ctx);
3264 return ICEDiag(2, E->getLocStart());
3265 }
3266 case Expr::DeclRefExprClass:
3267 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
3268 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00003269 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00003270 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3271
3272 // Parameter variables are never constants. Without this check,
3273 // getAnyInitializer() can find a default argument, which leads
3274 // to chaos.
3275 if (isa<ParmVarDecl>(D))
3276 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3277
3278 // C++ 7.1.5.1p2
3279 // A variable of non-volatile const-qualified integral or enumeration
3280 // type initialized by an ICE can be used in ICEs.
3281 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCall864e3962010-05-07 05:32:02 +00003282 // Look for a declaration of this variable that has an initializer.
3283 const VarDecl *ID = 0;
3284 const Expr *Init = Dcl->getAnyInitializer(ID);
3285 if (Init) {
3286 if (ID->isInitKnownICE()) {
3287 // We have already checked whether this subexpression is an
3288 // integral constant expression.
3289 if (ID->isInitICE())
3290 return NoDiag();
3291 else
3292 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3293 }
3294
3295 // It's an ICE whether or not the definition we found is
3296 // out-of-line. See DR 721 and the discussion in Clang PR
3297 // 6206 for details.
3298
3299 if (Dcl->isCheckingICE()) {
3300 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3301 }
3302
3303 Dcl->setCheckingICE();
3304 ICEDiag Result = CheckICE(Init, Ctx);
3305 // Cache the result of the ICE test.
3306 Dcl->setInitKnownICE(Result.Val == 0);
3307 return Result;
3308 }
3309 }
3310 }
3311 return ICEDiag(2, E->getLocStart());
3312 case Expr::UnaryOperatorClass: {
3313 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3314 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003315 case UO_PostInc:
3316 case UO_PostDec:
3317 case UO_PreInc:
3318 case UO_PreDec:
3319 case UO_AddrOf:
3320 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00003321 // C99 6.6/3 allows increment and decrement within unevaluated
3322 // subexpressions of constant expressions, but they can never be ICEs
3323 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003324 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00003325 case UO_Extension:
3326 case UO_LNot:
3327 case UO_Plus:
3328 case UO_Minus:
3329 case UO_Not:
3330 case UO_Real:
3331 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003332 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003333 }
3334
3335 // OffsetOf falls through here.
3336 }
3337 case Expr::OffsetOfExprClass: {
3338 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00003339 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00003340 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00003341 // compliance: we should warn earlier for offsetof expressions with
3342 // array subscripts that aren't ICEs, and if the array subscripts
3343 // are ICEs, the value of the offsetof must be an integer constant.
3344 return CheckEvalInICE(E, Ctx);
3345 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003346 case Expr::UnaryExprOrTypeTraitExprClass: {
3347 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3348 if ((Exp->getKind() == UETT_SizeOf) &&
3349 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003350 return ICEDiag(2, E->getLocStart());
3351 return NoDiag();
3352 }
3353 case Expr::BinaryOperatorClass: {
3354 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3355 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003356 case BO_PtrMemD:
3357 case BO_PtrMemI:
3358 case BO_Assign:
3359 case BO_MulAssign:
3360 case BO_DivAssign:
3361 case BO_RemAssign:
3362 case BO_AddAssign:
3363 case BO_SubAssign:
3364 case BO_ShlAssign:
3365 case BO_ShrAssign:
3366 case BO_AndAssign:
3367 case BO_XorAssign:
3368 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00003369 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3370 // constant expressions, but they can never be ICEs because an ICE cannot
3371 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003372 return ICEDiag(2, E->getLocStart());
3373
John McCalle3027922010-08-25 11:45:40 +00003374 case BO_Mul:
3375 case BO_Div:
3376 case BO_Rem:
3377 case BO_Add:
3378 case BO_Sub:
3379 case BO_Shl:
3380 case BO_Shr:
3381 case BO_LT:
3382 case BO_GT:
3383 case BO_LE:
3384 case BO_GE:
3385 case BO_EQ:
3386 case BO_NE:
3387 case BO_And:
3388 case BO_Xor:
3389 case BO_Or:
3390 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003391 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3392 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003393 if (Exp->getOpcode() == BO_Div ||
3394 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00003395 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00003396 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003397 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003398 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003399 if (REval == 0)
3400 return ICEDiag(1, E->getLocStart());
3401 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003402 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003403 if (LEval.isMinSignedValue())
3404 return ICEDiag(1, E->getLocStart());
3405 }
3406 }
3407 }
John McCalle3027922010-08-25 11:45:40 +00003408 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003409 if (Ctx.getLangOptions().C99) {
3410 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3411 // if it isn't evaluated.
3412 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3413 return ICEDiag(1, E->getLocStart());
3414 } else {
3415 // In both C89 and C++, commas in ICEs are illegal.
3416 return ICEDiag(2, E->getLocStart());
3417 }
3418 }
3419 if (LHSResult.Val >= RHSResult.Val)
3420 return LHSResult;
3421 return RHSResult;
3422 }
John McCalle3027922010-08-25 11:45:40 +00003423 case BO_LAnd:
3424 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003425 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003426
3427 // C++0x [expr.const]p2:
3428 // [...] subexpressions of logical AND (5.14), logical OR
3429 // (5.15), and condi- tional (5.16) operations that are not
3430 // evaluated are not considered.
3431 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3432 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003433 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003434 return LHSResult;
3435
3436 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003437 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003438 return LHSResult;
3439 }
3440
John McCall864e3962010-05-07 05:32:02 +00003441 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3442 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3443 // Rare case where the RHS has a comma "side-effect"; we need
3444 // to actually check the condition to see whether the side
3445 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003446 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003447 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003448 return RHSResult;
3449 return NoDiag();
3450 }
3451
3452 if (LHSResult.Val >= RHSResult.Val)
3453 return LHSResult;
3454 return RHSResult;
3455 }
3456 }
3457 }
3458 case Expr::ImplicitCastExprClass:
3459 case Expr::CStyleCastExprClass:
3460 case Expr::CXXFunctionalCastExprClass:
3461 case Expr::CXXStaticCastExprClass:
3462 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00003463 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003464 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003465 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00003466 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00003467 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3468 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00003469 switch (cast<CastExpr>(E)->getCastKind()) {
3470 case CK_LValueToRValue:
3471 case CK_NoOp:
3472 case CK_IntegralToBoolean:
3473 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003474 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003475 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00003476 return ICEDiag(2, E->getLocStart());
3477 }
John McCall864e3962010-05-07 05:32:02 +00003478 }
John McCallc07a0c72011-02-17 10:25:35 +00003479 case Expr::BinaryConditionalOperatorClass: {
3480 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3481 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3482 if (CommonResult.Val == 2) return CommonResult;
3483 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3484 if (FalseResult.Val == 2) return FalseResult;
3485 if (CommonResult.Val == 1) return CommonResult;
3486 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003487 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003488 return FalseResult;
3489 }
John McCall864e3962010-05-07 05:32:02 +00003490 case Expr::ConditionalOperatorClass: {
3491 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3492 // If the condition (ignoring parens) is a __builtin_constant_p call,
3493 // then only the true side is actually considered in an integer constant
3494 // expression, and it is fully evaluated. This is an important GNU
3495 // extension. See GCC PR38377 for discussion.
3496 if (const CallExpr *CallCE
3497 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3498 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3499 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003500 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003501 !EVResult.Val.isInt()) {
3502 return ICEDiag(2, E->getLocStart());
3503 }
3504 return NoDiag();
3505 }
3506 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003507 if (CondResult.Val == 2)
3508 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003509
3510 // C++0x [expr.const]p2:
3511 // subexpressions of [...] conditional (5.16) operations that
3512 // are not evaluated are not considered
3513 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003514 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003515 : false;
3516 ICEDiag TrueResult = NoDiag();
3517 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3518 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3519 ICEDiag FalseResult = NoDiag();
3520 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3521 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3522
John McCall864e3962010-05-07 05:32:02 +00003523 if (TrueResult.Val == 2)
3524 return TrueResult;
3525 if (FalseResult.Val == 2)
3526 return FalseResult;
3527 if (CondResult.Val == 1)
3528 return CondResult;
3529 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3530 return NoDiag();
3531 // Rare case where the diagnostics depend on which side is evaluated
3532 // Note that if we get here, CondResult is 0, and at least one of
3533 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003534 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003535 return FalseResult;
3536 }
3537 return TrueResult;
3538 }
3539 case Expr::CXXDefaultArgExprClass:
3540 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3541 case Expr::ChooseExprClass: {
3542 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3543 }
3544 }
3545
3546 // Silence a GCC warning
3547 return ICEDiag(2, E->getLocStart());
3548}
3549
3550bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3551 SourceLocation *Loc, bool isEvaluated) const {
3552 ICEDiag d = CheckICE(this, Ctx);
3553 if (d.Val != 0) {
3554 if (Loc) *Loc = d.Loc;
3555 return false;
3556 }
Richard Smith11562c52011-10-28 17:51:58 +00003557 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00003558 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00003559 return true;
3560}