blob: 7fe03b58a053fc0fafb219ca3e5ce4d0970ea9e1 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Richard Smith254a73d2011-10-28 22:34:42 +000046 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000047 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000048
Richard Smith0b0a0b62011-10-29 20:57:55 +000049 /// A core constant value. This can be the value of any constant expression,
50 /// or a pointer or reference to a non-static object or function parameter.
51 class CCValue : public APValue {
52 typedef llvm::APSInt APSInt;
53 typedef llvm::APFloat APFloat;
Richard Smithfec09922011-11-01 16:57:24 +000054 /// If the value is a reference or pointer into a parameter or temporary,
55 /// this is the corresponding call stack frame.
56 CallStackFrame *CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +000057 public:
Richard Smithfec09922011-11-01 16:57:24 +000058 struct GlobalValue {};
59
Richard Smith0b0a0b62011-10-29 20:57:55 +000060 CCValue() {}
61 explicit CCValue(const APSInt &I) : APValue(I) {}
62 explicit CCValue(const APFloat &F) : APValue(F) {}
63 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
64 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
65 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smithfec09922011-11-01 16:57:24 +000066 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
67 CCValue(const Expr *B, const CharUnits &O, CallStackFrame *F) :
68 APValue(B, O), CallFrame(F) {}
69 CCValue(const APValue &V, GlobalValue) :
70 APValue(V), CallFrame(0) {}
Richard Smith0b0a0b62011-10-29 20:57:55 +000071
Richard Smithfec09922011-11-01 16:57:24 +000072 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +000073 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +000074 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +000075 }
76 };
77
Richard Smith254a73d2011-10-28 22:34:42 +000078 /// A stack frame in the constexpr call stack.
79 struct CallStackFrame {
80 EvalInfo &Info;
81
82 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +000083 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +000084
85 /// ParmBindings - Parameter bindings for this function call, indexed by
86 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +000087 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +000088
Richard Smith4e4c78ff2011-10-31 05:52:43 +000089 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
90 typedef MapTy::const_iterator temp_iterator;
91 /// Temporaries - Temporary lvalues materialized within this stack frame.
92 MapTy Temporaries;
93
94 CallStackFrame(EvalInfo &Info, const CCValue *Arguments);
95 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +000096 };
97
Richard Smith4e4c78ff2011-10-31 05:52:43 +000098 struct EvalInfo {
99 const ASTContext &Ctx;
100
101 /// EvalStatus - Contains information about the evaluation.
102 Expr::EvalStatus &EvalStatus;
103
104 /// CurrentCall - The top of the constexpr call stack.
105 CallStackFrame *CurrentCall;
106
107 /// NumCalls - The number of calls we've evaluated so far.
108 unsigned NumCalls;
109
110 /// CallStackDepth - The number of calls in the call stack right now.
111 unsigned CallStackDepth;
112
113 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
114 /// OpaqueValues - Values used as the common expression in a
115 /// BinaryConditionalOperator.
116 MapTy OpaqueValues;
117
118 /// BottomFrame - The frame in which evaluation started. This must be
119 /// initialized last.
120 CallStackFrame BottomFrame;
121
122
123 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
124 : Ctx(C), EvalStatus(S), CurrentCall(0), NumCalls(0), CallStackDepth(0),
125 BottomFrame(*this, 0) {}
126
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000127 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
128 MapTy::const_iterator i = OpaqueValues.find(e);
129 if (i == OpaqueValues.end()) return 0;
130 return &i->second;
131 }
132
133 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
134 };
135
136 CallStackFrame::CallStackFrame(EvalInfo &Info, const CCValue *Arguments)
Richard Smithfec09922011-11-01 16:57:24 +0000137 : Info(Info), Caller(Info.CurrentCall), Arguments(Arguments) {
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000138 Info.CurrentCall = this;
139 ++Info.CallStackDepth;
140 }
141
142 CallStackFrame::~CallStackFrame() {
143 assert(Info.CurrentCall == this && "calls retired out of order");
144 --Info.CallStackDepth;
145 Info.CurrentCall = Caller;
146 }
147
John McCall93d91dc2010-05-07 17:22:02 +0000148 struct ComplexValue {
149 private:
150 bool IsInt;
151
152 public:
153 APSInt IntReal, IntImag;
154 APFloat FloatReal, FloatImag;
155
156 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
157
158 void makeComplexFloat() { IsInt = false; }
159 bool isComplexFloat() const { return !IsInt; }
160 APFloat &getComplexFloatReal() { return FloatReal; }
161 APFloat &getComplexFloatImag() { return FloatImag; }
162
163 void makeComplexInt() { IsInt = true; }
164 bool isComplexInt() const { return IsInt; }
165 APSInt &getComplexIntReal() { return IntReal; }
166 APSInt &getComplexIntImag() { return IntImag; }
167
Richard Smith0b0a0b62011-10-29 20:57:55 +0000168 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000169 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000170 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000171 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000172 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000173 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000174 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000175 assert(v.isComplexFloat() || v.isComplexInt());
176 if (v.isComplexFloat()) {
177 makeComplexFloat();
178 FloatReal = v.getComplexFloatReal();
179 FloatImag = v.getComplexFloatImag();
180 } else {
181 makeComplexInt();
182 IntReal = v.getComplexIntReal();
183 IntImag = v.getComplexIntImag();
184 }
185 }
John McCall93d91dc2010-05-07 17:22:02 +0000186 };
John McCall45d55e42010-05-07 21:00:08 +0000187
188 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000189 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000190 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000191 CallStackFrame *Frame;
John McCall45d55e42010-05-07 21:00:08 +0000192
Richard Smith8b3497e2011-10-31 01:37:14 +0000193 const Expr *getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000194 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000195 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000196 CallStackFrame *getLValueFrame() const { return Frame; }
John McCall45d55e42010-05-07 21:00:08 +0000197
Richard Smith0b0a0b62011-10-29 20:57:55 +0000198 void moveInto(CCValue &V) const {
Richard Smithfec09922011-11-01 16:57:24 +0000199 V = CCValue(Base, Offset, Frame);
John McCall45d55e42010-05-07 21:00:08 +0000200 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000201 void setFrom(const CCValue &V) {
202 assert(V.isLValue());
203 Base = V.getLValueBase();
204 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000205 Frame = V.getLValueFrame();
John McCallc07a0c72011-02-17 10:25:35 +0000206 }
John McCall45d55e42010-05-07 21:00:08 +0000207 };
John McCall93d91dc2010-05-07 17:22:02 +0000208}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000209
Richard Smith0b0a0b62011-10-29 20:57:55 +0000210static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000211static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
212static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000213static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000214static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000215 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000216static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000217static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000218
219//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000220// Misc utilities
221//===----------------------------------------------------------------------===//
222
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000223static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000224 if (!E) return true;
225
226 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
227 if (isa<FunctionDecl>(DRE->getDecl()))
228 return true;
229 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
230 return VD->hasGlobalStorage();
231 return false;
232 }
233
234 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
235 return CLE->isFileScope();
236
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000237 if (isa<MemberExpr>(E) || isa<MaterializeTemporaryExpr>(E))
Richard Smith11562c52011-10-28 17:51:58 +0000238 return false;
239
John McCall95007602010-05-10 23:27:23 +0000240 return true;
241}
242
Richard Smith0b0a0b62011-10-29 20:57:55 +0000243/// Check that this core constant expression value is a valid value for a
244/// constant expression.
245static bool CheckConstantExpression(const CCValue &Value) {
246 return !Value.isLValue() || IsGlobalLValue(Value.getLValueBase());
247}
248
Richard Smith83c68212011-10-31 05:11:32 +0000249const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
250 if (!LVal.Base)
251 return 0;
252
253 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVal.Base))
254 return DRE->getDecl();
255
256 // FIXME: Static data members accessed via a MemberExpr are represented as
257 // that MemberExpr. We should use the Decl directly instead.
258 if (const MemberExpr *ME = dyn_cast<MemberExpr>(LVal.Base)) {
259 assert(!isa<FieldDecl>(ME->getMemberDecl()) && "shouldn't see fields here");
260 return ME->getMemberDecl();
261 }
262
263 return 0;
264}
265
266static bool IsLiteralLValue(const LValue &Value) {
267 return Value.Base &&
268 !isa<DeclRefExpr>(Value.Base) &&
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000269 !isa<MemberExpr>(Value.Base) &&
270 !isa<MaterializeTemporaryExpr>(Value.Base);
Richard Smith83c68212011-10-31 05:11:32 +0000271}
272
273static bool IsWeakLValue(const LValue &Value) {
274 const ValueDecl *Decl = GetLValueBaseDecl(Value);
275 if (!Decl)
276 return false;
277
278 return Decl->hasAttr<WeakAttr>() ||
279 Decl->hasAttr<WeakRefAttr>() ||
280 Decl->isWeakImported();
281}
282
Richard Smith11562c52011-10-28 17:51:58 +0000283static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCall45d55e42010-05-07 21:00:08 +0000284 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000285
John McCalleb3e4f32010-05-07 21:34:32 +0000286 // A null base expression indicates a null pointer. These are always
287 // evaluatable, and they are false unless the offset is zero.
288 if (!Base) {
289 Result = !Value.Offset.isZero();
290 return true;
291 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000292
John McCall95007602010-05-10 23:27:23 +0000293 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000294 // FIXME: C++11 requires such conversions. Remove this check.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000295 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000296
John McCalleb3e4f32010-05-07 21:34:32 +0000297 // We have a non-null base expression. These are generally known to
298 // be true, but if it'a decl-ref to a weak symbol it can be null at
299 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000300 Result = true;
Richard Smith83c68212011-10-31 05:11:32 +0000301 return !IsWeakLValue(Value);
Eli Friedman334046a2009-06-14 02:17:33 +0000302}
303
Richard Smith0b0a0b62011-10-29 20:57:55 +0000304static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000305 switch (Val.getKind()) {
306 case APValue::Uninitialized:
307 return false;
308 case APValue::Int:
309 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000310 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000311 case APValue::Float:
312 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000313 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000314 case APValue::ComplexInt:
315 Result = Val.getComplexIntReal().getBoolValue() ||
316 Val.getComplexIntImag().getBoolValue();
317 return true;
318 case APValue::ComplexFloat:
319 Result = !Val.getComplexFloatReal().isZero() ||
320 !Val.getComplexFloatImag().isZero();
321 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000322 case APValue::LValue: {
323 LValue PointerResult;
324 PointerResult.setFrom(Val);
325 return EvalPointerValueAsBool(PointerResult, Result);
326 }
Richard Smith11562c52011-10-28 17:51:58 +0000327 case APValue::Vector:
328 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000329 }
330
Richard Smith11562c52011-10-28 17:51:58 +0000331 llvm_unreachable("unknown APValue kind");
332}
333
334static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
335 EvalInfo &Info) {
336 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000337 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000338 if (!Evaluate(Val, Info, E))
339 return false;
340 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000341}
342
Mike Stump11289f42009-09-09 15:08:12 +0000343static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000344 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000345 unsigned DestWidth = Ctx.getIntWidth(DestType);
346 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000347 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000348
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000349 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000350 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000351 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000352 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
353 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000354}
355
Mike Stump11289f42009-09-09 15:08:12 +0000356static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000357 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000358 bool ignored;
359 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000360 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000361 APFloat::rmNearestTiesToEven, &ignored);
362 return Result;
363}
364
Mike Stump11289f42009-09-09 15:08:12 +0000365static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000366 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000367 unsigned DestWidth = Ctx.getIntWidth(DestType);
368 APSInt Result = Value;
369 // Figure out if this is a truncate, extend or noop cast.
370 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000371 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000372 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000373 return Result;
374}
375
Mike Stump11289f42009-09-09 15:08:12 +0000376static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000377 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000378
379 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
380 Result.convertFromAPInt(Value, Value.isSigned(),
381 APFloat::rmNearestTiesToEven);
382 return Result;
383}
384
Richard Smith27908702011-10-24 17:54:18 +0000385/// Try to evaluate the initializer for a variable declaration.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000386static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +0000387 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000388 // If this is a parameter to an active constexpr function call, perform
389 // argument substitution.
390 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithfec09922011-11-01 16:57:24 +0000391 if (!Frame || !Frame->Arguments)
392 return false;
393 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
394 return true;
Richard Smith254a73d2011-10-28 22:34:42 +0000395 }
Richard Smith27908702011-10-24 17:54:18 +0000396
397 const Expr *Init = VD->getAnyInitializer();
398 if (!Init)
Richard Smith0b0a0b62011-10-29 20:57:55 +0000399 return false;
Richard Smith27908702011-10-24 17:54:18 +0000400
Richard Smith0b0a0b62011-10-29 20:57:55 +0000401 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smithfec09922011-11-01 16:57:24 +0000402 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000403 return !Result.isUninit();
404 }
Richard Smith27908702011-10-24 17:54:18 +0000405
406 if (VD->isEvaluatingValue())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000407 return false;
Richard Smith27908702011-10-24 17:54:18 +0000408
409 VD->setEvaluatingValue();
410
Richard Smith0b0a0b62011-10-29 20:57:55 +0000411 Expr::EvalStatus EStatus;
412 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith11562c52011-10-28 17:51:58 +0000413 // FIXME: The caller will need to know whether the value was a constant
414 // expression. If not, we should propagate up a diagnostic.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000415 if (!Evaluate(Result, InitInfo, Init) || !CheckConstantExpression(Result)) {
Richard Smith27908702011-10-24 17:54:18 +0000416 VD->setEvaluatedValue(APValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000417 return false;
418 }
Richard Smith27908702011-10-24 17:54:18 +0000419
Richard Smith0b0a0b62011-10-29 20:57:55 +0000420 VD->setEvaluatedValue(Result);
421 return true;
Richard Smith27908702011-10-24 17:54:18 +0000422}
423
Richard Smith11562c52011-10-28 17:51:58 +0000424static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000425 Qualifiers Quals = T.getQualifiers();
426 return Quals.hasConst() && !Quals.hasVolatile();
427}
428
Richard Smith11562c52011-10-28 17:51:58 +0000429bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000430 const LValue &LVal, CCValue &RVal) {
Richard Smith11562c52011-10-28 17:51:58 +0000431 const Expr *Base = LVal.Base;
Richard Smithfec09922011-11-01 16:57:24 +0000432 CallStackFrame *Frame = LVal.Frame;
Richard Smith11562c52011-10-28 17:51:58 +0000433
434 // FIXME: Indirection through a null pointer deserves a diagnostic.
435 if (!Base)
436 return false;
437
438 // FIXME: Support accessing subobjects of objects of literal types. A simple
439 // byte offset is insufficient for C++11 semantics: we need to know how the
440 // reference was formed (which union member was named, for instance).
441 // FIXME: Support subobjects of StringLiteral and PredefinedExpr.
442 if (!LVal.Offset.isZero())
443 return false;
444
Richard Smith8b3497e2011-10-31 01:37:14 +0000445 if (const ValueDecl *D = GetLValueBaseDecl(LVal)) {
Richard Smith11562c52011-10-28 17:51:58 +0000446 // If the lvalue has been cast to some other type, don't try to read it.
447 // FIXME: Could simulate a bitcast here.
Richard Smith8b3497e2011-10-31 01:37:14 +0000448 if (!Info.Ctx.hasSameUnqualifiedType(Type, D->getType()))
449 return 0;
Richard Smith11562c52011-10-28 17:51:58 +0000450
Richard Smith11562c52011-10-28 17:51:58 +0000451 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
452 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +0000453 // expressions are constant expressions too. Inside constexpr functions,
454 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +0000455 // In C, such things can also be folded, although they are not ICEs.
456 //
Richard Smith254a73d2011-10-28 22:34:42 +0000457 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
458 // interpretation of C++11 suggests that volatile parameters are OK if
459 // they're never read (there's no prohibition against constructing volatile
460 // objects in constant expressions), but lvalue-to-rvalue conversions on
461 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +0000462 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith254a73d2011-10-28 22:34:42 +0000463 if (!VD || !(IsConstNonVolatile(VD->getType()) || isa<ParmVarDecl>(VD)) ||
Richard Smithfec09922011-11-01 16:57:24 +0000464 !Type->isLiteralType() || !EvaluateVarDeclInit(Info, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +0000465 return false;
466
Richard Smith0b0a0b62011-10-29 20:57:55 +0000467 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smith11562c52011-10-28 17:51:58 +0000468 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000469
470 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
471 // conversion. This happens when the declaration and the lvalue should be
472 // considered synonymous, for instance when initializing an array of char
473 // from a string literal. Continue as if the initializer lvalue was the
474 // value we were originally given.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000475 if (!RVal.getLValueOffset().isZero())
Richard Smith11562c52011-10-28 17:51:58 +0000476 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000477 Base = RVal.getLValueBase();
Richard Smithfec09922011-11-01 16:57:24 +0000478 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +0000479 }
480
Richard Smithfec09922011-11-01 16:57:24 +0000481 // If this is a temporary expression with a nontrivial initializer, grab the
482 // value from the relevant stack frame.
483 if (Frame) {
484 RVal = Frame->Temporaries[Base];
485 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000486 }
Richard Smith11562c52011-10-28 17:51:58 +0000487
488 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
489 // initializer until now for such expressions. Such an expression can't be
490 // an ICE in C, so this only matters for fold.
491 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
492 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
493 return Evaluate(RVal, Info, CLE->getInitializer());
494 }
495
496 return false;
497}
498
Mike Stump876387b2009-10-27 22:09:17 +0000499namespace {
Richard Smith254a73d2011-10-28 22:34:42 +0000500enum EvalStmtResult {
501 /// Evaluation failed.
502 ESR_Failed,
503 /// Hit a 'return' statement.
504 ESR_Returned,
505 /// Evaluation succeeded.
506 ESR_Succeeded
507};
508}
509
510// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000511static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +0000512 const Stmt *S) {
513 switch (S->getStmtClass()) {
514 default:
515 return ESR_Failed;
516
517 case Stmt::NullStmtClass:
518 case Stmt::DeclStmtClass:
519 return ESR_Succeeded;
520
521 case Stmt::ReturnStmtClass:
522 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
523 return ESR_Returned;
524 return ESR_Failed;
525
526 case Stmt::CompoundStmtClass: {
527 const CompoundStmt *CS = cast<CompoundStmt>(S);
528 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
529 BE = CS->body_end(); BI != BE; ++BI) {
530 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
531 if (ESR != ESR_Succeeded)
532 return ESR;
533 }
534 return ESR_Succeeded;
535 }
536 }
537}
538
539/// Evaluate a function call.
540static bool HandleFunctionCall(ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000541 EvalInfo &Info, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000542 // FIXME: Implement a proper call limit, along with a command-line flag.
543 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
544 return false;
545
Richard Smith0b0a0b62011-10-29 20:57:55 +0000546 SmallVector<CCValue, 16> ArgValues(Args.size());
Richard Smith254a73d2011-10-28 22:34:42 +0000547 // FIXME: Deal with default arguments and 'this'.
548 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
549 I != E; ++I)
550 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
551 return false;
552
553 CallStackFrame Frame(Info, ArgValues.data());
554 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
555}
556
557namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000558class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000559 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000560 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000561public:
562
Richard Smith725810a2011-10-16 21:26:27 +0000563 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000564
565 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000566 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000567 return true;
568 }
569
Peter Collingbournee9200682011-05-13 03:29:01 +0000570 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
571 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000572 return Visit(E->getResultExpr());
573 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000574 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000575 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000576 return true;
577 return false;
578 }
John McCall31168b02011-06-15 23:02:42 +0000579 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000580 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000581 return true;
582 return false;
583 }
584 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000585 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000586 return true;
587 return false;
588 }
589
Mike Stump876387b2009-10-27 22:09:17 +0000590 // We don't want to evaluate BlockExprs multiple times, as they generate
591 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000592 bool VisitBlockExpr(const BlockExpr *E) { return true; }
593 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
594 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000595 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000596 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
597 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
598 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
599 bool VisitStringLiteral(const StringLiteral *E) { return false; }
600 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
601 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000602 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000603 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000604 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000605 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000606 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000607 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
608 bool VisitBinAssign(const BinaryOperator *E) { return true; }
609 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
610 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000611 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000612 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
613 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
614 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
615 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
616 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000617 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000618 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000619 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000620 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000621 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000622
623 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000624 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000625 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
626 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000627 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000628 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000629 return false;
630 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000631
Peter Collingbournee9200682011-05-13 03:29:01 +0000632 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000633};
634
John McCallc07a0c72011-02-17 10:25:35 +0000635class OpaqueValueEvaluation {
636 EvalInfo &info;
637 OpaqueValueExpr *opaqueValue;
638
639public:
640 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
641 Expr *value)
642 : info(info), opaqueValue(opaqueValue) {
643
644 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000645 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000646 this->opaqueValue = 0;
647 return;
648 }
John McCallc07a0c72011-02-17 10:25:35 +0000649 }
650
651 bool hasError() const { return opaqueValue == 0; }
652
653 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000654 // FIXME: This will not work for recursive constexpr functions using opaque
655 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000656 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
657 }
658};
659
Mike Stump876387b2009-10-27 22:09:17 +0000660} // end anonymous namespace
661
Eli Friedman9a156e52008-11-12 09:44:48 +0000662//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000663// Generic Evaluation
664//===----------------------------------------------------------------------===//
665namespace {
666
667template <class Derived, typename RetTy=void>
668class ExprEvaluatorBase
669 : public ConstStmtVisitor<Derived, RetTy> {
670private:
Richard Smith0b0a0b62011-10-29 20:57:55 +0000671 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000672 return static_cast<Derived*>(this)->Success(V, E);
673 }
674 RetTy DerivedError(const Expr *E) {
675 return static_cast<Derived*>(this)->Error(E);
676 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000677 RetTy DerivedValueInitialization(const Expr *E) {
678 return static_cast<Derived*>(this)->ValueInitialization(E);
679 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000680
681protected:
682 EvalInfo &Info;
683 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
684 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
685
Richard Smith4ce706a2011-10-11 21:43:33 +0000686 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
687
Richard Smithfec09922011-11-01 16:57:24 +0000688 bool MakeTemporary(const Expr *Key, const Expr *Value, LValue &Result) {
689 if (!Evaluate(Info.CurrentCall->Temporaries[Key], Info, Value))
690 return false;
691 Result.Base = Key;
692 Result.Offset = CharUnits::Zero();
693 Result.Frame = Info.CurrentCall;
694 return true;
695 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000696public:
697 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
698
699 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000700 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000701 }
702 RetTy VisitExpr(const Expr *E) {
703 return DerivedError(E);
704 }
705
706 RetTy VisitParenExpr(const ParenExpr *E)
707 { return StmtVisitorTy::Visit(E->getSubExpr()); }
708 RetTy VisitUnaryExtension(const UnaryOperator *E)
709 { return StmtVisitorTy::Visit(E->getSubExpr()); }
710 RetTy VisitUnaryPlus(const UnaryOperator *E)
711 { return StmtVisitorTy::Visit(E->getSubExpr()); }
712 RetTy VisitChooseExpr(const ChooseExpr *E)
713 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
714 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
715 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000716 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
717 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000718
719 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
720 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
721 if (opaque.hasError())
722 return DerivedError(E);
723
724 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +0000725 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000726 return DerivedError(E);
727
728 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
729 }
730
731 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
732 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +0000733 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000734 return DerivedError(E);
735
Richard Smith11562c52011-10-28 17:51:58 +0000736 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +0000737 return StmtVisitorTy::Visit(EvalExpr);
738 }
739
740 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000741 const CCValue *Value = Info.getOpaqueValue(E);
742 if (!Value)
Peter Collingbournee9200682011-05-13 03:29:01 +0000743 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
744 : DerivedError(E));
Richard Smith0b0a0b62011-10-29 20:57:55 +0000745 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000746 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000747
Richard Smith254a73d2011-10-28 22:34:42 +0000748 RetTy VisitCallExpr(const CallExpr *E) {
749 const Expr *Callee = E->getCallee();
750 QualType CalleeType = Callee->getType();
751
752 // FIXME: Handle the case where Callee is a (parenthesized) MemberExpr for a
753 // non-static member function.
754 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember))
755 return DerivedError(E);
756
757 if (!CalleeType->isFunctionType() && !CalleeType->isFunctionPointerType())
758 return DerivedError(E);
759
Richard Smith0b0a0b62011-10-29 20:57:55 +0000760 CCValue Call;
Richard Smith254a73d2011-10-28 22:34:42 +0000761 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
762 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
763 return DerivedError(Callee);
764
765 const FunctionDecl *FD = 0;
766 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Call.getLValueBase()))
767 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
768 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Call.getLValueBase()))
769 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
770 if (!FD)
771 return DerivedError(Callee);
772
773 // Don't call function pointers which have been cast to some other type.
774 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
775 return DerivedError(E);
776
777 const FunctionDecl *Definition;
778 Stmt *Body = FD->getBody(Definition);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000779 CCValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +0000780 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
781
782 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
Richard Smithfec09922011-11-01 16:57:24 +0000783 HandleFunctionCall(Args, Body, Info, Result) &&
784 CheckConstantExpression(Result))
Richard Smith254a73d2011-10-28 22:34:42 +0000785 return DerivedSuccess(Result, E);
786
787 return DerivedError(E);
788 }
789
Richard Smith11562c52011-10-28 17:51:58 +0000790 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
791 return StmtVisitorTy::Visit(E->getInitializer());
792 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000793 RetTy VisitInitListExpr(const InitListExpr *E) {
794 if (Info.getLangOpts().CPlusPlus0x) {
795 if (E->getNumInits() == 0)
796 return DerivedValueInitialization(E);
797 if (E->getNumInits() == 1)
798 return StmtVisitorTy::Visit(E->getInit(0));
799 }
800 return DerivedError(E);
801 }
802 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
803 return DerivedValueInitialization(E);
804 }
805 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
806 return DerivedValueInitialization(E);
807 }
808
Richard Smith11562c52011-10-28 17:51:58 +0000809 RetTy VisitCastExpr(const CastExpr *E) {
810 switch (E->getCastKind()) {
811 default:
812 break;
813
814 case CK_NoOp:
815 return StmtVisitorTy::Visit(E->getSubExpr());
816
817 case CK_LValueToRValue: {
818 LValue LVal;
819 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000820 CCValue RVal;
Richard Smith11562c52011-10-28 17:51:58 +0000821 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
822 return DerivedSuccess(RVal, E);
823 }
824 break;
825 }
826 }
827
828 return DerivedError(E);
829 }
830
Richard Smith4a678122011-10-24 18:44:57 +0000831 /// Visit a value which is evaluated, but whose value is ignored.
832 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000833 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +0000834 if (!Evaluate(Scratch, Info, E))
835 Info.EvalStatus.HasSideEffects = true;
836 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000837};
838
839}
840
841//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000842// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +0000843//
844// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
845// function designators (in C), decl references to void objects (in C), and
846// temporaries (if building with -Wno-address-of-temporary).
847//
848// LValue evaluation produces values comprising a base expression of one of the
849// following types:
850// * DeclRefExpr
851// * MemberExpr for a static member
852// * CompoundLiteralExpr in C
853// * StringLiteral
854// * PredefinedExpr
855// * ObjCEncodeExpr
856// * AddrLabelExpr
857// * BlockExpr
858// * CallExpr for a MakeStringConstant builtin
Richard Smithfec09922011-11-01 16:57:24 +0000859// plus an offset in bytes. It can also produce lvalues referring to locals. In
860// that case, the Frame will point to a stack frame, and the Expr is used as a
861// key to find the relevant temporary's value.
Eli Friedman9a156e52008-11-12 09:44:48 +0000862//===----------------------------------------------------------------------===//
863namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000864class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000865 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000866 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000867 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000868
Peter Collingbournee9200682011-05-13 03:29:01 +0000869 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000870 Result.Base = E;
871 Result.Offset = CharUnits::Zero();
Richard Smithfec09922011-11-01 16:57:24 +0000872 Result.Frame = 0;
John McCall45d55e42010-05-07 21:00:08 +0000873 return true;
874 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000875public:
Mike Stump11289f42009-09-09 15:08:12 +0000876
John McCall45d55e42010-05-07 21:00:08 +0000877 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000878 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000879
Richard Smith0b0a0b62011-10-29 20:57:55 +0000880 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000881 Result.setFrom(V);
882 return true;
883 }
884 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000885 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000886 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000887
Richard Smith11562c52011-10-28 17:51:58 +0000888 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
889
Peter Collingbournee9200682011-05-13 03:29:01 +0000890 bool VisitDeclRefExpr(const DeclRefExpr *E);
891 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000892 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000893 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
894 bool VisitMemberExpr(const MemberExpr *E);
895 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
896 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
897 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
898 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000899
Peter Collingbournee9200682011-05-13 03:29:01 +0000900 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000901 switch (E->getCastKind()) {
902 default:
Richard Smith11562c52011-10-28 17:51:58 +0000903 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000904
Eli Friedmance3e02a2011-10-11 00:13:24 +0000905 case CK_LValueBitCast:
Anders Carlssonde55f642009-10-03 16:30:22 +0000906 return Visit(E->getSubExpr());
Eli Friedmance3e02a2011-10-11 00:13:24 +0000907
Richard Smith11562c52011-10-28 17:51:58 +0000908 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
909 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlssonde55f642009-10-03 16:30:22 +0000910 }
911 }
Sebastian Redl12757ab2011-09-24 17:48:14 +0000912
Eli Friedman449fe542009-03-23 04:56:01 +0000913 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000914
Eli Friedman9a156e52008-11-12 09:44:48 +0000915};
916} // end anonymous namespace
917
Richard Smith11562c52011-10-28 17:51:58 +0000918/// Evaluate an expression as an lvalue. This can be legitimately called on
919/// expressions which are not glvalues, in a few cases:
920/// * function designators in C,
921/// * "extern void" objects,
922/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +0000923static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +0000924 assert((E->isGLValue() || E->getType()->isFunctionType() ||
925 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
926 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +0000927 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000928}
929
Peter Collingbournee9200682011-05-13 03:29:01 +0000930bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000931 if (isa<FunctionDecl>(E->getDecl()))
John McCall45d55e42010-05-07 21:00:08 +0000932 return Success(E);
Richard Smith11562c52011-10-28 17:51:58 +0000933 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
934 return VisitVarDecl(E, VD);
935 return Error(E);
936}
Richard Smith733237d2011-10-24 23:14:33 +0000937
Richard Smith11562c52011-10-28 17:51:58 +0000938bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +0000939 if (!VD->getType()->isReferenceType()) {
940 if (isa<ParmVarDecl>(VD)) {
941 Result.Base = E;
942 Result.Offset = CharUnits::Zero();
943 Result.Frame = Info.CurrentCall;
944 return true;
945 }
Richard Smith11562c52011-10-28 17:51:58 +0000946 return Success(E);
Richard Smithfec09922011-11-01 16:57:24 +0000947 }
Eli Friedman751aa72b72009-05-27 06:04:58 +0000948
Richard Smith0b0a0b62011-10-29 20:57:55 +0000949 CCValue V;
Richard Smithfec09922011-11-01 16:57:24 +0000950 if (EvaluateVarDeclInit(Info, VD, Info.CurrentCall, V))
Richard Smith0b0a0b62011-10-29 20:57:55 +0000951 return Success(V, E);
Richard Smith11562c52011-10-28 17:51:58 +0000952
953 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000954}
955
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000956bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
957 const MaterializeTemporaryExpr *E) {
Richard Smithfec09922011-11-01 16:57:24 +0000958 return MakeTemporary(E, E->GetTemporaryExpr(), Result);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000959}
960
Peter Collingbournee9200682011-05-13 03:29:01 +0000961bool
962LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000963 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
964 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
965 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +0000966 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000967}
968
Peter Collingbournee9200682011-05-13 03:29:01 +0000969bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000970 // Handle static data members.
971 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
972 VisitIgnoredValue(E->getBase());
973 return VisitVarDecl(E, VD);
974 }
975
Richard Smith254a73d2011-10-28 22:34:42 +0000976 // Handle static member functions.
977 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
978 if (MD->isStatic()) {
979 VisitIgnoredValue(E->getBase());
980 return Success(E);
981 }
982 }
983
Eli Friedman9a156e52008-11-12 09:44:48 +0000984 QualType Ty;
985 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000986 if (!EvaluatePointer(E->getBase(), Result, Info))
987 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000988 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000989 } else {
John McCall45d55e42010-05-07 21:00:08 +0000990 if (!Visit(E->getBase()))
991 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000992 Ty = E->getBase()->getType();
993 }
994
Peter Collingbournee9200682011-05-13 03:29:01 +0000995 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000996 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000997
Peter Collingbournee9200682011-05-13 03:29:01 +0000998 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000999 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +00001000 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001001
1002 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +00001003 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001004
Eli Friedmana3c122d2011-07-07 01:54:01 +00001005 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001006 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +00001007 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +00001008}
1009
Peter Collingbournee9200682011-05-13 03:29:01 +00001010bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001011 // FIXME: Deal with vectors as array subscript bases.
1012 if (E->getBase()->getType()->isVectorType())
1013 return false;
1014
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001015 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00001016 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001017
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001018 APSInt Index;
1019 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00001020 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001021
Ken Dyck40775002010-01-11 17:06:35 +00001022 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +00001023 Result.Offset += Index.getSExtValue() * ElementSize;
1024 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001025}
Eli Friedman9a156e52008-11-12 09:44:48 +00001026
Peter Collingbournee9200682011-05-13 03:29:01 +00001027bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00001028 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00001029}
1030
Eli Friedman9a156e52008-11-12 09:44:48 +00001031//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001032// Pointer Evaluation
1033//===----------------------------------------------------------------------===//
1034
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001035namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001036class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001037 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001038 LValue &Result;
1039
Peter Collingbournee9200682011-05-13 03:29:01 +00001040 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00001041 Result.Base = E;
1042 Result.Offset = CharUnits::Zero();
Richard Smithfec09922011-11-01 16:57:24 +00001043 Result.Frame = 0;
John McCall45d55e42010-05-07 21:00:08 +00001044 return true;
1045 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001046public:
Mike Stump11289f42009-09-09 15:08:12 +00001047
John McCall45d55e42010-05-07 21:00:08 +00001048 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001049 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001050
Richard Smith0b0a0b62011-10-29 20:57:55 +00001051 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001052 Result.setFrom(V);
1053 return true;
1054 }
1055 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +00001056 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001057 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001058 bool ValueInitialization(const Expr *E) {
1059 return Success((Expr*)0);
1060 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001061
John McCall45d55e42010-05-07 21:00:08 +00001062 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001063 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00001064 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001065 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00001066 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001067 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00001068 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001069 bool VisitCallExpr(const CallExpr *E);
1070 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00001071 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00001072 return Success(E);
1073 return false;
Mike Stumpa6703322009-02-19 22:01:56 +00001074 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001075 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +00001076 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +00001077
Eli Friedman449fe542009-03-23 04:56:01 +00001078 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001079};
Chris Lattner05706e882008-07-11 18:11:29 +00001080} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001081
John McCall45d55e42010-05-07 21:00:08 +00001082static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001083 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00001084 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00001085}
1086
John McCall45d55e42010-05-07 21:00:08 +00001087bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001088 if (E->getOpcode() != BO_Add &&
1089 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +00001090 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001091
Chris Lattner05706e882008-07-11 18:11:29 +00001092 const Expr *PExp = E->getLHS();
1093 const Expr *IExp = E->getRHS();
1094 if (IExp->getType()->isPointerType())
1095 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00001096
John McCall45d55e42010-05-07 21:00:08 +00001097 if (!EvaluatePointer(PExp, Result, Info))
1098 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001099
John McCall45d55e42010-05-07 21:00:08 +00001100 llvm::APSInt Offset;
1101 if (!EvaluateInteger(IExp, Offset, Info))
1102 return false;
1103 int64_t AdditionalOffset
1104 = Offset.isSigned() ? Offset.getSExtValue()
1105 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +00001106
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001107 // Compute the new offset in the appropriate width.
1108
1109 QualType PointeeType =
1110 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +00001111 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +00001112
Anders Carlssonef56fba2009-02-19 04:55:58 +00001113 // Explicitly handle GNU void* and function pointer arithmetic extensions.
1114 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +00001115 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +00001116 else
John McCall45d55e42010-05-07 21:00:08 +00001117 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +00001118
John McCalle3027922010-08-25 11:45:40 +00001119 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +00001120 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +00001121 else
John McCall45d55e42010-05-07 21:00:08 +00001122 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +00001123
John McCall45d55e42010-05-07 21:00:08 +00001124 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001125}
Eli Friedman9a156e52008-11-12 09:44:48 +00001126
John McCall45d55e42010-05-07 21:00:08 +00001127bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1128 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001129}
Mike Stump11289f42009-09-09 15:08:12 +00001130
Chris Lattner05706e882008-07-11 18:11:29 +00001131
Peter Collingbournee9200682011-05-13 03:29:01 +00001132bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1133 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00001134
Eli Friedman847a2bc2009-12-27 05:43:15 +00001135 switch (E->getCastKind()) {
1136 default:
1137 break;
1138
John McCalle3027922010-08-25 11:45:40 +00001139 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00001140 case CK_CPointerToObjCPointerCast:
1141 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001142 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +00001143 return Visit(SubExpr);
1144
Anders Carlsson18275092010-10-31 20:41:46 +00001145 case CK_DerivedToBase:
1146 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001147 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00001148 return false;
1149
1150 // Now figure out the necessary offset to add to the baseLV to get from
1151 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +00001152 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +00001153
1154 QualType Ty = E->getSubExpr()->getType();
1155 const CXXRecordDecl *DerivedDecl =
1156 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
1157
1158 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1159 PathE = E->path_end(); PathI != PathE; ++PathI) {
1160 const CXXBaseSpecifier *Base = *PathI;
1161
1162 // FIXME: If the base is virtual, we'd need to determine the type of the
1163 // most derived class and we don't support that right now.
1164 if (Base->isVirtual())
1165 return false;
1166
1167 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1168 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1169
Richard Smith0b0a0b62011-10-29 20:57:55 +00001170 Result.getLValueOffset() += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +00001171 DerivedDecl = BaseDecl;
1172 }
1173
Anders Carlsson18275092010-10-31 20:41:46 +00001174 return true;
1175 }
1176
Richard Smith0b0a0b62011-10-29 20:57:55 +00001177 case CK_NullToPointer:
1178 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00001179
John McCalle3027922010-08-25 11:45:40 +00001180 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001181 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00001182 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00001183 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00001184
John McCall45d55e42010-05-07 21:00:08 +00001185 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001186 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1187 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
John McCall45d55e42010-05-07 21:00:08 +00001188 Result.Base = 0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001189 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00001190 Result.Frame = 0;
John McCall45d55e42010-05-07 21:00:08 +00001191 return true;
1192 } else {
1193 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001194 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00001195 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001196 }
1197 }
John McCalle3027922010-08-25 11:45:40 +00001198 case CK_ArrayToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00001199 // FIXME: Support array-to-pointer decay on array rvalues.
1200 if (!SubExpr->isGLValue())
1201 return Error(E);
1202 return EvaluateLValue(SubExpr, Result, Info);
1203
John McCalle3027922010-08-25 11:45:40 +00001204 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00001205 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001206 }
1207
Richard Smith11562c52011-10-28 17:51:58 +00001208 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00001209}
Chris Lattner05706e882008-07-11 18:11:29 +00001210
Peter Collingbournee9200682011-05-13 03:29:01 +00001211bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +00001212 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +00001213 Builtin::BI__builtin___CFStringMakeConstantString ||
1214 E->isBuiltinCall(Info.Ctx) ==
1215 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +00001216 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00001217
Peter Collingbournee9200682011-05-13 03:29:01 +00001218 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001219}
Chris Lattner05706e882008-07-11 18:11:29 +00001220
1221//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001222// Vector Evaluation
1223//===----------------------------------------------------------------------===//
1224
1225namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001226 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00001227 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1228 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001229 public:
Mike Stump11289f42009-09-09 15:08:12 +00001230
Richard Smith2d406342011-10-22 21:10:00 +00001231 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1232 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001233
Richard Smith2d406342011-10-22 21:10:00 +00001234 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1235 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1236 // FIXME: remove this APValue copy.
1237 Result = APValue(V.data(), V.size());
1238 return true;
1239 }
1240 bool Success(const APValue &V, const Expr *E) {
1241 Result = V;
1242 return true;
1243 }
1244 bool Error(const Expr *E) { return false; }
1245 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00001246
Richard Smith2d406342011-10-22 21:10:00 +00001247 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00001248 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00001249 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00001250 bool VisitInitListExpr(const InitListExpr *E);
1251 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001252 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001253 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00001254 // shufflevector, ExtVectorElementExpr
1255 // (Note that these require implementing conversions
1256 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001257 };
1258} // end anonymous namespace
1259
1260static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001261 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00001262 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001263}
1264
Richard Smith2d406342011-10-22 21:10:00 +00001265bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1266 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001267 QualType EltTy = VTy->getElementType();
1268 unsigned NElts = VTy->getNumElements();
1269 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +00001270
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001271 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00001272 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001273
Eli Friedmanc757de22011-03-25 00:43:55 +00001274 switch (E->getCastKind()) {
1275 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00001276 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00001277 if (SETy->isIntegerType()) {
1278 APSInt IntResult;
1279 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001280 return Error(E);
1281 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00001282 } else if (SETy->isRealFloatingType()) {
1283 APFloat F(0.0);
1284 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001285 return Error(E);
1286 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00001287 } else {
Richard Smith2d406342011-10-22 21:10:00 +00001288 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001289 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001290
1291 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00001292 SmallVector<APValue, 4> Elts(NElts, Val);
1293 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00001294 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001295 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +00001296 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +00001297 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +00001298 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001299
Eli Friedmanc757de22011-03-25 00:43:55 +00001300 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +00001301 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +00001302
Eli Friedmanc757de22011-03-25 00:43:55 +00001303 APSInt Init;
1304 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001305 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001306
Eli Friedmanc757de22011-03-25 00:43:55 +00001307 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1308 "Vectors must be composed of ints or floats");
1309
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001310 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +00001311 for (unsigned i = 0; i != NElts; ++i) {
1312 APSInt Tmp = Init.extOrTrunc(EltWidth);
1313
1314 if (EltTy->isIntegerType())
1315 Elts.push_back(APValue(Tmp));
1316 else
1317 Elts.push_back(APValue(APFloat(Tmp)));
1318
1319 Init >>= EltWidth;
1320 }
Richard Smith2d406342011-10-22 21:10:00 +00001321 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001322 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001323 default:
Richard Smith11562c52011-10-28 17:51:58 +00001324 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001325 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001326}
1327
Richard Smith2d406342011-10-22 21:10:00 +00001328bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001329VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00001330 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001331 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00001332 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00001333
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001334 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001335 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001336
John McCall875679e2010-06-11 17:54:15 +00001337 // If a vector is initialized with a single element, that value
1338 // becomes every element of the vector, not just the first.
1339 // This is the behavior described in the IBM AltiVec documentation.
1340 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00001341
1342 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00001343 // vector (OpenCL 6.1.6).
1344 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00001345 return Visit(E->getInit(0));
1346
John McCall875679e2010-06-11 17:54:15 +00001347 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001348 if (EltTy->isIntegerType()) {
1349 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00001350 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001351 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001352 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001353 } else {
1354 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00001355 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001356 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001357 InitValue = APValue(f);
1358 }
1359 for (unsigned i = 0; i < NumElements; i++) {
1360 Elements.push_back(InitValue);
1361 }
1362 } else {
1363 for (unsigned i = 0; i < NumElements; i++) {
1364 if (EltTy->isIntegerType()) {
1365 llvm::APSInt sInt(32);
1366 if (i < NumInits) {
1367 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001368 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001369 } else {
1370 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1371 }
1372 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00001373 } else {
John McCall875679e2010-06-11 17:54:15 +00001374 llvm::APFloat f(0.0);
1375 if (i < NumInits) {
1376 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001377 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001378 } else {
1379 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1380 }
1381 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00001382 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001383 }
1384 }
Richard Smith2d406342011-10-22 21:10:00 +00001385 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001386}
1387
Richard Smith2d406342011-10-22 21:10:00 +00001388bool
1389VectorExprEvaluator::ValueInitialization(const Expr *E) {
1390 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00001391 QualType EltTy = VT->getElementType();
1392 APValue ZeroElement;
1393 if (EltTy->isIntegerType())
1394 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1395 else
1396 ZeroElement =
1397 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1398
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001399 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00001400 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001401}
1402
Richard Smith2d406342011-10-22 21:10:00 +00001403bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00001404 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00001405 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001406}
1407
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001408//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001409// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001410//
1411// As a GNU extension, we support casting pointers to sufficiently-wide integer
1412// types and back in constant folding. Integer values are thus represented
1413// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00001414//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001415
1416namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001417class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001418 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001419 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001420public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001421 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001422 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001423
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001424 bool Success(const llvm::APSInt &SI, const Expr *E) {
1425 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001426 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001427 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001428 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001429 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001430 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001431 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001432 return true;
1433 }
1434
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001435 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001436 assert(E->getType()->isIntegralOrEnumerationType() &&
1437 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001438 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001439 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001440 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001441 Result.getInt().setIsUnsigned(
1442 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001443 return true;
1444 }
1445
1446 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001447 assert(E->getType()->isIntegralOrEnumerationType() &&
1448 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001449 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001450 return true;
1451 }
1452
Ken Dyckdbc01912011-03-11 02:13:43 +00001453 bool Success(CharUnits Size, const Expr *E) {
1454 return Success(Size.getQuantity(), E);
1455 }
1456
1457
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001458 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001459 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001460 if (Info.EvalStatus.Diag == 0) {
1461 Info.EvalStatus.DiagLoc = L;
1462 Info.EvalStatus.Diag = D;
1463 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001464 }
Chris Lattner99415702008-07-12 00:14:42 +00001465 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001466 }
Mike Stump11289f42009-09-09 15:08:12 +00001467
Richard Smith0b0a0b62011-10-29 20:57:55 +00001468 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00001469 if (V.isLValue()) {
1470 Result = V;
1471 return true;
1472 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001473 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001474 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001475 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001476 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001477 }
Mike Stump11289f42009-09-09 15:08:12 +00001478
Richard Smith4ce706a2011-10-11 21:43:33 +00001479 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1480
Peter Collingbournee9200682011-05-13 03:29:01 +00001481 //===--------------------------------------------------------------------===//
1482 // Visitor Methods
1483 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001484
Chris Lattner7174bf32008-07-12 00:38:25 +00001485 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001486 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001487 }
1488 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001489 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001490 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001491
1492 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1493 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001494 if (CheckReferencedDecl(E, E->getDecl()))
1495 return true;
1496
1497 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001498 }
1499 bool VisitMemberExpr(const MemberExpr *E) {
1500 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00001501 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001502 return true;
1503 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001504
1505 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001506 }
1507
Peter Collingbournee9200682011-05-13 03:29:01 +00001508 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001509 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001510 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001511 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001512
Peter Collingbournee9200682011-05-13 03:29:01 +00001513 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001514 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001515
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001516 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001517 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001518 }
Mike Stump11289f42009-09-09 15:08:12 +00001519
Richard Smith4ce706a2011-10-11 21:43:33 +00001520 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001521 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001522 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001523 }
1524
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001525 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001526 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001527 }
1528
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001529 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1530 return Success(E->getValue(), E);
1531 }
1532
John Wiegley6242b6a2011-04-28 00:16:57 +00001533 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1534 return Success(E->getValue(), E);
1535 }
1536
John Wiegleyf9f65842011-04-25 06:54:41 +00001537 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1538 return Success(E->getValue(), E);
1539 }
1540
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001541 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001542 bool VisitUnaryImag(const UnaryOperator *E);
1543
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001544 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001545 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001546
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001547private:
Ken Dyck160146e2010-01-27 17:10:57 +00001548 CharUnits GetAlignOfExpr(const Expr *E);
1549 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001550 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001551 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001552 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001553};
Chris Lattner05706e882008-07-11 18:11:29 +00001554} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001555
Richard Smith11562c52011-10-28 17:51:58 +00001556/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1557/// produce either the integer value or a pointer.
1558///
1559/// GCC has a heinous extension which folds casts between pointer types and
1560/// pointer-sized integral types. We support this by allowing the evaluation of
1561/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1562/// Some simple arithmetic on such values is supported (they are treated much
1563/// like char*).
Richard Smith0b0a0b62011-10-29 20:57:55 +00001564static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
1565 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001566 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001567 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001568}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001569
Daniel Dunbarce399542009-02-20 18:22:23 +00001570static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001571 CCValue Val;
Daniel Dunbarce399542009-02-20 18:22:23 +00001572 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1573 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001574 Result = Val.getInt();
1575 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001576}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001577
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001578bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001579 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001580 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001581 // Check for signedness/width mismatches between E type and ECD value.
1582 bool SameSign = (ECD->getInitVal().isSigned()
1583 == E->getType()->isSignedIntegerOrEnumerationType());
1584 bool SameWidth = (ECD->getInitVal().getBitWidth()
1585 == Info.Ctx.getIntWidth(E->getType()));
1586 if (SameSign && SameWidth)
1587 return Success(ECD->getInitVal(), E);
1588 else {
1589 // Get rid of mismatch (otherwise Success assertions will fail)
1590 // by computing a new value matching the type of E.
1591 llvm::APSInt Val = ECD->getInitVal();
1592 if (!SameSign)
1593 Val.setIsSigned(!ECD->getInitVal().isSigned());
1594 if (!SameWidth)
1595 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1596 return Success(Val, E);
1597 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001598 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001599 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001600}
1601
Chris Lattner86ee2862008-10-06 06:40:35 +00001602/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1603/// as GCC.
1604static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1605 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001606 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001607 enum gcc_type_class {
1608 no_type_class = -1,
1609 void_type_class, integer_type_class, char_type_class,
1610 enumeral_type_class, boolean_type_class,
1611 pointer_type_class, reference_type_class, offset_type_class,
1612 real_type_class, complex_type_class,
1613 function_type_class, method_type_class,
1614 record_type_class, union_type_class,
1615 array_type_class, string_type_class,
1616 lang_type_class
1617 };
Mike Stump11289f42009-09-09 15:08:12 +00001618
1619 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001620 // ideal, however it is what gcc does.
1621 if (E->getNumArgs() == 0)
1622 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001623
Chris Lattner86ee2862008-10-06 06:40:35 +00001624 QualType ArgTy = E->getArg(0)->getType();
1625 if (ArgTy->isVoidType())
1626 return void_type_class;
1627 else if (ArgTy->isEnumeralType())
1628 return enumeral_type_class;
1629 else if (ArgTy->isBooleanType())
1630 return boolean_type_class;
1631 else if (ArgTy->isCharType())
1632 return string_type_class; // gcc doesn't appear to use char_type_class
1633 else if (ArgTy->isIntegerType())
1634 return integer_type_class;
1635 else if (ArgTy->isPointerType())
1636 return pointer_type_class;
1637 else if (ArgTy->isReferenceType())
1638 return reference_type_class;
1639 else if (ArgTy->isRealType())
1640 return real_type_class;
1641 else if (ArgTy->isComplexType())
1642 return complex_type_class;
1643 else if (ArgTy->isFunctionType())
1644 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001645 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001646 return record_type_class;
1647 else if (ArgTy->isUnionType())
1648 return union_type_class;
1649 else if (ArgTy->isArrayType())
1650 return array_type_class;
1651 else if (ArgTy->isUnionType())
1652 return union_type_class;
1653 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001654 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001655 return -1;
1656}
1657
John McCall95007602010-05-10 23:27:23 +00001658/// Retrieves the "underlying object type" of the given expression,
1659/// as used by __builtin_object_size.
1660QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1661 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1662 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1663 return VD->getType();
1664 } else if (isa<CompoundLiteralExpr>(E)) {
1665 return E->getType();
1666 }
1667
1668 return QualType();
1669}
1670
Peter Collingbournee9200682011-05-13 03:29:01 +00001671bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001672 // TODO: Perhaps we should let LLVM lower this?
1673 LValue Base;
1674 if (!EvaluatePointer(E->getArg(0), Base, Info))
1675 return false;
1676
1677 // If we can prove the base is null, lower to zero now.
1678 const Expr *LVBase = Base.getLValueBase();
1679 if (!LVBase) return Success(0, E);
1680
1681 QualType T = GetObjectType(LVBase);
1682 if (T.isNull() ||
1683 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001684 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001685 T->isVariablyModifiedType() ||
1686 T->isDependentType())
1687 return false;
1688
1689 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1690 CharUnits Offset = Base.getLValueOffset();
1691
1692 if (!Offset.isNegative() && Offset <= Size)
1693 Size -= Offset;
1694 else
1695 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001696 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001697}
1698
Peter Collingbournee9200682011-05-13 03:29:01 +00001699bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001700 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001701 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001702 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001703
1704 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001705 if (TryEvaluateBuiltinObjectSize(E))
1706 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001707
Eric Christopher99469702010-01-19 22:58:35 +00001708 // If evaluating the argument has side-effects we can't determine
1709 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001710 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001711 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001712 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001713 return Success(0, E);
1714 }
Mike Stump876387b2009-10-27 22:09:17 +00001715
Mike Stump722cedf2009-10-26 18:35:08 +00001716 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1717 }
1718
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001719 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001720 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001721
Anders Carlsson4c76e932008-11-24 04:21:33 +00001722 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001723 // __builtin_constant_p always has one operand: it returns true if that
1724 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001725 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001726
1727 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001728 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001729 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001730 return Success(Operand, E);
1731 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001732
1733 case Builtin::BI__builtin_expect:
1734 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001735
1736 case Builtin::BIstrlen:
1737 case Builtin::BI__builtin_strlen:
1738 // As an extension, we support strlen() and __builtin_strlen() as constant
1739 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001740 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001741 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1742 // The string literal may have embedded null characters. Find the first
1743 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001744 StringRef Str = S->getString();
1745 StringRef::size_type Pos = Str.find(0);
1746 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001747 Str = Str.substr(0, Pos);
1748
1749 return Success(Str.size(), E);
1750 }
1751
1752 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001753
1754 case Builtin::BI__atomic_is_lock_free: {
1755 APSInt SizeVal;
1756 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1757 return false;
1758
1759 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1760 // of two less than the maximum inline atomic width, we know it is
1761 // lock-free. If the size isn't a power of two, or greater than the
1762 // maximum alignment where we promote atomics, we know it is not lock-free
1763 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1764 // the answer can only be determined at runtime; for example, 16-byte
1765 // atomics have lock-free implementations on some, but not all,
1766 // x86-64 processors.
1767
1768 // Check power-of-two.
1769 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1770 if (!Size.isPowerOfTwo())
1771#if 0
1772 // FIXME: Suppress this folding until the ABI for the promotion width
1773 // settles.
1774 return Success(0, E);
1775#else
1776 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1777#endif
1778
1779#if 0
1780 // Check against promotion width.
1781 // FIXME: Suppress this folding until the ABI for the promotion width
1782 // settles.
1783 unsigned PromoteWidthBits =
1784 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1785 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1786 return Success(0, E);
1787#endif
1788
1789 // Check against inlining width.
1790 unsigned InlineWidthBits =
1791 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1792 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1793 return Success(1, E);
1794
1795 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1796 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001797 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001798}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001799
Richard Smith8b3497e2011-10-31 01:37:14 +00001800static bool HasSameBase(const LValue &A, const LValue &B) {
1801 if (!A.getLValueBase())
1802 return !B.getLValueBase();
1803 if (!B.getLValueBase())
1804 return false;
1805
1806 if (A.getLValueBase() != B.getLValueBase()) {
1807 const Decl *ADecl = GetLValueBaseDecl(A);
1808 if (!ADecl)
1809 return false;
1810 const Decl *BDecl = GetLValueBaseDecl(B);
1811 if (ADecl != BDecl)
1812 return false;
1813 }
1814
1815 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00001816 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00001817}
1818
Chris Lattnere13042c2008-07-11 19:10:17 +00001819bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001820 if (E->isAssignmentOp())
1821 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1822
John McCalle3027922010-08-25 11:45:40 +00001823 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00001824 VisitIgnoredValue(E->getLHS());
1825 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00001826 }
1827
1828 if (E->isLogicalOp()) {
1829 // These need to be handled specially because the operands aren't
1830 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001831 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001832
Richard Smith11562c52011-10-28 17:51:58 +00001833 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001834 // We were able to evaluate the LHS, see if we can get away with not
1835 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001836 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001837 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001838
Richard Smith11562c52011-10-28 17:51:58 +00001839 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001840 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001841 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001842 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001843 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001844 }
1845 } else {
Richard Smith11562c52011-10-28 17:51:58 +00001846 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001847 // We can't evaluate the LHS; however, sometimes the result
1848 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001849 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1850 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001851 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001852 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00001853 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001854
1855 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001856 }
1857 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001858 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001859
Eli Friedman5a332ea2008-11-13 06:09:17 +00001860 return false;
1861 }
1862
Anders Carlssonacc79812008-11-16 07:17:21 +00001863 QualType LHSTy = E->getLHS()->getType();
1864 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001865
1866 if (LHSTy->isAnyComplexType()) {
1867 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001868 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001869
1870 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1871 return false;
1872
1873 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1874 return false;
1875
1876 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001877 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001878 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001879 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001880 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1881
John McCalle3027922010-08-25 11:45:40 +00001882 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001883 return Success((CR_r == APFloat::cmpEqual &&
1884 CR_i == APFloat::cmpEqual), E);
1885 else {
John McCalle3027922010-08-25 11:45:40 +00001886 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001887 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001888 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001889 CR_r == APFloat::cmpLessThan ||
1890 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001891 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001892 CR_i == APFloat::cmpLessThan ||
1893 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001894 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001895 } else {
John McCalle3027922010-08-25 11:45:40 +00001896 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001897 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1898 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1899 else {
John McCalle3027922010-08-25 11:45:40 +00001900 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001901 "Invalid compex comparison.");
1902 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1903 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1904 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001905 }
1906 }
Mike Stump11289f42009-09-09 15:08:12 +00001907
Anders Carlssonacc79812008-11-16 07:17:21 +00001908 if (LHSTy->isRealFloatingType() &&
1909 RHSTy->isRealFloatingType()) {
1910 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001911
Anders Carlssonacc79812008-11-16 07:17:21 +00001912 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1913 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001914
Anders Carlssonacc79812008-11-16 07:17:21 +00001915 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1916 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001917
Anders Carlssonacc79812008-11-16 07:17:21 +00001918 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001919
Anders Carlssonacc79812008-11-16 07:17:21 +00001920 switch (E->getOpcode()) {
1921 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001922 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001923 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001924 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001925 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001926 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001927 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001928 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001929 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001930 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001931 E);
John McCalle3027922010-08-25 11:45:40 +00001932 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001933 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001934 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001935 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001936 || CR == APFloat::cmpLessThan
1937 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001938 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001939 }
Mike Stump11289f42009-09-09 15:08:12 +00001940
Eli Friedmana38da572009-04-28 19:17:36 +00001941 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00001942 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001943 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001944 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1945 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001946
John McCall45d55e42010-05-07 21:00:08 +00001947 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001948 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1949 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001950
Richard Smith8b3497e2011-10-31 01:37:14 +00001951 // Reject differing bases from the normal codepath; we special-case
1952 // comparisons to null.
1953 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00001954 // Inequalities and subtractions between unrelated pointers have
1955 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00001956 if (!E->isEqualityOp())
1957 return false;
Eli Friedmanc6be94b2011-10-31 22:28:05 +00001958 // A constant address may compare equal to the address of a symbol.
1959 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00001960 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00001961 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
1962 (!RHSValue.Base && !RHSValue.Offset.isZero()))
1963 return false;
Richard Smith83c68212011-10-31 05:11:32 +00001964 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00001965 // distinct addresses. In clang, we do not guarantee the addresses are
1966 // distinct.
Richard Smith83c68212011-10-31 05:11:32 +00001967 if (IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue))
Eli Friedman334046a2009-06-14 02:17:33 +00001968 return false;
Richard Smith83c68212011-10-31 05:11:32 +00001969 // We can't tell whether weak symbols will end up pointing to the same
1970 // object.
1971 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Eli Friedman334046a2009-06-14 02:17:33 +00001972 return false;
Richard Smith83c68212011-10-31 05:11:32 +00001973 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00001974 // (Note that clang defaults to -fmerge-all-constants, which can
1975 // lead to inconsistent results for comparisons involving the address
1976 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00001977 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00001978 }
Eli Friedman64004332009-03-23 04:38:34 +00001979
John McCalle3027922010-08-25 11:45:40 +00001980 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001981 QualType Type = E->getLHS()->getType();
1982 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001983
Ken Dyck02990832010-01-15 12:37:54 +00001984 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001985 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001986 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001987
Ken Dyck02990832010-01-15 12:37:54 +00001988 CharUnits Diff = LHSValue.getLValueOffset() -
1989 RHSValue.getLValueOffset();
1990 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001991 }
Richard Smith8b3497e2011-10-31 01:37:14 +00001992
1993 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
1994 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
1995 switch (E->getOpcode()) {
1996 default: llvm_unreachable("missing comparison operator");
1997 case BO_LT: return Success(LHSOffset < RHSOffset, E);
1998 case BO_GT: return Success(LHSOffset > RHSOffset, E);
1999 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
2000 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
2001 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
2002 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002003 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002004 }
2005 }
Douglas Gregorb90df602010-06-16 00:17:44 +00002006 if (!LHSTy->isIntegralOrEnumerationType() ||
2007 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002008 // We can't continue from here for non-integral types, and they
2009 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00002010 return false;
2011 }
2012
Anders Carlsson9c181652008-07-08 14:35:21 +00002013 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002014 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00002015 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00002016 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00002017
Richard Smith11562c52011-10-28 17:51:58 +00002018 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002019 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002020 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00002021
2022 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00002023 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00002024 CharUnits AdditionalOffset = CharUnits::fromQuantity(
2025 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00002026 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00002027 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00002028 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00002029 LHSVal.getLValueOffset() -= AdditionalOffset;
2030 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00002031 return true;
2032 }
2033
2034 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00002035 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00002036 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002037 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
2038 LHSVal.getInt().getZExtValue());
2039 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00002040 return true;
2041 }
2042
2043 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00002044 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00002045 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00002046
Richard Smith11562c52011-10-28 17:51:58 +00002047 APSInt &LHS = LHSVal.getInt();
2048 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00002049
Anders Carlsson9c181652008-07-08 14:35:21 +00002050 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002051 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002052 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00002053 case BO_Mul: return Success(LHS * RHS, E);
2054 case BO_Add: return Success(LHS + RHS, E);
2055 case BO_Sub: return Success(LHS - RHS, E);
2056 case BO_And: return Success(LHS & RHS, E);
2057 case BO_Xor: return Success(LHS ^ RHS, E);
2058 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002059 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00002060 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002061 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002062 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002063 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00002064 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002065 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002066 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002067 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00002068 // During constant-folding, a negative shift is an opposite shift.
2069 if (RHS.isSigned() && RHS.isNegative()) {
2070 RHS = -RHS;
2071 goto shift_right;
2072 }
2073
2074 shift_left:
2075 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00002076 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2077 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002078 }
John McCalle3027922010-08-25 11:45:40 +00002079 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00002080 // During constant-folding, a negative shift is an opposite shift.
2081 if (RHS.isSigned() && RHS.isNegative()) {
2082 RHS = -RHS;
2083 goto shift_left;
2084 }
2085
2086 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00002087 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00002088 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2089 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002090 }
Mike Stump11289f42009-09-09 15:08:12 +00002091
Richard Smith11562c52011-10-28 17:51:58 +00002092 case BO_LT: return Success(LHS < RHS, E);
2093 case BO_GT: return Success(LHS > RHS, E);
2094 case BO_LE: return Success(LHS <= RHS, E);
2095 case BO_GE: return Success(LHS >= RHS, E);
2096 case BO_EQ: return Success(LHS == RHS, E);
2097 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00002098 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002099}
2100
Ken Dyck160146e2010-01-27 17:10:57 +00002101CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002102 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2103 // the result is the size of the referenced type."
2104 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2105 // result shall be the alignment of the referenced type."
2106 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2107 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00002108
2109 // __alignof is defined to return the preferred alignment.
2110 return Info.Ctx.toCharUnitsFromBits(
2111 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00002112}
2113
Ken Dyck160146e2010-01-27 17:10:57 +00002114CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00002115 E = E->IgnoreParens();
2116
2117 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00002118 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00002119 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002120 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2121 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00002122
Chris Lattner68061312009-01-24 21:53:27 +00002123 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002124 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2125 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00002126
Chris Lattner24aeeab2009-01-24 21:09:06 +00002127 return GetAlignOfType(E->getType());
2128}
2129
2130
Peter Collingbournee190dee2011-03-11 19:24:49 +00002131/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2132/// a result as the expression's type.
2133bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2134 const UnaryExprOrTypeTraitExpr *E) {
2135 switch(E->getKind()) {
2136 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00002137 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00002138 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002139 else
Ken Dyckdbc01912011-03-11 02:13:43 +00002140 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002141 }
Eli Friedman64004332009-03-23 04:38:34 +00002142
Peter Collingbournee190dee2011-03-11 19:24:49 +00002143 case UETT_VecStep: {
2144 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00002145
Peter Collingbournee190dee2011-03-11 19:24:49 +00002146 if (Ty->isVectorType()) {
2147 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00002148
Peter Collingbournee190dee2011-03-11 19:24:49 +00002149 // The vec_step built-in functions that take a 3-component
2150 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2151 if (n == 3)
2152 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002153
Peter Collingbournee190dee2011-03-11 19:24:49 +00002154 return Success(n, E);
2155 } else
2156 return Success(1, E);
2157 }
2158
2159 case UETT_SizeOf: {
2160 QualType SrcTy = E->getTypeOfArgument();
2161 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2162 // the result is the size of the referenced type."
2163 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2164 // result shall be the alignment of the referenced type."
2165 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2166 SrcTy = Ref->getPointeeType();
2167
2168 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2169 // extension.
2170 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
2171 return Success(1, E);
2172
2173 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2174 if (!SrcTy->isConstantSizeType())
2175 return false;
2176
2177 // Get information about the size.
2178 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
2179 }
2180 }
2181
2182 llvm_unreachable("unknown expr/type trait");
2183 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002184}
2185
Peter Collingbournee9200682011-05-13 03:29:01 +00002186bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00002187 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00002188 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00002189 if (n == 0)
2190 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002191 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00002192 for (unsigned i = 0; i != n; ++i) {
2193 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
2194 switch (ON.getKind()) {
2195 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00002196 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00002197 APSInt IdxResult;
2198 if (!EvaluateInteger(Idx, IdxResult, Info))
2199 return false;
2200 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
2201 if (!AT)
2202 return false;
2203 CurrentType = AT->getElementType();
2204 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
2205 Result += IdxResult.getSExtValue() * ElementSize;
2206 break;
2207 }
2208
2209 case OffsetOfExpr::OffsetOfNode::Field: {
2210 FieldDecl *MemberDecl = ON.getField();
2211 const RecordType *RT = CurrentType->getAs<RecordType>();
2212 if (!RT)
2213 return false;
2214 RecordDecl *RD = RT->getDecl();
2215 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00002216 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00002217 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002218 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00002219 CurrentType = MemberDecl->getType().getNonReferenceType();
2220 break;
2221 }
2222
2223 case OffsetOfExpr::OffsetOfNode::Identifier:
2224 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00002225 return false;
2226
2227 case OffsetOfExpr::OffsetOfNode::Base: {
2228 CXXBaseSpecifier *BaseSpec = ON.getBase();
2229 if (BaseSpec->isVirtual())
2230 return false;
2231
2232 // Find the layout of the class whose base we are looking into.
2233 const RecordType *RT = CurrentType->getAs<RecordType>();
2234 if (!RT)
2235 return false;
2236 RecordDecl *RD = RT->getDecl();
2237 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
2238
2239 // Find the base class itself.
2240 CurrentType = BaseSpec->getType();
2241 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2242 if (!BaseRT)
2243 return false;
2244
2245 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00002246 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00002247 break;
2248 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002249 }
2250 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002251 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00002252}
2253
Chris Lattnere13042c2008-07-11 19:10:17 +00002254bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002255 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002256 // LNot's operand isn't necessarily an integer, so we handle it specially.
2257 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00002258 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00002259 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002260 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00002261 }
2262
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002263 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00002264 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002265 return false;
2266
Richard Smith11562c52011-10-28 17:51:58 +00002267 // Get the operand value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002268 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00002269 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00002270 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002271
Chris Lattnerf09ad162008-07-11 22:15:16 +00002272 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002273 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00002274 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2275 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002276 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00002277 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00002278 // FIXME: Should extension allow i-c-e extension expressions in its scope?
2279 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00002280 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002281 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00002282 // The result is just the value.
2283 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002284 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00002285 if (!Val.isInt()) return false;
2286 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00002287 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00002288 if (!Val.isInt()) return false;
2289 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00002290 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002291}
Mike Stump11289f42009-09-09 15:08:12 +00002292
Chris Lattner477c4be2008-07-12 01:15:53 +00002293/// HandleCast - This is used to evaluate implicit or explicit casts where the
2294/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00002295bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
2296 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002297 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00002298 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002299
Eli Friedmanc757de22011-03-25 00:43:55 +00002300 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00002301 case CK_BaseToDerived:
2302 case CK_DerivedToBase:
2303 case CK_UncheckedDerivedToBase:
2304 case CK_Dynamic:
2305 case CK_ToUnion:
2306 case CK_ArrayToPointerDecay:
2307 case CK_FunctionToPointerDecay:
2308 case CK_NullToPointer:
2309 case CK_NullToMemberPointer:
2310 case CK_BaseToDerivedMemberPointer:
2311 case CK_DerivedToBaseMemberPointer:
2312 case CK_ConstructorConversion:
2313 case CK_IntegralToPointer:
2314 case CK_ToVoid:
2315 case CK_VectorSplat:
2316 case CK_IntegralToFloating:
2317 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002318 case CK_CPointerToObjCPointerCast:
2319 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002320 case CK_AnyPointerToBlockPointerCast:
2321 case CK_ObjCObjectLValueCast:
2322 case CK_FloatingRealToComplex:
2323 case CK_FloatingComplexToReal:
2324 case CK_FloatingComplexCast:
2325 case CK_FloatingComplexToIntegralComplex:
2326 case CK_IntegralRealToComplex:
2327 case CK_IntegralComplexCast:
2328 case CK_IntegralComplexToFloatingComplex:
2329 llvm_unreachable("invalid cast kind for integral value");
2330
Eli Friedman9faf2f92011-03-25 19:07:11 +00002331 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002332 case CK_Dependent:
2333 case CK_GetObjCProperty:
2334 case CK_LValueBitCast:
2335 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00002336 case CK_ARCProduceObject:
2337 case CK_ARCConsumeObject:
2338 case CK_ARCReclaimReturnedObject:
2339 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00002340 return false;
2341
2342 case CK_LValueToRValue:
2343 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002344 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002345
2346 case CK_MemberPointerToBoolean:
2347 case CK_PointerToBoolean:
2348 case CK_IntegralToBoolean:
2349 case CK_FloatingToBoolean:
2350 case CK_FloatingComplexToBoolean:
2351 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002352 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002353 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002354 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002355 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002356 }
2357
Eli Friedmanc757de22011-03-25 00:43:55 +00002358 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00002359 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00002360 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002361
Eli Friedman742421e2009-02-20 01:15:07 +00002362 if (!Result.isInt()) {
2363 // Only allow casts of lvalues if they are lossless.
2364 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2365 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002366
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002367 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002368 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00002369 }
Mike Stump11289f42009-09-09 15:08:12 +00002370
Eli Friedmanc757de22011-03-25 00:43:55 +00002371 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00002372 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00002373 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00002374 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002375
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002376 if (LV.getLValueBase()) {
2377 // Only allow based lvalue casts if they are lossless.
2378 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2379 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002380
John McCall45d55e42010-05-07 21:00:08 +00002381 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002382 return true;
2383 }
2384
Ken Dyck02990832010-01-15 12:37:54 +00002385 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2386 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002387 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002388 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002389
Eli Friedmanc757de22011-03-25 00:43:55 +00002390 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00002391 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002392 if (!EvaluateComplex(SubExpr, C, Info))
2393 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00002394 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002395 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00002396
Eli Friedmanc757de22011-03-25 00:43:55 +00002397 case CK_FloatingToIntegral: {
2398 APFloat F(0.0);
2399 if (!EvaluateFloat(SubExpr, F, Info))
2400 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00002401
Eli Friedmanc757de22011-03-25 00:43:55 +00002402 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2403 }
2404 }
Mike Stump11289f42009-09-09 15:08:12 +00002405
Eli Friedmanc757de22011-03-25 00:43:55 +00002406 llvm_unreachable("unknown cast resulting in integral value");
2407 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002408}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002409
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002410bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2411 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002412 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002413 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2414 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2415 return Success(LV.getComplexIntReal(), E);
2416 }
2417
2418 return Visit(E->getSubExpr());
2419}
2420
Eli Friedman4e7a2412009-02-27 04:45:43 +00002421bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002422 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002423 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002424 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2425 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2426 return Success(LV.getComplexIntImag(), E);
2427 }
2428
Richard Smith4a678122011-10-24 18:44:57 +00002429 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00002430 return Success(0, E);
2431}
2432
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002433bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2434 return Success(E->getPackLength(), E);
2435}
2436
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002437bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2438 return Success(E->getValue(), E);
2439}
2440
Chris Lattner05706e882008-07-11 18:11:29 +00002441//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002442// Float Evaluation
2443//===----------------------------------------------------------------------===//
2444
2445namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002446class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002447 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002448 APFloat &Result;
2449public:
2450 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002451 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002452
Richard Smith0b0a0b62011-10-29 20:57:55 +00002453 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002454 Result = V.getFloat();
2455 return true;
2456 }
2457 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002458 return false;
2459 }
2460
Richard Smith4ce706a2011-10-11 21:43:33 +00002461 bool ValueInitialization(const Expr *E) {
2462 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2463 return true;
2464 }
2465
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002466 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002467
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002468 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002469 bool VisitBinaryOperator(const BinaryOperator *E);
2470 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002471 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002472
John McCallb1fb0d32010-05-07 22:08:54 +00002473 bool VisitUnaryReal(const UnaryOperator *E);
2474 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002475
John McCallb1fb0d32010-05-07 22:08:54 +00002476 // FIXME: Missing: array subscript of vector, member of vector,
2477 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002478};
2479} // end anonymous namespace
2480
2481static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002482 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002483 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002484}
2485
Jay Foad39c79802011-01-12 09:06:06 +00002486static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002487 QualType ResultTy,
2488 const Expr *Arg,
2489 bool SNaN,
2490 llvm::APFloat &Result) {
2491 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2492 if (!S) return false;
2493
2494 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2495
2496 llvm::APInt fill;
2497
2498 // Treat empty strings as if they were zero.
2499 if (S->getString().empty())
2500 fill = llvm::APInt(32, 0);
2501 else if (S->getString().getAsInteger(0, fill))
2502 return false;
2503
2504 if (SNaN)
2505 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2506 else
2507 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2508 return true;
2509}
2510
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002511bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002512 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002513 default:
2514 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2515
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002516 case Builtin::BI__builtin_huge_val:
2517 case Builtin::BI__builtin_huge_valf:
2518 case Builtin::BI__builtin_huge_vall:
2519 case Builtin::BI__builtin_inf:
2520 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002521 case Builtin::BI__builtin_infl: {
2522 const llvm::fltSemantics &Sem =
2523 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002524 Result = llvm::APFloat::getInf(Sem);
2525 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002526 }
Mike Stump11289f42009-09-09 15:08:12 +00002527
John McCall16291492010-02-28 13:00:19 +00002528 case Builtin::BI__builtin_nans:
2529 case Builtin::BI__builtin_nansf:
2530 case Builtin::BI__builtin_nansl:
2531 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2532 true, Result);
2533
Chris Lattner0b7282e2008-10-06 06:31:58 +00002534 case Builtin::BI__builtin_nan:
2535 case Builtin::BI__builtin_nanf:
2536 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002537 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002538 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002539 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2540 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002541
2542 case Builtin::BI__builtin_fabs:
2543 case Builtin::BI__builtin_fabsf:
2544 case Builtin::BI__builtin_fabsl:
2545 if (!EvaluateFloat(E->getArg(0), Result, Info))
2546 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002547
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002548 if (Result.isNegative())
2549 Result.changeSign();
2550 return true;
2551
Mike Stump11289f42009-09-09 15:08:12 +00002552 case Builtin::BI__builtin_copysign:
2553 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002554 case Builtin::BI__builtin_copysignl: {
2555 APFloat RHS(0.);
2556 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2557 !EvaluateFloat(E->getArg(1), RHS, Info))
2558 return false;
2559 Result.copySign(RHS);
2560 return true;
2561 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002562 }
2563}
2564
John McCallb1fb0d32010-05-07 22:08:54 +00002565bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002566 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2567 ComplexValue CV;
2568 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2569 return false;
2570 Result = CV.FloatReal;
2571 return true;
2572 }
2573
2574 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002575}
2576
2577bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002578 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2579 ComplexValue CV;
2580 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2581 return false;
2582 Result = CV.FloatImag;
2583 return true;
2584 }
2585
Richard Smith4a678122011-10-24 18:44:57 +00002586 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00002587 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2588 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002589 return true;
2590}
2591
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002592bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002593 switch (E->getOpcode()) {
2594 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002595 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00002596 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00002597 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00002598 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2599 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002600 Result.changeSign();
2601 return true;
2602 }
2603}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002604
Eli Friedman24c01542008-08-22 00:06:13 +00002605bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002606 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002607 VisitIgnoredValue(E->getLHS());
2608 return Visit(E->getRHS());
Eli Friedman141fbf32009-11-16 04:25:37 +00002609 }
2610
Richard Smith472d4952011-10-28 23:26:52 +00002611 // We can't evaluate pointer-to-member operations or assignments.
2612 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlssona5df61a2010-10-31 01:21:47 +00002613 return false;
2614
Eli Friedman24c01542008-08-22 00:06:13 +00002615 // FIXME: Diagnostics? I really don't understand how the warnings
2616 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002617 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002618 if (!EvaluateFloat(E->getLHS(), Result, Info))
2619 return false;
2620 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2621 return false;
2622
2623 switch (E->getOpcode()) {
2624 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002625 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002626 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2627 return true;
John McCalle3027922010-08-25 11:45:40 +00002628 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002629 Result.add(RHS, APFloat::rmNearestTiesToEven);
2630 return true;
John McCalle3027922010-08-25 11:45:40 +00002631 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002632 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2633 return true;
John McCalle3027922010-08-25 11:45:40 +00002634 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002635 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2636 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002637 }
2638}
2639
2640bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2641 Result = E->getValue();
2642 return true;
2643}
2644
Peter Collingbournee9200682011-05-13 03:29:01 +00002645bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2646 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002647
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002648 switch (E->getCastKind()) {
2649 default:
Richard Smith11562c52011-10-28 17:51:58 +00002650 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002651
2652 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002653 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002654 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002655 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002656 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002657 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002658 return true;
2659 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002660
2661 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002662 if (!Visit(SubExpr))
2663 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002664 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2665 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002666 return true;
2667 }
John McCalld7646252010-11-14 08:17:51 +00002668
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002669 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002670 ComplexValue V;
2671 if (!EvaluateComplex(SubExpr, V, Info))
2672 return false;
2673 Result = V.getComplexFloatReal();
2674 return true;
2675 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002676 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002677
2678 return false;
2679}
2680
Eli Friedman24c01542008-08-22 00:06:13 +00002681//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002682// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002683//===----------------------------------------------------------------------===//
2684
2685namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002686class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002687 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002688 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002689
Anders Carlsson537969c2008-11-16 20:27:53 +00002690public:
John McCall93d91dc2010-05-07 17:22:02 +00002691 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002692 : ExprEvaluatorBaseTy(info), Result(Result) {}
2693
Richard Smith0b0a0b62011-10-29 20:57:55 +00002694 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002695 Result.setFrom(V);
2696 return true;
2697 }
2698 bool Error(const Expr *E) {
2699 return false;
2700 }
Mike Stump11289f42009-09-09 15:08:12 +00002701
Anders Carlsson537969c2008-11-16 20:27:53 +00002702 //===--------------------------------------------------------------------===//
2703 // Visitor Methods
2704 //===--------------------------------------------------------------------===//
2705
Peter Collingbournee9200682011-05-13 03:29:01 +00002706 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002707
Peter Collingbournee9200682011-05-13 03:29:01 +00002708 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002709
John McCall93d91dc2010-05-07 17:22:02 +00002710 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002711 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002712 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002713};
2714} // end anonymous namespace
2715
John McCall93d91dc2010-05-07 17:22:02 +00002716static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2717 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002718 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002719 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002720}
2721
Peter Collingbournee9200682011-05-13 03:29:01 +00002722bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2723 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002724
2725 if (SubExpr->getType()->isRealFloatingType()) {
2726 Result.makeComplexFloat();
2727 APFloat &Imag = Result.FloatImag;
2728 if (!EvaluateFloat(SubExpr, Imag, Info))
2729 return false;
2730
2731 Result.FloatReal = APFloat(Imag.getSemantics());
2732 return true;
2733 } else {
2734 assert(SubExpr->getType()->isIntegerType() &&
2735 "Unexpected imaginary literal.");
2736
2737 Result.makeComplexInt();
2738 APSInt &Imag = Result.IntImag;
2739 if (!EvaluateInteger(SubExpr, Imag, Info))
2740 return false;
2741
2742 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2743 return true;
2744 }
2745}
2746
Peter Collingbournee9200682011-05-13 03:29:01 +00002747bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002748
John McCallfcef3cf2010-12-14 17:51:41 +00002749 switch (E->getCastKind()) {
2750 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002751 case CK_BaseToDerived:
2752 case CK_DerivedToBase:
2753 case CK_UncheckedDerivedToBase:
2754 case CK_Dynamic:
2755 case CK_ToUnion:
2756 case CK_ArrayToPointerDecay:
2757 case CK_FunctionToPointerDecay:
2758 case CK_NullToPointer:
2759 case CK_NullToMemberPointer:
2760 case CK_BaseToDerivedMemberPointer:
2761 case CK_DerivedToBaseMemberPointer:
2762 case CK_MemberPointerToBoolean:
2763 case CK_ConstructorConversion:
2764 case CK_IntegralToPointer:
2765 case CK_PointerToIntegral:
2766 case CK_PointerToBoolean:
2767 case CK_ToVoid:
2768 case CK_VectorSplat:
2769 case CK_IntegralCast:
2770 case CK_IntegralToBoolean:
2771 case CK_IntegralToFloating:
2772 case CK_FloatingToIntegral:
2773 case CK_FloatingToBoolean:
2774 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002775 case CK_CPointerToObjCPointerCast:
2776 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002777 case CK_AnyPointerToBlockPointerCast:
2778 case CK_ObjCObjectLValueCast:
2779 case CK_FloatingComplexToReal:
2780 case CK_FloatingComplexToBoolean:
2781 case CK_IntegralComplexToReal:
2782 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002783 case CK_ARCProduceObject:
2784 case CK_ARCConsumeObject:
2785 case CK_ARCReclaimReturnedObject:
2786 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002787 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002788
John McCallfcef3cf2010-12-14 17:51:41 +00002789 case CK_LValueToRValue:
2790 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002791 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00002792
2793 case CK_Dependent:
2794 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002795 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002796 case CK_UserDefinedConversion:
2797 return false;
2798
2799 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002800 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002801 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002802 return false;
2803
John McCallfcef3cf2010-12-14 17:51:41 +00002804 Result.makeComplexFloat();
2805 Result.FloatImag = APFloat(Real.getSemantics());
2806 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002807 }
2808
John McCallfcef3cf2010-12-14 17:51:41 +00002809 case CK_FloatingComplexCast: {
2810 if (!Visit(E->getSubExpr()))
2811 return false;
2812
2813 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2814 QualType From
2815 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2816
2817 Result.FloatReal
2818 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2819 Result.FloatImag
2820 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2821 return true;
2822 }
2823
2824 case CK_FloatingComplexToIntegralComplex: {
2825 if (!Visit(E->getSubExpr()))
2826 return false;
2827
2828 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2829 QualType From
2830 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2831 Result.makeComplexInt();
2832 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2833 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2834 return true;
2835 }
2836
2837 case CK_IntegralRealToComplex: {
2838 APSInt &Real = Result.IntReal;
2839 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2840 return false;
2841
2842 Result.makeComplexInt();
2843 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2844 return true;
2845 }
2846
2847 case CK_IntegralComplexCast: {
2848 if (!Visit(E->getSubExpr()))
2849 return false;
2850
2851 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2852 QualType From
2853 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2854
2855 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2856 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2857 return true;
2858 }
2859
2860 case CK_IntegralComplexToFloatingComplex: {
2861 if (!Visit(E->getSubExpr()))
2862 return false;
2863
2864 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2865 QualType From
2866 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2867 Result.makeComplexFloat();
2868 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2869 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2870 return true;
2871 }
2872 }
2873
2874 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002875 return false;
2876}
2877
John McCall93d91dc2010-05-07 17:22:02 +00002878bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002879 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002880 VisitIgnoredValue(E->getLHS());
2881 return Visit(E->getRHS());
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002882 }
John McCall93d91dc2010-05-07 17:22:02 +00002883 if (!Visit(E->getLHS()))
2884 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002885
John McCall93d91dc2010-05-07 17:22:02 +00002886 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002887 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002888 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002889
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002890 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2891 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002892 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002893 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002894 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002895 if (Result.isComplexFloat()) {
2896 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2897 APFloat::rmNearestTiesToEven);
2898 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2899 APFloat::rmNearestTiesToEven);
2900 } else {
2901 Result.getComplexIntReal() += RHS.getComplexIntReal();
2902 Result.getComplexIntImag() += RHS.getComplexIntImag();
2903 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002904 break;
John McCalle3027922010-08-25 11:45:40 +00002905 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002906 if (Result.isComplexFloat()) {
2907 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2908 APFloat::rmNearestTiesToEven);
2909 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2910 APFloat::rmNearestTiesToEven);
2911 } else {
2912 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2913 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2914 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002915 break;
John McCalle3027922010-08-25 11:45:40 +00002916 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002917 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002918 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002919 APFloat &LHS_r = LHS.getComplexFloatReal();
2920 APFloat &LHS_i = LHS.getComplexFloatImag();
2921 APFloat &RHS_r = RHS.getComplexFloatReal();
2922 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002923
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002924 APFloat Tmp = LHS_r;
2925 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2926 Result.getComplexFloatReal() = Tmp;
2927 Tmp = LHS_i;
2928 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2929 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2930
2931 Tmp = LHS_r;
2932 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2933 Result.getComplexFloatImag() = Tmp;
2934 Tmp = LHS_i;
2935 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2936 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2937 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002938 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002939 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002940 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2941 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002942 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002943 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2944 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2945 }
2946 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002947 case BO_Div:
2948 if (Result.isComplexFloat()) {
2949 ComplexValue LHS = Result;
2950 APFloat &LHS_r = LHS.getComplexFloatReal();
2951 APFloat &LHS_i = LHS.getComplexFloatImag();
2952 APFloat &RHS_r = RHS.getComplexFloatReal();
2953 APFloat &RHS_i = RHS.getComplexFloatImag();
2954 APFloat &Res_r = Result.getComplexFloatReal();
2955 APFloat &Res_i = Result.getComplexFloatImag();
2956
2957 APFloat Den = RHS_r;
2958 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2959 APFloat Tmp = RHS_i;
2960 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2961 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2962
2963 Res_r = LHS_r;
2964 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2965 Tmp = LHS_i;
2966 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2967 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2968 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2969
2970 Res_i = LHS_i;
2971 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2972 Tmp = LHS_r;
2973 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2974 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2975 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2976 } else {
2977 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2978 // FIXME: what about diagnostics?
2979 return false;
2980 }
2981 ComplexValue LHS = Result;
2982 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2983 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2984 Result.getComplexIntReal() =
2985 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2986 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2987 Result.getComplexIntImag() =
2988 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2989 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2990 }
2991 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002992 }
2993
John McCall93d91dc2010-05-07 17:22:02 +00002994 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002995}
2996
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002997bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2998 // Get the operand value into 'Result'.
2999 if (!Visit(E->getSubExpr()))
3000 return false;
3001
3002 switch (E->getOpcode()) {
3003 default:
3004 // FIXME: what about diagnostics?
3005 return false;
3006 case UO_Extension:
3007 return true;
3008 case UO_Plus:
3009 // The result is always just the subexpr.
3010 return true;
3011 case UO_Minus:
3012 if (Result.isComplexFloat()) {
3013 Result.getComplexFloatReal().changeSign();
3014 Result.getComplexFloatImag().changeSign();
3015 }
3016 else {
3017 Result.getComplexIntReal() = -Result.getComplexIntReal();
3018 Result.getComplexIntImag() = -Result.getComplexIntImag();
3019 }
3020 return true;
3021 case UO_Not:
3022 if (Result.isComplexFloat())
3023 Result.getComplexFloatImag().changeSign();
3024 else
3025 Result.getComplexIntImag() = -Result.getComplexIntImag();
3026 return true;
3027 }
3028}
3029
Anders Carlsson537969c2008-11-16 20:27:53 +00003030//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00003031// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00003032//===----------------------------------------------------------------------===//
3033
Richard Smith0b0a0b62011-10-29 20:57:55 +00003034static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003035 // In C, function designators are not lvalues, but we evaluate them as if they
3036 // are.
3037 if (E->isGLValue() || E->getType()->isFunctionType()) {
3038 LValue LV;
3039 if (!EvaluateLValue(E, LV, Info))
3040 return false;
3041 LV.moveInto(Result);
3042 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003043 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003044 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003045 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003046 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003047 return false;
John McCall45d55e42010-05-07 21:00:08 +00003048 } else if (E->getType()->hasPointerRepresentation()) {
3049 LValue LV;
3050 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003051 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003052 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00003053 } else if (E->getType()->isRealFloatingType()) {
3054 llvm::APFloat F(0.0);
3055 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003056 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003057 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00003058 } else if (E->getType()->isAnyComplexType()) {
3059 ComplexValue C;
3060 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003061 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003062 C.moveInto(Result);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003063 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00003064 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003065
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00003066 return true;
3067}
3068
Richard Smith11562c52011-10-28 17:51:58 +00003069
Richard Smith7b553f12011-10-29 00:50:52 +00003070/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00003071/// any crazy technique (that has nothing to do with language standards) that
3072/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00003073/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3074/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00003075bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
John McCallc07a0c72011-02-17 10:25:35 +00003076 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00003077
Richard Smith0b0a0b62011-10-29 20:57:55 +00003078 CCValue Value;
3079 if (!::Evaluate(Value, Info, this))
Richard Smith11562c52011-10-28 17:51:58 +00003080 return false;
3081
3082 if (isGLValue()) {
3083 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003084 LV.setFrom(Value);
3085 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3086 return false;
Richard Smith11562c52011-10-28 17:51:58 +00003087 }
3088
Richard Smith0b0a0b62011-10-29 20:57:55 +00003089 // Check this core constant expression is a constant expression, and if so,
3090 // slice it down to one.
3091 if (!CheckConstantExpression(Value))
3092 return false;
3093 Result.Val = Value;
3094 return true;
John McCallc07a0c72011-02-17 10:25:35 +00003095}
3096
Jay Foad39c79802011-01-12 09:06:06 +00003097bool Expr::EvaluateAsBooleanCondition(bool &Result,
3098 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003099 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00003100 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00003101 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00003102 Result);
John McCall1be1c632010-01-05 23:42:56 +00003103}
3104
Richard Smithcaf33902011-10-10 18:28:20 +00003105bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003106 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003107 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smith11562c52011-10-28 17:51:58 +00003108 !ExprResult.Val.isInt()) {
3109 return false;
3110 }
3111 Result = ExprResult.Val.getInt();
3112 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00003113}
3114
Jay Foad39c79802011-01-12 09:06:06 +00003115bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00003116 EvalInfo Info(Ctx, Result);
3117
John McCall45d55e42010-05-07 21:00:08 +00003118 LValue LV;
Richard Smith11562c52011-10-28 17:51:58 +00003119 if (EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003120 IsGlobalLValue(LV.Base)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003121 Result.Val = APValue(LV.Base, LV.Offset);
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003122 return true;
3123 }
3124 return false;
3125}
3126
Jay Foad39c79802011-01-12 09:06:06 +00003127bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
3128 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003129 EvalInfo Info(Ctx, Result);
3130
3131 LValue LV;
Richard Smithfec09922011-11-01 16:57:24 +00003132 if (EvaluateLValue(this, LV, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003133 Result.Val = APValue(LV.Base, LV.Offset);
John McCall45d55e42010-05-07 21:00:08 +00003134 return true;
3135 }
3136 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00003137}
3138
Richard Smith7b553f12011-10-29 00:50:52 +00003139/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3140/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00003141bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00003142 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00003143 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00003144}
Anders Carlsson59689ed2008-11-22 21:04:56 +00003145
Jay Foad39c79802011-01-12 09:06:06 +00003146bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00003147 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003148}
3149
Richard Smithcaf33902011-10-10 18:28:20 +00003150APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003151 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003152 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00003153 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00003154 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003155 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00003156
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003157 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00003158}
John McCall864e3962010-05-07 05:32:02 +00003159
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003160 bool Expr::EvalResult::isGlobalLValue() const {
3161 assert(Val.isLValue());
3162 return IsGlobalLValue(Val.getLValueBase());
3163 }
3164
3165
John McCall864e3962010-05-07 05:32:02 +00003166/// isIntegerConstantExpr - this recursive routine will test if an expression is
3167/// an integer constant expression.
3168
3169/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
3170/// comma, etc
3171///
3172/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
3173/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
3174/// cast+dereference.
3175
3176// CheckICE - This function does the fundamental ICE checking: the returned
3177// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
3178// Note that to reduce code duplication, this helper does no evaluation
3179// itself; the caller checks whether the expression is evaluatable, and
3180// in the rare cases where CheckICE actually cares about the evaluated
3181// value, it calls into Evalute.
3182//
3183// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00003184// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00003185// 1: This expression is not an ICE, but if it isn't evaluated, it's
3186// a legal subexpression for an ICE. This return value is used to handle
3187// the comma operator in C99 mode.
3188// 2: This expression is not an ICE, and is not a legal subexpression for one.
3189
Dan Gohman28ade552010-07-26 21:25:24 +00003190namespace {
3191
John McCall864e3962010-05-07 05:32:02 +00003192struct ICEDiag {
3193 unsigned Val;
3194 SourceLocation Loc;
3195
3196 public:
3197 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
3198 ICEDiag() : Val(0) {}
3199};
3200
Dan Gohman28ade552010-07-26 21:25:24 +00003201}
3202
3203static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00003204
3205static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
3206 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003207 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003208 !EVResult.Val.isInt()) {
3209 return ICEDiag(2, E->getLocStart());
3210 }
3211 return NoDiag();
3212}
3213
3214static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
3215 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00003216 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00003217 return ICEDiag(2, E->getLocStart());
3218 }
3219
3220 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00003221#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00003222#define STMT(Node, Base) case Expr::Node##Class:
3223#define EXPR(Node, Base)
3224#include "clang/AST/StmtNodes.inc"
3225 case Expr::PredefinedExprClass:
3226 case Expr::FloatingLiteralClass:
3227 case Expr::ImaginaryLiteralClass:
3228 case Expr::StringLiteralClass:
3229 case Expr::ArraySubscriptExprClass:
3230 case Expr::MemberExprClass:
3231 case Expr::CompoundAssignOperatorClass:
3232 case Expr::CompoundLiteralExprClass:
3233 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00003234 case Expr::DesignatedInitExprClass:
3235 case Expr::ImplicitValueInitExprClass:
3236 case Expr::ParenListExprClass:
3237 case Expr::VAArgExprClass:
3238 case Expr::AddrLabelExprClass:
3239 case Expr::StmtExprClass:
3240 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00003241 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00003242 case Expr::CXXDynamicCastExprClass:
3243 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00003244 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00003245 case Expr::CXXNullPtrLiteralExprClass:
3246 case Expr::CXXThisExprClass:
3247 case Expr::CXXThrowExprClass:
3248 case Expr::CXXNewExprClass:
3249 case Expr::CXXDeleteExprClass:
3250 case Expr::CXXPseudoDestructorExprClass:
3251 case Expr::UnresolvedLookupExprClass:
3252 case Expr::DependentScopeDeclRefExprClass:
3253 case Expr::CXXConstructExprClass:
3254 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00003255 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00003256 case Expr::CXXTemporaryObjectExprClass:
3257 case Expr::CXXUnresolvedConstructExprClass:
3258 case Expr::CXXDependentScopeMemberExprClass:
3259 case Expr::UnresolvedMemberExprClass:
3260 case Expr::ObjCStringLiteralClass:
3261 case Expr::ObjCEncodeExprClass:
3262 case Expr::ObjCMessageExprClass:
3263 case Expr::ObjCSelectorExprClass:
3264 case Expr::ObjCProtocolExprClass:
3265 case Expr::ObjCIvarRefExprClass:
3266 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00003267 case Expr::ObjCIsaExprClass:
3268 case Expr::ShuffleVectorExprClass:
3269 case Expr::BlockExprClass:
3270 case Expr::BlockDeclRefExprClass:
3271 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00003272 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00003273 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00003274 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00003275 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00003276 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00003277 case Expr::MaterializeTemporaryExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003278 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00003279 return ICEDiag(2, E->getLocStart());
3280
Sebastian Redl12757ab2011-09-24 17:48:14 +00003281 case Expr::InitListExprClass:
3282 if (Ctx.getLangOptions().CPlusPlus0x) {
3283 const InitListExpr *ILE = cast<InitListExpr>(E);
3284 if (ILE->getNumInits() == 0)
3285 return NoDiag();
3286 if (ILE->getNumInits() == 1)
3287 return CheckICE(ILE->getInit(0), Ctx);
3288 // Fall through for more than 1 expression.
3289 }
3290 return ICEDiag(2, E->getLocStart());
3291
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003292 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00003293 case Expr::GNUNullExprClass:
3294 // GCC considers the GNU __null value to be an integral constant expression.
3295 return NoDiag();
3296
John McCall7c454bb2011-07-15 05:09:51 +00003297 case Expr::SubstNonTypeTemplateParmExprClass:
3298 return
3299 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
3300
John McCall864e3962010-05-07 05:32:02 +00003301 case Expr::ParenExprClass:
3302 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00003303 case Expr::GenericSelectionExprClass:
3304 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003305 case Expr::IntegerLiteralClass:
3306 case Expr::CharacterLiteralClass:
3307 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00003308 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00003309 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003310 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00003311 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00003312 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003313 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00003314 return NoDiag();
3315 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00003316 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00003317 // C99 6.6/3 allows function calls within unevaluated subexpressions of
3318 // constant expressions, but they can never be ICEs because an ICE cannot
3319 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00003320 const CallExpr *CE = cast<CallExpr>(E);
3321 if (CE->isBuiltinCall(Ctx))
3322 return CheckEvalInICE(E, Ctx);
3323 return ICEDiag(2, E->getLocStart());
3324 }
3325 case Expr::DeclRefExprClass:
3326 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
3327 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00003328 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00003329 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3330
3331 // Parameter variables are never constants. Without this check,
3332 // getAnyInitializer() can find a default argument, which leads
3333 // to chaos.
3334 if (isa<ParmVarDecl>(D))
3335 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3336
3337 // C++ 7.1.5.1p2
3338 // A variable of non-volatile const-qualified integral or enumeration
3339 // type initialized by an ICE can be used in ICEs.
3340 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCall864e3962010-05-07 05:32:02 +00003341 // Look for a declaration of this variable that has an initializer.
3342 const VarDecl *ID = 0;
3343 const Expr *Init = Dcl->getAnyInitializer(ID);
3344 if (Init) {
3345 if (ID->isInitKnownICE()) {
3346 // We have already checked whether this subexpression is an
3347 // integral constant expression.
3348 if (ID->isInitICE())
3349 return NoDiag();
3350 else
3351 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3352 }
3353
3354 // It's an ICE whether or not the definition we found is
3355 // out-of-line. See DR 721 and the discussion in Clang PR
3356 // 6206 for details.
3357
3358 if (Dcl->isCheckingICE()) {
3359 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3360 }
3361
3362 Dcl->setCheckingICE();
3363 ICEDiag Result = CheckICE(Init, Ctx);
3364 // Cache the result of the ICE test.
3365 Dcl->setInitKnownICE(Result.Val == 0);
3366 return Result;
3367 }
3368 }
3369 }
3370 return ICEDiag(2, E->getLocStart());
3371 case Expr::UnaryOperatorClass: {
3372 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3373 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003374 case UO_PostInc:
3375 case UO_PostDec:
3376 case UO_PreInc:
3377 case UO_PreDec:
3378 case UO_AddrOf:
3379 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00003380 // C99 6.6/3 allows increment and decrement within unevaluated
3381 // subexpressions of constant expressions, but they can never be ICEs
3382 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003383 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00003384 case UO_Extension:
3385 case UO_LNot:
3386 case UO_Plus:
3387 case UO_Minus:
3388 case UO_Not:
3389 case UO_Real:
3390 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003391 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003392 }
3393
3394 // OffsetOf falls through here.
3395 }
3396 case Expr::OffsetOfExprClass: {
3397 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00003398 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00003399 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00003400 // compliance: we should warn earlier for offsetof expressions with
3401 // array subscripts that aren't ICEs, and if the array subscripts
3402 // are ICEs, the value of the offsetof must be an integer constant.
3403 return CheckEvalInICE(E, Ctx);
3404 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003405 case Expr::UnaryExprOrTypeTraitExprClass: {
3406 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3407 if ((Exp->getKind() == UETT_SizeOf) &&
3408 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003409 return ICEDiag(2, E->getLocStart());
3410 return NoDiag();
3411 }
3412 case Expr::BinaryOperatorClass: {
3413 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3414 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003415 case BO_PtrMemD:
3416 case BO_PtrMemI:
3417 case BO_Assign:
3418 case BO_MulAssign:
3419 case BO_DivAssign:
3420 case BO_RemAssign:
3421 case BO_AddAssign:
3422 case BO_SubAssign:
3423 case BO_ShlAssign:
3424 case BO_ShrAssign:
3425 case BO_AndAssign:
3426 case BO_XorAssign:
3427 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00003428 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3429 // constant expressions, but they can never be ICEs because an ICE cannot
3430 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003431 return ICEDiag(2, E->getLocStart());
3432
John McCalle3027922010-08-25 11:45:40 +00003433 case BO_Mul:
3434 case BO_Div:
3435 case BO_Rem:
3436 case BO_Add:
3437 case BO_Sub:
3438 case BO_Shl:
3439 case BO_Shr:
3440 case BO_LT:
3441 case BO_GT:
3442 case BO_LE:
3443 case BO_GE:
3444 case BO_EQ:
3445 case BO_NE:
3446 case BO_And:
3447 case BO_Xor:
3448 case BO_Or:
3449 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003450 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3451 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003452 if (Exp->getOpcode() == BO_Div ||
3453 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00003454 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00003455 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003456 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003457 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003458 if (REval == 0)
3459 return ICEDiag(1, E->getLocStart());
3460 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003461 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003462 if (LEval.isMinSignedValue())
3463 return ICEDiag(1, E->getLocStart());
3464 }
3465 }
3466 }
John McCalle3027922010-08-25 11:45:40 +00003467 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003468 if (Ctx.getLangOptions().C99) {
3469 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3470 // if it isn't evaluated.
3471 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3472 return ICEDiag(1, E->getLocStart());
3473 } else {
3474 // In both C89 and C++, commas in ICEs are illegal.
3475 return ICEDiag(2, E->getLocStart());
3476 }
3477 }
3478 if (LHSResult.Val >= RHSResult.Val)
3479 return LHSResult;
3480 return RHSResult;
3481 }
John McCalle3027922010-08-25 11:45:40 +00003482 case BO_LAnd:
3483 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003484 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003485
3486 // C++0x [expr.const]p2:
3487 // [...] subexpressions of logical AND (5.14), logical OR
3488 // (5.15), and condi- tional (5.16) operations that are not
3489 // evaluated are not considered.
3490 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3491 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003492 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003493 return LHSResult;
3494
3495 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003496 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003497 return LHSResult;
3498 }
3499
John McCall864e3962010-05-07 05:32:02 +00003500 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3501 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3502 // Rare case where the RHS has a comma "side-effect"; we need
3503 // to actually check the condition to see whether the side
3504 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003505 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003506 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003507 return RHSResult;
3508 return NoDiag();
3509 }
3510
3511 if (LHSResult.Val >= RHSResult.Val)
3512 return LHSResult;
3513 return RHSResult;
3514 }
3515 }
3516 }
3517 case Expr::ImplicitCastExprClass:
3518 case Expr::CStyleCastExprClass:
3519 case Expr::CXXFunctionalCastExprClass:
3520 case Expr::CXXStaticCastExprClass:
3521 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00003522 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003523 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003524 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00003525 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00003526 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3527 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00003528 switch (cast<CastExpr>(E)->getCastKind()) {
3529 case CK_LValueToRValue:
3530 case CK_NoOp:
3531 case CK_IntegralToBoolean:
3532 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003533 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003534 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00003535 return ICEDiag(2, E->getLocStart());
3536 }
John McCall864e3962010-05-07 05:32:02 +00003537 }
John McCallc07a0c72011-02-17 10:25:35 +00003538 case Expr::BinaryConditionalOperatorClass: {
3539 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3540 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3541 if (CommonResult.Val == 2) return CommonResult;
3542 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3543 if (FalseResult.Val == 2) return FalseResult;
3544 if (CommonResult.Val == 1) return CommonResult;
3545 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003546 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003547 return FalseResult;
3548 }
John McCall864e3962010-05-07 05:32:02 +00003549 case Expr::ConditionalOperatorClass: {
3550 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3551 // If the condition (ignoring parens) is a __builtin_constant_p call,
3552 // then only the true side is actually considered in an integer constant
3553 // expression, and it is fully evaluated. This is an important GNU
3554 // extension. See GCC PR38377 for discussion.
3555 if (const CallExpr *CallCE
3556 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3557 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3558 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003559 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003560 !EVResult.Val.isInt()) {
3561 return ICEDiag(2, E->getLocStart());
3562 }
3563 return NoDiag();
3564 }
3565 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003566 if (CondResult.Val == 2)
3567 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003568
3569 // C++0x [expr.const]p2:
3570 // subexpressions of [...] conditional (5.16) operations that
3571 // are not evaluated are not considered
3572 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003573 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003574 : false;
3575 ICEDiag TrueResult = NoDiag();
3576 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3577 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3578 ICEDiag FalseResult = NoDiag();
3579 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3580 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3581
John McCall864e3962010-05-07 05:32:02 +00003582 if (TrueResult.Val == 2)
3583 return TrueResult;
3584 if (FalseResult.Val == 2)
3585 return FalseResult;
3586 if (CondResult.Val == 1)
3587 return CondResult;
3588 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3589 return NoDiag();
3590 // Rare case where the diagnostics depend on which side is evaluated
3591 // Note that if we get here, CondResult is 0, and at least one of
3592 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003593 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003594 return FalseResult;
3595 }
3596 return TrueResult;
3597 }
3598 case Expr::CXXDefaultArgExprClass:
3599 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3600 case Expr::ChooseExprClass: {
3601 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3602 }
3603 }
3604
3605 // Silence a GCC warning
3606 return ICEDiag(2, E->getLocStart());
3607}
3608
3609bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3610 SourceLocation *Loc, bool isEvaluated) const {
3611 ICEDiag d = CheckICE(this, Ctx);
3612 if (d.Val != 0) {
3613 if (Loc) *Loc = d.Loc;
3614 return false;
3615 }
Richard Smith11562c52011-10-28 17:51:58 +00003616 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00003617 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00003618 return true;
3619}