blob: 3a897ab34842dc9a2efb9fadee3b1eff3b34e492 [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 Smithd62306a2011-11-10 06:34:14 +000046 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000049
Richard Smithce40ad62011-11-12 22:28:03 +000050 QualType getType(APValue::LValueBase B) {
51 if (!B) return QualType();
52 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
53 return D->getType();
54 return B.get<const Expr*>()->getType();
55 }
56
Richard Smithd62306a2011-11-10 06:34:14 +000057 /// Get an LValue path entry, which is known to not be an array index, as a
58 /// field declaration.
59 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
60 APValue::BaseOrMemberType Value;
61 Value.setFromOpaqueValue(E.BaseOrMember);
62 return dyn_cast<FieldDecl>(Value.getPointer());
63 }
64 /// Get an LValue path entry, which is known to not be an array index, as a
65 /// base class declaration.
66 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
67 APValue::BaseOrMemberType Value;
68 Value.setFromOpaqueValue(E.BaseOrMember);
69 return dyn_cast<CXXRecordDecl>(Value.getPointer());
70 }
71 /// Determine whether this LValue path entry for a base class names a virtual
72 /// base class.
73 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
74 APValue::BaseOrMemberType Value;
75 Value.setFromOpaqueValue(E.BaseOrMember);
76 return Value.getInt();
77 }
78
Richard Smith80815602011-11-07 05:07:52 +000079 /// Determine whether the described subobject is an array element.
80 static bool SubobjectIsArrayElement(QualType Base,
81 ArrayRef<APValue::LValuePathEntry> Path) {
82 bool IsArrayElement = false;
83 const Type *T = Base.getTypePtr();
84 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
85 IsArrayElement = T && T->isArrayType();
86 if (IsArrayElement)
87 T = T->getBaseElementTypeUnsafe();
Richard Smithd62306a2011-11-10 06:34:14 +000088 else if (const FieldDecl *FD = getAsField(Path[I]))
Richard Smith80815602011-11-07 05:07:52 +000089 T = FD->getType().getTypePtr();
90 else
91 // Path[I] describes a base class.
92 T = 0;
93 }
94 return IsArrayElement;
95 }
96
Richard Smith96e0c102011-11-04 02:25:55 +000097 /// A path from a glvalue to a subobject of that glvalue.
98 struct SubobjectDesignator {
99 /// True if the subobject was named in a manner not supported by C++11. Such
100 /// lvalues can still be folded, but they are not core constant expressions
101 /// and we cannot perform lvalue-to-rvalue conversions on them.
102 bool Invalid : 1;
103
104 /// Whether this designates an array element.
105 bool ArrayElement : 1;
106
107 /// Whether this designates 'one past the end' of the current subobject.
108 bool OnePastTheEnd : 1;
109
Richard Smith80815602011-11-07 05:07:52 +0000110 typedef APValue::LValuePathEntry PathEntry;
111
Richard Smith96e0c102011-11-04 02:25:55 +0000112 /// The entries on the path from the glvalue to the designated subobject.
113 SmallVector<PathEntry, 8> Entries;
114
115 SubobjectDesignator() :
116 Invalid(false), ArrayElement(false), OnePastTheEnd(false) {}
117
Richard Smith80815602011-11-07 05:07:52 +0000118 SubobjectDesignator(const APValue &V) :
119 Invalid(!V.isLValue() || !V.hasLValuePath()), ArrayElement(false),
120 OnePastTheEnd(false) {
121 if (!Invalid) {
122 ArrayRef<PathEntry> VEntries = V.getLValuePath();
123 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
124 if (V.getLValueBase())
Richard Smithce40ad62011-11-12 22:28:03 +0000125 ArrayElement = SubobjectIsArrayElement(getType(V.getLValueBase()),
Richard Smith80815602011-11-07 05:07:52 +0000126 V.getLValuePath());
127 else
128 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
Richard Smith027bf112011-11-17 22:56:20 +0000129 OnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000130 }
131 }
132
Richard Smith96e0c102011-11-04 02:25:55 +0000133 void setInvalid() {
134 Invalid = true;
135 Entries.clear();
136 }
137 /// Update this designator to refer to the given element within this array.
138 void addIndex(uint64_t N) {
139 if (Invalid) return;
140 if (OnePastTheEnd) {
141 setInvalid();
142 return;
143 }
144 PathEntry Entry;
Richard Smith80815602011-11-07 05:07:52 +0000145 Entry.ArrayIndex = N;
Richard Smith96e0c102011-11-04 02:25:55 +0000146 Entries.push_back(Entry);
147 ArrayElement = true;
148 }
149 /// Update this designator to refer to the given base or member of this
150 /// object.
Richard Smithd62306a2011-11-10 06:34:14 +0000151 void addDecl(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000152 if (Invalid) return;
153 if (OnePastTheEnd) {
154 setInvalid();
155 return;
156 }
157 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000158 APValue::BaseOrMemberType Value(D, Virtual);
159 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000160 Entries.push_back(Entry);
161 ArrayElement = false;
162 }
163 /// Add N to the address of this subobject.
164 void adjustIndex(uint64_t N) {
165 if (Invalid) return;
166 if (ArrayElement) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000167 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith80815602011-11-07 05:07:52 +0000168 Entries.back().ArrayIndex += N;
Richard Smith96e0c102011-11-04 02:25:55 +0000169 return;
170 }
171 if (OnePastTheEnd && N == (uint64_t)-1)
172 OnePastTheEnd = false;
173 else if (!OnePastTheEnd && N == 1)
174 OnePastTheEnd = true;
175 else if (N != 0)
176 setInvalid();
177 }
178 };
179
Richard Smith0b0a0b62011-10-29 20:57:55 +0000180 /// A core constant value. This can be the value of any constant expression,
181 /// or a pointer or reference to a non-static object or function parameter.
Richard Smith027bf112011-11-17 22:56:20 +0000182 ///
183 /// For an LValue, the base and offset are stored in the APValue subobject,
184 /// but the other information is stored in the SubobjectDesignator. For all
185 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000186 class CCValue : public APValue {
187 typedef llvm::APSInt APSInt;
188 typedef llvm::APFloat APFloat;
Richard Smithfec09922011-11-01 16:57:24 +0000189 /// If the value is a reference or pointer into a parameter or temporary,
190 /// this is the corresponding call stack frame.
191 CallStackFrame *CallFrame;
Richard Smith96e0c102011-11-04 02:25:55 +0000192 /// If the value is a reference or pointer, this is a description of how the
193 /// subobject was specified.
194 SubobjectDesignator Designator;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000195 public:
Richard Smithfec09922011-11-01 16:57:24 +0000196 struct GlobalValue {};
197
Richard Smith0b0a0b62011-10-29 20:57:55 +0000198 CCValue() {}
199 explicit CCValue(const APSInt &I) : APValue(I) {}
200 explicit CCValue(const APFloat &F) : APValue(F) {}
201 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
202 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
203 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smithfec09922011-11-01 16:57:24 +0000204 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smithce40ad62011-11-12 22:28:03 +0000205 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith96e0c102011-11-04 02:25:55 +0000206 const SubobjectDesignator &D) :
Richard Smith80815602011-11-07 05:07:52 +0000207 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithfec09922011-11-01 16:57:24 +0000208 CCValue(const APValue &V, GlobalValue) :
Richard Smith80815602011-11-07 05:07:52 +0000209 APValue(V), CallFrame(0), Designator(V) {}
Richard Smith027bf112011-11-17 22:56:20 +0000210 CCValue(const ValueDecl *D, bool IsDerivedMember,
211 ArrayRef<const CXXRecordDecl*> Path) :
212 APValue(D, IsDerivedMember, Path) {}
Richard Smith0b0a0b62011-10-29 20:57:55 +0000213
Richard Smithfec09922011-11-01 16:57:24 +0000214 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000215 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +0000216 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000217 }
Richard Smith96e0c102011-11-04 02:25:55 +0000218 SubobjectDesignator &getLValueDesignator() {
219 assert(getKind() == LValue);
220 return Designator;
221 }
222 const SubobjectDesignator &getLValueDesignator() const {
223 return const_cast<CCValue*>(this)->getLValueDesignator();
224 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000225 };
226
Richard Smith254a73d2011-10-28 22:34:42 +0000227 /// A stack frame in the constexpr call stack.
228 struct CallStackFrame {
229 EvalInfo &Info;
230
231 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000232 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000233
Richard Smithd62306a2011-11-10 06:34:14 +0000234 /// This - The binding for the this pointer in this call, if any.
235 const LValue *This;
236
Richard Smith254a73d2011-10-28 22:34:42 +0000237 /// ParmBindings - Parameter bindings for this function call, indexed by
238 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000239 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000240
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000241 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
242 typedef MapTy::const_iterator temp_iterator;
243 /// Temporaries - Temporary lvalues materialized within this stack frame.
244 MapTy Temporaries;
245
Richard Smithd62306a2011-11-10 06:34:14 +0000246 CallStackFrame(EvalInfo &Info, const LValue *This,
247 const CCValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000248 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000249 };
250
Richard Smith92b1ce02011-12-12 09:28:41 +0000251 /// A partial diagnostic which we might know in advance that we are not going
252 /// to emit.
253 class OptionalDiagnostic {
254 PartialDiagnostic *Diag;
255
256 public:
257 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
258
259 template<typename T>
260 OptionalDiagnostic &operator<<(const T &v) {
261 if (Diag)
262 *Diag << v;
263 return *this;
264 }
265 };
266
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000267 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000268 ASTContext &Ctx;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000269
270 /// EvalStatus - Contains information about the evaluation.
271 Expr::EvalStatus &EvalStatus;
272
273 /// CurrentCall - The top of the constexpr call stack.
274 CallStackFrame *CurrentCall;
275
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000276 /// CallStackDepth - The number of calls in the call stack right now.
277 unsigned CallStackDepth;
278
279 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
280 /// OpaqueValues - Values used as the common expression in a
281 /// BinaryConditionalOperator.
282 MapTy OpaqueValues;
283
284 /// BottomFrame - The frame in which evaluation started. This must be
285 /// initialized last.
286 CallStackFrame BottomFrame;
287
Richard Smithd62306a2011-11-10 06:34:14 +0000288 /// EvaluatingDecl - This is the declaration whose initializer is being
289 /// evaluated, if any.
290 const VarDecl *EvaluatingDecl;
291
292 /// EvaluatingDeclValue - This is the value being constructed for the
293 /// declaration whose initializer is being evaluated, if any.
294 APValue *EvaluatingDeclValue;
295
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000296
297 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith92b1ce02011-12-12 09:28:41 +0000298 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
299 CallStackDepth(0), BottomFrame(*this, 0, 0), EvaluatingDecl(0),
300 EvaluatingDeclValue(0) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000301
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000302 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
303 MapTy::const_iterator i = OpaqueValues.find(e);
304 if (i == OpaqueValues.end()) return 0;
305 return &i->second;
306 }
307
Richard Smithd62306a2011-11-10 06:34:14 +0000308 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
309 EvaluatingDecl = VD;
310 EvaluatingDeclValue = &Value;
311 }
312
Richard Smith9a568822011-11-21 19:36:32 +0000313 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
314
315 bool atCallLimit() const {
316 return CallStackDepth > getLangOpts().ConstexprCallDepth;
317 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000318
Richard Smithf57d8cb2011-12-09 22:58:01 +0000319 /// Diagnose that the evaluation cannot be folded.
Richard Smith92b1ce02011-12-12 09:28:41 +0000320 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000321 // If we have a prior diagnostic, it will be noting that the expression
322 // isn't a constant expression. This diagnostic is more important.
323 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000324 if (EvalStatus.Diag) {
325 EvalStatus.Diag->clear();
326 EvalStatus.Diag->reserve(1);
327 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
328 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
329 // FIXME: Add a call stack for constexpr evaluation.
330 return OptionalDiagnostic(&EvalStatus.Diag->back().second);
331 }
332 return OptionalDiagnostic();
333 }
334
335 /// Diagnose that the evaluation does not produce a C++11 core constant
336 /// expression.
337 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId) {
338 // Don't override a previous diagnostic.
339 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
340 return OptionalDiagnostic();
341 return Diag(Loc, DiagId);
Richard Smithf57d8cb2011-12-09 22:58:01 +0000342 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000343 };
344
Richard Smithd62306a2011-11-10 06:34:14 +0000345 CallStackFrame::CallStackFrame(EvalInfo &Info, const LValue *This,
346 const CCValue *Arguments)
347 : Info(Info), Caller(Info.CurrentCall), This(This), Arguments(Arguments) {
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000348 Info.CurrentCall = this;
349 ++Info.CallStackDepth;
350 }
351
352 CallStackFrame::~CallStackFrame() {
353 assert(Info.CurrentCall == this && "calls retired out of order");
354 --Info.CallStackDepth;
355 Info.CurrentCall = Caller;
356 }
357
John McCall93d91dc2010-05-07 17:22:02 +0000358 struct ComplexValue {
359 private:
360 bool IsInt;
361
362 public:
363 APSInt IntReal, IntImag;
364 APFloat FloatReal, FloatImag;
365
366 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
367
368 void makeComplexFloat() { IsInt = false; }
369 bool isComplexFloat() const { return !IsInt; }
370 APFloat &getComplexFloatReal() { return FloatReal; }
371 APFloat &getComplexFloatImag() { return FloatImag; }
372
373 void makeComplexInt() { IsInt = true; }
374 bool isComplexInt() const { return IsInt; }
375 APSInt &getComplexIntReal() { return IntReal; }
376 APSInt &getComplexIntImag() { return IntImag; }
377
Richard Smith0b0a0b62011-10-29 20:57:55 +0000378 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000379 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000380 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000381 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000382 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000383 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000384 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000385 assert(v.isComplexFloat() || v.isComplexInt());
386 if (v.isComplexFloat()) {
387 makeComplexFloat();
388 FloatReal = v.getComplexFloatReal();
389 FloatImag = v.getComplexFloatImag();
390 } else {
391 makeComplexInt();
392 IntReal = v.getComplexIntReal();
393 IntImag = v.getComplexIntImag();
394 }
395 }
John McCall93d91dc2010-05-07 17:22:02 +0000396 };
John McCall45d55e42010-05-07 21:00:08 +0000397
398 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000399 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000400 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000401 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000402 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000403
Richard Smithce40ad62011-11-12 22:28:03 +0000404 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000405 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000406 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000407 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000408 SubobjectDesignator &getLValueDesignator() { return Designator; }
409 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000410
Richard Smith0b0a0b62011-10-29 20:57:55 +0000411 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000412 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000413 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000414 void setFrom(const CCValue &V) {
415 assert(V.isLValue());
416 Base = V.getLValueBase();
417 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000418 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000419 Designator = V.getLValueDesignator();
420 }
421
Richard Smithce40ad62011-11-12 22:28:03 +0000422 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
423 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000424 Offset = CharUnits::Zero();
425 Frame = F;
426 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000427 }
John McCall45d55e42010-05-07 21:00:08 +0000428 };
Richard Smith027bf112011-11-17 22:56:20 +0000429
430 struct MemberPtr {
431 MemberPtr() {}
432 explicit MemberPtr(const ValueDecl *Decl) :
433 DeclAndIsDerivedMember(Decl, false), Path() {}
434
435 /// The member or (direct or indirect) field referred to by this member
436 /// pointer, or 0 if this is a null member pointer.
437 const ValueDecl *getDecl() const {
438 return DeclAndIsDerivedMember.getPointer();
439 }
440 /// Is this actually a member of some type derived from the relevant class?
441 bool isDerivedMember() const {
442 return DeclAndIsDerivedMember.getInt();
443 }
444 /// Get the class which the declaration actually lives in.
445 const CXXRecordDecl *getContainingRecord() const {
446 return cast<CXXRecordDecl>(
447 DeclAndIsDerivedMember.getPointer()->getDeclContext());
448 }
449
450 void moveInto(CCValue &V) const {
451 V = CCValue(getDecl(), isDerivedMember(), Path);
452 }
453 void setFrom(const CCValue &V) {
454 assert(V.isMemberPointer());
455 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
456 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
457 Path.clear();
458 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
459 Path.insert(Path.end(), P.begin(), P.end());
460 }
461
462 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
463 /// whether the member is a member of some class derived from the class type
464 /// of the member pointer.
465 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
466 /// Path - The path of base/derived classes from the member declaration's
467 /// class (exclusive) to the class type of the member pointer (inclusive).
468 SmallVector<const CXXRecordDecl*, 4> Path;
469
470 /// Perform a cast towards the class of the Decl (either up or down the
471 /// hierarchy).
472 bool castBack(const CXXRecordDecl *Class) {
473 assert(!Path.empty());
474 const CXXRecordDecl *Expected;
475 if (Path.size() >= 2)
476 Expected = Path[Path.size() - 2];
477 else
478 Expected = getContainingRecord();
479 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
480 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
481 // if B does not contain the original member and is not a base or
482 // derived class of the class containing the original member, the result
483 // of the cast is undefined.
484 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
485 // (D::*). We consider that to be a language defect.
486 return false;
487 }
488 Path.pop_back();
489 return true;
490 }
491 /// Perform a base-to-derived member pointer cast.
492 bool castToDerived(const CXXRecordDecl *Derived) {
493 if (!getDecl())
494 return true;
495 if (!isDerivedMember()) {
496 Path.push_back(Derived);
497 return true;
498 }
499 if (!castBack(Derived))
500 return false;
501 if (Path.empty())
502 DeclAndIsDerivedMember.setInt(false);
503 return true;
504 }
505 /// Perform a derived-to-base member pointer cast.
506 bool castToBase(const CXXRecordDecl *Base) {
507 if (!getDecl())
508 return true;
509 if (Path.empty())
510 DeclAndIsDerivedMember.setInt(true);
511 if (isDerivedMember()) {
512 Path.push_back(Base);
513 return true;
514 }
515 return castBack(Base);
516 }
517 };
John McCall93d91dc2010-05-07 17:22:02 +0000518}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000519
Richard Smith0b0a0b62011-10-29 20:57:55 +0000520static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000521static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +0000522 const LValue &This, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000523static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
524static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000525static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
526 EvalInfo &Info);
527static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000528static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000529static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000530 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000531static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000532static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000533
534//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000535// Misc utilities
536//===----------------------------------------------------------------------===//
537
Richard Smithd62306a2011-11-10 06:34:14 +0000538/// Should this call expression be treated as a string literal?
539static bool IsStringLiteralCall(const CallExpr *E) {
540 unsigned Builtin = E->isBuiltinCall();
541 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
542 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
543}
544
Richard Smithce40ad62011-11-12 22:28:03 +0000545static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000546 // C++11 [expr.const]p3 An address constant expression is a prvalue core
547 // constant expression of pointer type that evaluates to...
548
549 // ... a null pointer value, or a prvalue core constant expression of type
550 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000551 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000552
Richard Smithce40ad62011-11-12 22:28:03 +0000553 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
554 // ... the address of an object with static storage duration,
555 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
556 return VD->hasGlobalStorage();
557 // ... the address of a function,
558 return isa<FunctionDecl>(D);
559 }
560
561 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000562 switch (E->getStmtClass()) {
563 default:
564 return false;
Richard Smithd62306a2011-11-10 06:34:14 +0000565 case Expr::CompoundLiteralExprClass:
566 return cast<CompoundLiteralExpr>(E)->isFileScope();
567 // A string literal has static storage duration.
568 case Expr::StringLiteralClass:
569 case Expr::PredefinedExprClass:
570 case Expr::ObjCStringLiteralClass:
571 case Expr::ObjCEncodeExprClass:
572 return true;
573 case Expr::CallExprClass:
574 return IsStringLiteralCall(cast<CallExpr>(E));
575 // For GCC compatibility, &&label has static storage duration.
576 case Expr::AddrLabelExprClass:
577 return true;
578 // A Block literal expression may be used as the initialization value for
579 // Block variables at global or local static scope.
580 case Expr::BlockExprClass:
581 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
582 }
John McCall95007602010-05-10 23:27:23 +0000583}
584
Richard Smith80815602011-11-07 05:07:52 +0000585/// Check that this reference or pointer core constant expression is a valid
586/// value for a constant expression. Type T should be either LValue or CCValue.
587template<typename T>
Richard Smithf57d8cb2011-12-09 22:58:01 +0000588static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
589 const T &LVal, APValue &Value) {
590 if (!IsGlobalLValue(LVal.getLValueBase())) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000591 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith80815602011-11-07 05:07:52 +0000592 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000593 }
Richard Smith80815602011-11-07 05:07:52 +0000594
595 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
596 // A constant expression must refer to an object or be a null pointer.
Richard Smith027bf112011-11-17 22:56:20 +0000597 if (Designator.Invalid ||
Richard Smith80815602011-11-07 05:07:52 +0000598 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smith80815602011-11-07 05:07:52 +0000599 // FIXME: This is not a constant expression.
600 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
601 APValue::NoLValuePath());
602 return true;
603 }
604
605 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smith027bf112011-11-17 22:56:20 +0000606 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith80815602011-11-07 05:07:52 +0000607 return true;
608}
609
Richard Smith0b0a0b62011-10-29 20:57:55 +0000610/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000611/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000612/// If not, report an appropriate diagnostic.
613static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
614 const CCValue &CCValue, APValue &Value) {
Richard Smith80815602011-11-07 05:07:52 +0000615 if (!CCValue.isLValue()) {
616 Value = CCValue;
617 return true;
618 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000619 return CheckLValueConstantExpression(Info, E, CCValue, Value);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000620}
621
Richard Smith83c68212011-10-31 05:11:32 +0000622const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000623 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000624}
625
626static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000627 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000628}
629
Richard Smithcecf1842011-11-01 21:06:14 +0000630static bool IsWeakLValue(const LValue &Value) {
631 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000632 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000633}
634
Richard Smith027bf112011-11-17 22:56:20 +0000635static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000636 // A null base expression indicates a null pointer. These are always
637 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000638 if (!Value.getLValueBase()) {
639 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000640 return true;
641 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000642
John McCall95007602010-05-10 23:27:23 +0000643 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000644 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000645 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000646
Richard Smith027bf112011-11-17 22:56:20 +0000647 // We have a non-null base. These are generally known to be true, but if it's
648 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000649 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000650 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000651 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000652}
653
Richard Smith0b0a0b62011-10-29 20:57:55 +0000654static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000655 switch (Val.getKind()) {
656 case APValue::Uninitialized:
657 return false;
658 case APValue::Int:
659 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000660 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000661 case APValue::Float:
662 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000663 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000664 case APValue::ComplexInt:
665 Result = Val.getComplexIntReal().getBoolValue() ||
666 Val.getComplexIntImag().getBoolValue();
667 return true;
668 case APValue::ComplexFloat:
669 Result = !Val.getComplexFloatReal().isZero() ||
670 !Val.getComplexFloatImag().isZero();
671 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000672 case APValue::LValue:
673 return EvalPointerValueAsBool(Val, Result);
674 case APValue::MemberPointer:
675 Result = Val.getMemberPointerDecl();
676 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000677 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000678 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000679 case APValue::Struct:
680 case APValue::Union:
Richard Smith11562c52011-10-28 17:51:58 +0000681 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000682 }
683
Richard Smith11562c52011-10-28 17:51:58 +0000684 llvm_unreachable("unknown APValue kind");
685}
686
687static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
688 EvalInfo &Info) {
689 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000690 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000691 if (!Evaluate(Val, Info, E))
692 return false;
693 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000694}
695
Mike Stump11289f42009-09-09 15:08:12 +0000696static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000697 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000698 unsigned DestWidth = Ctx.getIntWidth(DestType);
699 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000700 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000701
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000702 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000703 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000704 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000705 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
706 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000707}
708
Mike Stump11289f42009-09-09 15:08:12 +0000709static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000710 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000711 bool ignored;
712 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000713 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000714 APFloat::rmNearestTiesToEven, &ignored);
715 return Result;
716}
717
Mike Stump11289f42009-09-09 15:08:12 +0000718static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000719 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000720 unsigned DestWidth = Ctx.getIntWidth(DestType);
721 APSInt Result = Value;
722 // Figure out if this is a truncate, extend or noop cast.
723 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000724 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000725 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000726 return Result;
727}
728
Mike Stump11289f42009-09-09 15:08:12 +0000729static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000730 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000731
732 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
733 Result.convertFromAPInt(Value, Value.isSigned(),
734 APFloat::rmNearestTiesToEven);
735 return Result;
736}
737
Richard Smith027bf112011-11-17 22:56:20 +0000738static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
739 const CXXRecordDecl *&MostDerivedType,
740 unsigned &MostDerivedPathLength,
741 bool &MostDerivedIsArrayElement) {
742 const SubobjectDesignator &D = LVal.Designator;
743 if (D.Invalid || !LVal.Base)
Richard Smithd62306a2011-11-10 06:34:14 +0000744 return false;
745
Richard Smith027bf112011-11-17 22:56:20 +0000746 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smithd62306a2011-11-10 06:34:14 +0000747
748 // Find path prefix which leads to the most-derived subobject.
Richard Smithd62306a2011-11-10 06:34:14 +0000749 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smith027bf112011-11-17 22:56:20 +0000750 MostDerivedPathLength = 0;
751 MostDerivedIsArrayElement = false;
Richard Smithd62306a2011-11-10 06:34:14 +0000752
753 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
754 bool IsArray = T && T->isArrayType();
755 if (IsArray)
756 T = T->getBaseElementTypeUnsafe();
757 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
758 T = FD->getType().getTypePtr();
759 else
760 T = 0;
761
762 if (T) {
763 MostDerivedType = T->getAsCXXRecordDecl();
764 MostDerivedPathLength = I + 1;
765 MostDerivedIsArrayElement = IsArray;
766 }
767 }
768
Richard Smithd62306a2011-11-10 06:34:14 +0000769 // (B*)&d + 1 has no most-derived object.
770 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
771 return false;
772
Richard Smith027bf112011-11-17 22:56:20 +0000773 return MostDerivedType != 0;
774}
775
776static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
777 const RecordDecl *TruncatedType,
778 unsigned TruncatedElements,
779 bool IsArrayElement) {
780 SubobjectDesignator &D = Result.Designator;
781 const RecordDecl *RD = TruncatedType;
782 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +0000783 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
784 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +0000785 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +0000786 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +0000787 else
Richard Smithd62306a2011-11-10 06:34:14 +0000788 Result.Offset -= Layout.getBaseClassOffset(Base);
789 RD = Base;
790 }
Richard Smith027bf112011-11-17 22:56:20 +0000791 D.Entries.resize(TruncatedElements);
792 D.ArrayElement = IsArrayElement;
793}
794
795/// If the given LValue refers to a base subobject of some object, find the most
796/// derived object and the corresponding complete record type. This is necessary
797/// in order to find the offset of a virtual base class.
798static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
799 const CXXRecordDecl *&MostDerivedType) {
800 unsigned MostDerivedPathLength;
801 bool MostDerivedIsArrayElement;
802 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
803 MostDerivedPathLength, MostDerivedIsArrayElement))
804 return false;
805
806 // Remove the trailing base class path entries and their offsets.
807 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
808 MostDerivedIsArrayElement);
Richard Smithd62306a2011-11-10 06:34:14 +0000809 return true;
810}
811
812static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
813 const CXXRecordDecl *Derived,
814 const CXXRecordDecl *Base,
815 const ASTRecordLayout *RL = 0) {
816 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
817 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
818 Obj.Designator.addDecl(Base, /*Virtual*/ false);
819}
820
821static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
822 const CXXRecordDecl *DerivedDecl,
823 const CXXBaseSpecifier *Base) {
824 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
825
826 if (!Base->isVirtual()) {
827 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
828 return true;
829 }
830
831 // Extract most-derived object and corresponding type.
832 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
833 return false;
834
835 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
836 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
837 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
838 return true;
839}
840
841/// Update LVal to refer to the given field, which must be a member of the type
842/// currently described by LVal.
843static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
844 const FieldDecl *FD,
845 const ASTRecordLayout *RL = 0) {
846 if (!RL)
847 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
848
849 unsigned I = FD->getFieldIndex();
850 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
851 LVal.Designator.addDecl(FD);
852}
853
854/// Get the size of the given type in char units.
855static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
856 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
857 // extension.
858 if (Type->isVoidType() || Type->isFunctionType()) {
859 Size = CharUnits::One();
860 return true;
861 }
862
863 if (!Type->isConstantSizeType()) {
864 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
865 return false;
866 }
867
868 Size = Info.Ctx.getTypeSizeInChars(Type);
869 return true;
870}
871
872/// Update a pointer value to model pointer arithmetic.
873/// \param Info - Information about the ongoing evaluation.
874/// \param LVal - The pointer value to be updated.
875/// \param EltTy - The pointee type represented by LVal.
876/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
877static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
878 QualType EltTy, int64_t Adjustment) {
879 CharUnits SizeOfPointee;
880 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
881 return false;
882
883 // Compute the new offset in the appropriate width.
884 LVal.Offset += Adjustment * SizeOfPointee;
885 LVal.Designator.adjustIndex(Adjustment);
886 return true;
887}
888
Richard Smith27908702011-10-24 17:54:18 +0000889/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000890static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
891 const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +0000892 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000893 // If this is a parameter to an active constexpr function call, perform
894 // argument substitution.
895 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000896 if (!Frame || !Frame->Arguments) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000897 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +0000898 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000899 }
Richard Smithfec09922011-11-01 16:57:24 +0000900 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
901 return true;
Richard Smith254a73d2011-10-28 22:34:42 +0000902 }
Richard Smith27908702011-10-24 17:54:18 +0000903
Richard Smithd62306a2011-11-10 06:34:14 +0000904 // If we're currently evaluating the initializer of this declaration, use that
905 // in-flight value.
906 if (Info.EvaluatingDecl == VD) {
907 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
908 return !Result.isUninit();
909 }
910
Richard Smithcecf1842011-11-01 21:06:14 +0000911 // Never evaluate the initializer of a weak variable. We can't be sure that
912 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000913 if (VD->isWeak()) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000914 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +0000915 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000916 }
Richard Smithcecf1842011-11-01 21:06:14 +0000917
Richard Smith27908702011-10-24 17:54:18 +0000918 const Expr *Init = VD->getAnyInitializer();
Richard Smithf57d8cb2011-12-09 22:58:01 +0000919 if (!Init || Init->isValueDependent()) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000920 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000921 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000922 }
Richard Smith27908702011-10-24 17:54:18 +0000923
Richard Smith0b0a0b62011-10-29 20:57:55 +0000924 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smithfec09922011-11-01 16:57:24 +0000925 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000926 return !Result.isUninit();
927 }
Richard Smith27908702011-10-24 17:54:18 +0000928
Richard Smithf57d8cb2011-12-09 22:58:01 +0000929 if (VD->isEvaluatingValue()) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000930 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000931 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000932 }
Richard Smith27908702011-10-24 17:54:18 +0000933
934 VD->setEvaluatingValue();
935
Richard Smith0b0a0b62011-10-29 20:57:55 +0000936 Expr::EvalStatus EStatus;
937 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smithd62306a2011-11-10 06:34:14 +0000938 APValue EvalResult;
939 InitInfo.setEvaluatingDecl(VD, EvalResult);
940 LValue LVal;
Richard Smithce40ad62011-11-12 22:28:03 +0000941 LVal.set(VD);
Richard Smith11562c52011-10-28 17:51:58 +0000942 // FIXME: The caller will need to know whether the value was a constant
943 // expression. If not, we should propagate up a diagnostic.
Richard Smithd62306a2011-11-10 06:34:14 +0000944 if (!EvaluateConstantExpression(EvalResult, InitInfo, LVal, Init)) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000945 // FIXME: If the evaluation failure was not permanent (for instance, if we
946 // hit a variable with no declaration yet, or a constexpr function with no
947 // definition yet), the standard is unclear as to how we should behave.
948 //
949 // Either the initializer should be evaluated when the variable is defined,
950 // or a failed evaluation of the initializer should be reattempted each time
951 // it is used.
Richard Smith27908702011-10-24 17:54:18 +0000952 VD->setEvaluatedValue(APValue());
Richard Smith92b1ce02011-12-12 09:28:41 +0000953 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000954 return false;
955 }
Richard Smith27908702011-10-24 17:54:18 +0000956
Richard Smithed5165f2011-11-04 05:33:44 +0000957 VD->setEvaluatedValue(EvalResult);
958 Result = CCValue(EvalResult, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000959 return true;
Richard Smith27908702011-10-24 17:54:18 +0000960}
961
Richard Smith11562c52011-10-28 17:51:58 +0000962static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000963 Qualifiers Quals = T.getQualifiers();
964 return Quals.hasConst() && !Quals.hasVolatile();
965}
966
Richard Smithe97cbd72011-11-11 04:05:33 +0000967/// Get the base index of the given base class within an APValue representing
968/// the given derived class.
969static unsigned getBaseIndex(const CXXRecordDecl *Derived,
970 const CXXRecordDecl *Base) {
971 Base = Base->getCanonicalDecl();
972 unsigned Index = 0;
973 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
974 E = Derived->bases_end(); I != E; ++I, ++Index) {
975 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
976 return Index;
977 }
978
979 llvm_unreachable("base class missing from derived class's bases list");
980}
981
Richard Smithf3e9e432011-11-07 09:22:26 +0000982/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000983static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
984 CCValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +0000985 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000986 if (Sub.Invalid || Sub.OnePastTheEnd) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000987 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +0000988 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000989 }
Richard Smith6804be52011-11-11 08:28:03 +0000990 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +0000991 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +0000992
993 assert(!Obj.isLValue() && "extracting subobject of lvalue");
994 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +0000995 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +0000996 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000997 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +0000998 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +0000999 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001000 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001001 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001002 if (CAT->getSize().ule(Index)) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001003 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001004 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001005 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001006 if (O->getArrayInitializedElts() > Index)
1007 O = &O->getArrayInitializedElt(Index);
1008 else
1009 O = &O->getArrayFiller();
1010 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +00001011 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1012 // Next subobject is a class, struct or union field.
1013 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1014 if (RD->isUnion()) {
1015 const FieldDecl *UnionField = O->getUnionField();
1016 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001017 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001018 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001019 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001020 }
Richard Smithd62306a2011-11-10 06:34:14 +00001021 O = &O->getUnionValue();
1022 } else
1023 O = &O->getStructField(Field->getFieldIndex());
1024 ObjType = Field->getType();
Richard Smithf3e9e432011-11-07 09:22:26 +00001025 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001026 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001027 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1028 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1029 O = &O->getStructBase(getBaseIndex(Derived, Base));
1030 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001031 }
Richard Smithd62306a2011-11-10 06:34:14 +00001032
Richard Smithf57d8cb2011-12-09 22:58:01 +00001033 if (O->isUninit()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001034 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001035 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001036 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001037 }
1038
Richard Smithf3e9e432011-11-07 09:22:26 +00001039 Obj = CCValue(*O, CCValue::GlobalValue());
1040 return true;
1041}
1042
Richard Smithd62306a2011-11-10 06:34:14 +00001043/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1044/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1045/// for looking up the glvalue referred to by an entity of reference type.
1046///
1047/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001048/// \param Conv - The expression for which we are performing the conversion.
1049/// Used for diagnostics.
Richard Smithd62306a2011-11-10 06:34:14 +00001050/// \param Type - The type we expect this conversion to produce.
1051/// \param LVal - The glvalue on which we are attempting to perform this action.
1052/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001053static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1054 QualType Type,
Richard Smithf3e9e432011-11-07 09:22:26 +00001055 const LValue &LVal, CCValue &RVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001056 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001057 CallStackFrame *Frame = LVal.Frame;
Richard Smith11562c52011-10-28 17:51:58 +00001058
Richard Smithf57d8cb2011-12-09 22:58:01 +00001059 if (!LVal.Base) {
1060 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith92b1ce02011-12-12 09:28:41 +00001061 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith11562c52011-10-28 17:51:58 +00001062 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001063 }
Richard Smith11562c52011-10-28 17:51:58 +00001064
Richard Smithce40ad62011-11-12 22:28:03 +00001065 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001066 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1067 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001068 // expressions are constant expressions too. Inside constexpr functions,
1069 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001070 // In C, such things can also be folded, although they are not ICEs.
1071 //
Richard Smith254a73d2011-10-28 22:34:42 +00001072 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
1073 // interpretation of C++11 suggests that volatile parameters are OK if
1074 // they're never read (there's no prohibition against constructing volatile
1075 // objects in constant expressions), but lvalue-to-rvalue conversions on
1076 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +00001077 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001078 if (!VD || VD->isInvalidDecl()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001079 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001080 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001081 }
1082
Richard Smithce40ad62011-11-12 22:28:03 +00001083 QualType VT = VD->getType();
Richard Smith96e0c102011-11-04 02:25:55 +00001084 if (!isa<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001085 if (!IsConstNonVolatile(VT)) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001086 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001087 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001088 }
Richard Smitha08acd82011-11-07 03:22:51 +00001089 // FIXME: Allow folding of values of any literal type in all languages.
1090 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
Richard Smithf57d8cb2011-12-09 22:58:01 +00001091 !VD->isConstexpr()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001092 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001093 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001094 }
Richard Smith96e0c102011-11-04 02:25:55 +00001095 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001096 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001097 return false;
1098
Richard Smith0b0a0b62011-10-29 20:57:55 +00001099 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001100 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001101
1102 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1103 // conversion. This happens when the declaration and the lvalue should be
1104 // considered synonymous, for instance when initializing an array of char
1105 // from a string literal. Continue as if the initializer lvalue was the
1106 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001107 assert(RVal.getLValueOffset().isZero() &&
1108 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001109 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001110 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001111 }
1112
Richard Smith96e0c102011-11-04 02:25:55 +00001113 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1114 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1115 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001116 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001117 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001118 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001119 }
Richard Smith96e0c102011-11-04 02:25:55 +00001120
1121 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001122 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001123 if (Index > S->getLength()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001124 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001125 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001126 }
Richard Smith96e0c102011-11-04 02:25:55 +00001127 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1128 Type->isUnsignedIntegerType());
1129 if (Index < S->getLength())
1130 Value = S->getCodeUnit(Index);
1131 RVal = CCValue(Value);
1132 return true;
1133 }
1134
Richard Smithf3e9e432011-11-07 09:22:26 +00001135 if (Frame) {
1136 // If this is a temporary expression with a nontrivial initializer, grab the
1137 // value from the relevant stack frame.
1138 RVal = Frame->Temporaries[Base];
1139 } else if (const CompoundLiteralExpr *CLE
1140 = dyn_cast<CompoundLiteralExpr>(Base)) {
1141 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1142 // initializer until now for such expressions. Such an expression can't be
1143 // an ICE in C, so this only matters for fold.
1144 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1145 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1146 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001147 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00001148 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001149 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001150 }
Richard Smith96e0c102011-11-04 02:25:55 +00001151
Richard Smithf57d8cb2011-12-09 22:58:01 +00001152 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1153 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001154}
1155
Richard Smithe97cbd72011-11-11 04:05:33 +00001156/// Build an lvalue for the object argument of a member function call.
1157static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1158 LValue &This) {
1159 if (Object->getType()->isPointerType())
1160 return EvaluatePointer(Object, This, Info);
1161
1162 if (Object->isGLValue())
1163 return EvaluateLValue(Object, This, Info);
1164
Richard Smith027bf112011-11-17 22:56:20 +00001165 if (Object->getType()->isLiteralType())
1166 return EvaluateTemporary(Object, This, Info);
1167
1168 return false;
1169}
1170
1171/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1172/// lvalue referring to the result.
1173///
1174/// \param Info - Information about the ongoing evaluation.
1175/// \param BO - The member pointer access operation.
1176/// \param LV - Filled in with a reference to the resulting object.
1177/// \param IncludeMember - Specifies whether the member itself is included in
1178/// the resulting LValue subobject designator. This is not possible when
1179/// creating a bound member function.
1180/// \return The field or method declaration to which the member pointer refers,
1181/// or 0 if evaluation fails.
1182static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1183 const BinaryOperator *BO,
1184 LValue &LV,
1185 bool IncludeMember = true) {
1186 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1187
1188 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1189 return 0;
1190
1191 MemberPtr MemPtr;
1192 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1193 return 0;
1194
1195 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1196 // member value, the behavior is undefined.
1197 if (!MemPtr.getDecl())
1198 return 0;
1199
1200 if (MemPtr.isDerivedMember()) {
1201 // This is a member of some derived class. Truncate LV appropriately.
1202 const CXXRecordDecl *MostDerivedType;
1203 unsigned MostDerivedPathLength;
1204 bool MostDerivedIsArrayElement;
1205 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1206 MostDerivedIsArrayElement))
1207 return 0;
1208
1209 // The end of the derived-to-base path for the base object must match the
1210 // derived-to-base path for the member pointer.
1211 if (MostDerivedPathLength + MemPtr.Path.size() >
1212 LV.Designator.Entries.size())
1213 return 0;
1214 unsigned PathLengthToMember =
1215 LV.Designator.Entries.size() - MemPtr.Path.size();
1216 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1217 const CXXRecordDecl *LVDecl = getAsBaseClass(
1218 LV.Designator.Entries[PathLengthToMember + I]);
1219 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1220 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1221 return 0;
1222 }
1223
1224 // Truncate the lvalue to the appropriate derived class.
1225 bool ResultIsArray = false;
1226 if (PathLengthToMember == MostDerivedPathLength)
1227 ResultIsArray = MostDerivedIsArrayElement;
1228 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1229 PathLengthToMember, ResultIsArray);
1230 } else if (!MemPtr.Path.empty()) {
1231 // Extend the LValue path with the member pointer's path.
1232 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1233 MemPtr.Path.size() + IncludeMember);
1234
1235 // Walk down to the appropriate base class.
1236 QualType LVType = BO->getLHS()->getType();
1237 if (const PointerType *PT = LVType->getAs<PointerType>())
1238 LVType = PT->getPointeeType();
1239 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1240 assert(RD && "member pointer access on non-class-type expression");
1241 // The first class in the path is that of the lvalue.
1242 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1243 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1244 HandleLValueDirectBase(Info, LV, RD, Base);
1245 RD = Base;
1246 }
1247 // Finally cast to the class containing the member.
1248 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1249 }
1250
1251 // Add the member. Note that we cannot build bound member functions here.
1252 if (IncludeMember) {
1253 // FIXME: Deal with IndirectFieldDecls.
1254 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1255 if (!FD) return 0;
1256 HandleLValueMember(Info, LV, FD);
1257 }
1258
1259 return MemPtr.getDecl();
1260}
1261
1262/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1263/// the provided lvalue, which currently refers to the base object.
1264static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1265 LValue &Result) {
1266 const CXXRecordDecl *MostDerivedType;
1267 unsigned MostDerivedPathLength;
1268 bool MostDerivedIsArrayElement;
1269
1270 // Check this cast doesn't take us outside the object.
1271 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1272 MostDerivedPathLength,
1273 MostDerivedIsArrayElement))
1274 return false;
1275 SubobjectDesignator &D = Result.Designator;
1276 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1277 return false;
1278
1279 // Check the type of the final cast. We don't need to check the path,
1280 // since a cast can only be formed if the path is unique.
1281 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1282 bool ResultIsArray = false;
1283 QualType TargetQT = E->getType();
1284 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1285 TargetQT = PT->getPointeeType();
1286 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1287 const CXXRecordDecl *FinalType;
1288 if (NewEntriesSize == MostDerivedPathLength) {
1289 ResultIsArray = MostDerivedIsArrayElement;
1290 FinalType = MostDerivedType;
1291 } else
1292 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1293 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1294 return false;
1295
1296 // Truncate the lvalue to the appropriate derived class.
1297 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1298 ResultIsArray);
1299 return true;
Richard Smithe97cbd72011-11-11 04:05:33 +00001300}
1301
Mike Stump876387b2009-10-27 22:09:17 +00001302namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001303enum EvalStmtResult {
1304 /// Evaluation failed.
1305 ESR_Failed,
1306 /// Hit a 'return' statement.
1307 ESR_Returned,
1308 /// Evaluation succeeded.
1309 ESR_Succeeded
1310};
1311}
1312
1313// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001314static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001315 const Stmt *S) {
1316 switch (S->getStmtClass()) {
1317 default:
1318 return ESR_Failed;
1319
1320 case Stmt::NullStmtClass:
1321 case Stmt::DeclStmtClass:
1322 return ESR_Succeeded;
1323
1324 case Stmt::ReturnStmtClass:
1325 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
1326 return ESR_Returned;
1327 return ESR_Failed;
1328
1329 case Stmt::CompoundStmtClass: {
1330 const CompoundStmt *CS = cast<CompoundStmt>(S);
1331 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1332 BE = CS->body_end(); BI != BE; ++BI) {
1333 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1334 if (ESR != ESR_Succeeded)
1335 return ESR;
1336 }
1337 return ESR_Succeeded;
1338 }
1339 }
1340}
1341
Richard Smithd62306a2011-11-10 06:34:14 +00001342namespace {
Richard Smith60494462011-11-11 05:48:57 +00001343typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001344}
1345
1346/// EvaluateArgs - Evaluate the arguments to a function call.
1347static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1348 EvalInfo &Info) {
1349 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1350 I != E; ++I)
1351 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1352 return false;
1353 return true;
1354}
1355
Richard Smith254a73d2011-10-28 22:34:42 +00001356/// Evaluate a function call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001357static bool HandleFunctionCall(const Expr *CallExpr, const LValue *This,
1358 ArrayRef<const Expr*> Args, const Stmt *Body,
1359 EvalInfo &Info, CCValue &Result) {
1360 if (Info.atCallLimit()) {
1361 // FIXME: Add a specific proper diagnostic for this.
Richard Smith92b1ce02011-12-12 09:28:41 +00001362 Info.Diag(CallExpr->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith254a73d2011-10-28 22:34:42 +00001363 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001364 }
Richard Smith254a73d2011-10-28 22:34:42 +00001365
Richard Smithd62306a2011-11-10 06:34:14 +00001366 ArgVector ArgValues(Args.size());
1367 if (!EvaluateArgs(Args, ArgValues, Info))
1368 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001369
Richard Smithd62306a2011-11-10 06:34:14 +00001370 CallStackFrame Frame(Info, This, ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001371 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1372}
1373
Richard Smithd62306a2011-11-10 06:34:14 +00001374/// Evaluate a constructor call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001375static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00001376 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001377 const CXXConstructorDecl *Definition,
Richard Smithe97cbd72011-11-11 04:05:33 +00001378 EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +00001379 APValue &Result) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001380 if (Info.atCallLimit()) {
1381 // FIXME: Add a specific diagnostic for this.
Richard Smith92b1ce02011-12-12 09:28:41 +00001382 Info.Diag(CallExpr->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001383 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001384 }
Richard Smithd62306a2011-11-10 06:34:14 +00001385
1386 ArgVector ArgValues(Args.size());
1387 if (!EvaluateArgs(Args, ArgValues, Info))
1388 return false;
1389
1390 CallStackFrame Frame(Info, &This, ArgValues.data());
1391
1392 // If it's a delegating constructor, just delegate.
1393 if (Definition->isDelegatingConstructor()) {
1394 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1395 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1396 }
1397
1398 // Reserve space for the struct members.
1399 const CXXRecordDecl *RD = Definition->getParent();
1400 if (!RD->isUnion())
1401 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1402 std::distance(RD->field_begin(), RD->field_end()));
1403
1404 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1405
1406 unsigned BasesSeen = 0;
1407#ifndef NDEBUG
1408 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1409#endif
1410 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1411 E = Definition->init_end(); I != E; ++I) {
1412 if ((*I)->isBaseInitializer()) {
1413 QualType BaseType((*I)->getBaseClass(), 0);
1414#ifndef NDEBUG
1415 // Non-virtual base classes are initialized in the order in the class
1416 // definition. We cannot have a virtual base class for a literal type.
1417 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1418 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1419 "base class initializers not in expected order");
1420 ++BaseIt;
1421#endif
1422 LValue Subobject = This;
1423 HandleLValueDirectBase(Info, Subobject, RD,
1424 BaseType->getAsCXXRecordDecl(), &Layout);
1425 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1426 Subobject, (*I)->getInit()))
1427 return false;
1428 } else if (FieldDecl *FD = (*I)->getMember()) {
1429 LValue Subobject = This;
1430 HandleLValueMember(Info, Subobject, FD, &Layout);
1431 if (RD->isUnion()) {
1432 Result = APValue(FD);
1433 if (!EvaluateConstantExpression(Result.getUnionValue(), Info,
1434 Subobject, (*I)->getInit()))
1435 return false;
1436 } else if (!EvaluateConstantExpression(
1437 Result.getStructField(FD->getFieldIndex()),
1438 Info, Subobject, (*I)->getInit()))
1439 return false;
1440 } else {
1441 // FIXME: handle indirect field initializers
Richard Smith92b1ce02011-12-12 09:28:41 +00001442 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf57d8cb2011-12-09 22:58:01 +00001443 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001444 return false;
1445 }
1446 }
1447
1448 return true;
1449}
1450
Richard Smith254a73d2011-10-28 22:34:42 +00001451namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001452class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001453 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001454 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001455public:
1456
Richard Smith725810a2011-10-16 21:26:27 +00001457 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001458
1459 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001460 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001461 return true;
1462 }
1463
Peter Collingbournee9200682011-05-13 03:29:01 +00001464 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1465 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001466 return Visit(E->getResultExpr());
1467 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001468 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001469 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001470 return true;
1471 return false;
1472 }
John McCall31168b02011-06-15 23:02:42 +00001473 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001474 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001475 return true;
1476 return false;
1477 }
1478 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001479 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001480 return true;
1481 return false;
1482 }
1483
Mike Stump876387b2009-10-27 22:09:17 +00001484 // We don't want to evaluate BlockExprs multiple times, as they generate
1485 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001486 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1487 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1488 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001489 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001490 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1491 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1492 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1493 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1494 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1495 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001496 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001497 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001498 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001499 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001500 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001501 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1502 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1503 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1504 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001505 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001506 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1507 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1508 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1509 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1510 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001511 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001512 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001513 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001514 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001515 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001516
1517 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001518 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001519 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1520 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001521 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001522 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001523 return false;
1524 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001525
Peter Collingbournee9200682011-05-13 03:29:01 +00001526 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001527};
1528
John McCallc07a0c72011-02-17 10:25:35 +00001529class OpaqueValueEvaluation {
1530 EvalInfo &info;
1531 OpaqueValueExpr *opaqueValue;
1532
1533public:
1534 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1535 Expr *value)
1536 : info(info), opaqueValue(opaqueValue) {
1537
1538 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00001539 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00001540 this->opaqueValue = 0;
1541 return;
1542 }
John McCallc07a0c72011-02-17 10:25:35 +00001543 }
1544
1545 bool hasError() const { return opaqueValue == 0; }
1546
1547 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00001548 // FIXME: This will not work for recursive constexpr functions using opaque
1549 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00001550 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1551 }
1552};
1553
Mike Stump876387b2009-10-27 22:09:17 +00001554} // end anonymous namespace
1555
Eli Friedman9a156e52008-11-12 09:44:48 +00001556//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00001557// Generic Evaluation
1558//===----------------------------------------------------------------------===//
1559namespace {
1560
Richard Smithf57d8cb2011-12-09 22:58:01 +00001561// FIXME: RetTy is always bool. Remove it.
1562template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00001563class ExprEvaluatorBase
1564 : public ConstStmtVisitor<Derived, RetTy> {
1565private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001566 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001567 return static_cast<Derived*>(this)->Success(V, E);
1568 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001569 RetTy DerivedValueInitialization(const Expr *E) {
1570 return static_cast<Derived*>(this)->ValueInitialization(E);
1571 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001572
1573protected:
1574 EvalInfo &Info;
1575 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1576 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1577
Richard Smith92b1ce02011-12-12 09:28:41 +00001578 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith187ef012011-12-12 09:41:58 +00001579 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001580 }
1581
1582 /// Report an evaluation error. This should only be called when an error is
1583 /// first discovered. When propagating an error, just return false.
1584 bool Error(const Expr *E, diag::kind D) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001585 Info.Diag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001586 return false;
1587 }
1588 bool Error(const Expr *E) {
1589 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1590 }
1591
1592 RetTy ValueInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00001593
Peter Collingbournee9200682011-05-13 03:29:01 +00001594public:
1595 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1596
1597 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00001598 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00001599 }
1600 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001601 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001602 }
1603
1604 RetTy VisitParenExpr(const ParenExpr *E)
1605 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1606 RetTy VisitUnaryExtension(const UnaryOperator *E)
1607 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1608 RetTy VisitUnaryPlus(const UnaryOperator *E)
1609 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1610 RetTy VisitChooseExpr(const ChooseExpr *E)
1611 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1612 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1613 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00001614 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1615 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00001616 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1617 { return StmtVisitorTy::Visit(E->getExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001618
Richard Smith6d6ecc32011-12-12 12:46:16 +00001619 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1620 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1621 return static_cast<Derived*>(this)->VisitCastExpr(E);
1622 }
1623 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1624 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1625 return static_cast<Derived*>(this)->VisitCastExpr(E);
1626 }
1627
Richard Smith027bf112011-11-17 22:56:20 +00001628 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1629 switch (E->getOpcode()) {
1630 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00001631 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00001632
1633 case BO_Comma:
1634 VisitIgnoredValue(E->getLHS());
1635 return StmtVisitorTy::Visit(E->getRHS());
1636
1637 case BO_PtrMemD:
1638 case BO_PtrMemI: {
1639 LValue Obj;
1640 if (!HandleMemberPointerAccess(Info, E, Obj))
1641 return false;
1642 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001643 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00001644 return false;
1645 return DerivedSuccess(Result, E);
1646 }
1647 }
1648 }
1649
Peter Collingbournee9200682011-05-13 03:29:01 +00001650 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1651 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1652 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001653 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001654
1655 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00001656 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001657 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001658
1659 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1660 }
1661
1662 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1663 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00001664 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001665 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001666
Richard Smith11562c52011-10-28 17:51:58 +00001667 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00001668 return StmtVisitorTy::Visit(EvalExpr);
1669 }
1670
1671 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001672 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001673 if (!Value) {
1674 const Expr *Source = E->getSourceExpr();
1675 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00001676 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001677 if (Source == E) { // sanity checking.
1678 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00001679 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001680 }
1681 return StmtVisitorTy::Visit(Source);
1682 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001683 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001684 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001685
Richard Smith254a73d2011-10-28 22:34:42 +00001686 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00001687 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00001688 QualType CalleeType = Callee->getType();
1689
Richard Smith254a73d2011-10-28 22:34:42 +00001690 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00001691 LValue *This = 0, ThisVal;
1692 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00001693
Richard Smithe97cbd72011-11-11 04:05:33 +00001694 // Extract function decl and 'this' pointer from the callee.
1695 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001696 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00001697 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
1698 // Explicit bound member calls, such as x.f() or p->g();
1699 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001700 return false;
1701 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00001702 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00001703 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
1704 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00001705 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
1706 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00001707 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00001708 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00001709 return Error(Callee);
1710
1711 FD = dyn_cast<FunctionDecl>(Member);
1712 if (!FD)
1713 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00001714 } else if (CalleeType->isFunctionPointerType()) {
1715 CCValue Call;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001716 if (!Evaluate(Call, Info, Callee))
1717 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00001718
Richard Smithf57d8cb2011-12-09 22:58:01 +00001719 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
1720 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00001721 FD = dyn_cast_or_null<FunctionDecl>(
1722 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00001723 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00001724 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00001725
1726 // Overloaded operator calls to member functions are represented as normal
1727 // calls with '*this' as the first argument.
1728 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1729 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001730 // FIXME: When selecting an implicit conversion for an overloaded
1731 // operator delete, we sometimes try to evaluate calls to conversion
1732 // operators without a 'this' parameter!
1733 if (Args.empty())
1734 return Error(E);
1735
Richard Smithe97cbd72011-11-11 04:05:33 +00001736 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
1737 return false;
1738 This = &ThisVal;
1739 Args = Args.slice(1);
1740 }
1741
1742 // Don't call function pointers which have been cast to some other type.
1743 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001744 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00001745 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00001746 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00001747
1748 const FunctionDecl *Definition;
1749 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00001750 CCValue CCResult;
1751 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00001752
Richard Smithf57d8cb2011-12-09 22:58:01 +00001753 if (!Body || !Definition->isConstexpr() || Definition->isInvalidDecl())
1754 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00001755
Richard Smithf57d8cb2011-12-09 22:58:01 +00001756 if (!HandleFunctionCall(E, This, Args, Body, Info, CCResult) ||
1757 !CheckConstantExpression(Info, E, CCResult, Result))
1758 return false;
1759
1760 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00001761 }
1762
Richard Smith11562c52011-10-28 17:51:58 +00001763 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1764 return StmtVisitorTy::Visit(E->getInitializer());
1765 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001766 RetTy VisitInitListExpr(const InitListExpr *E) {
1767 if (Info.getLangOpts().CPlusPlus0x) {
1768 if (E->getNumInits() == 0)
1769 return DerivedValueInitialization(E);
1770 if (E->getNumInits() == 1)
1771 return StmtVisitorTy::Visit(E->getInit(0));
1772 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001773 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00001774 }
1775 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1776 return DerivedValueInitialization(E);
1777 }
1778 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1779 return DerivedValueInitialization(E);
1780 }
Richard Smith027bf112011-11-17 22:56:20 +00001781 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
1782 return DerivedValueInitialization(E);
1783 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001784
Richard Smithd62306a2011-11-10 06:34:14 +00001785 /// A member expression where the object is a prvalue is itself a prvalue.
1786 RetTy VisitMemberExpr(const MemberExpr *E) {
1787 assert(!E->isArrow() && "missing call to bound member function?");
1788
1789 CCValue Val;
1790 if (!Evaluate(Val, Info, E->getBase()))
1791 return false;
1792
1793 QualType BaseTy = E->getBase()->getType();
1794
1795 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00001796 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00001797 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
1798 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1799 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1800
1801 SubobjectDesignator Designator;
1802 Designator.addDecl(FD);
1803
Richard Smithf57d8cb2011-12-09 22:58:01 +00001804 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00001805 DerivedSuccess(Val, E);
1806 }
1807
Richard Smith11562c52011-10-28 17:51:58 +00001808 RetTy VisitCastExpr(const CastExpr *E) {
1809 switch (E->getCastKind()) {
1810 default:
1811 break;
1812
1813 case CK_NoOp:
1814 return StmtVisitorTy::Visit(E->getSubExpr());
1815
1816 case CK_LValueToRValue: {
1817 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001818 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
1819 return false;
1820 CCValue RVal;
1821 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
1822 return false;
1823 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00001824 }
1825 }
1826
Richard Smithf57d8cb2011-12-09 22:58:01 +00001827 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00001828 }
1829
Richard Smith4a678122011-10-24 18:44:57 +00001830 /// Visit a value which is evaluated, but whose value is ignored.
1831 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001832 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00001833 if (!Evaluate(Scratch, Info, E))
1834 Info.EvalStatus.HasSideEffects = true;
1835 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001836};
1837
1838}
1839
1840//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00001841// Common base class for lvalue and temporary evaluation.
1842//===----------------------------------------------------------------------===//
1843namespace {
1844template<class Derived>
1845class LValueExprEvaluatorBase
1846 : public ExprEvaluatorBase<Derived, bool> {
1847protected:
1848 LValue &Result;
1849 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
1850 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
1851
1852 bool Success(APValue::LValueBase B) {
1853 Result.set(B);
1854 return true;
1855 }
1856
1857public:
1858 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
1859 ExprEvaluatorBaseTy(Info), Result(Result) {}
1860
1861 bool Success(const CCValue &V, const Expr *E) {
1862 Result.setFrom(V);
1863 return true;
1864 }
Richard Smith027bf112011-11-17 22:56:20 +00001865
1866 bool CheckValidLValue() {
1867 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
1868 // there are no null references, nor once-past-the-end references.
1869 // FIXME: Check for one-past-the-end array indices
1870 return Result.Base && !Result.Designator.Invalid &&
1871 !Result.Designator.OnePastTheEnd;
1872 }
1873
1874 bool VisitMemberExpr(const MemberExpr *E) {
1875 // Handle non-static data members.
1876 QualType BaseTy;
1877 if (E->isArrow()) {
1878 if (!EvaluatePointer(E->getBase(), Result, this->Info))
1879 return false;
1880 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
1881 } else {
1882 if (!this->Visit(E->getBase()))
1883 return false;
1884 BaseTy = E->getBase()->getType();
1885 }
1886 // FIXME: In C++11, require the result to be a valid lvalue.
1887
1888 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1889 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00001890 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00001891 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1892 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1893 (void)BaseTy;
1894
1895 HandleLValueMember(this->Info, Result, FD);
1896
1897 if (FD->getType()->isReferenceType()) {
1898 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001899 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00001900 RefValue))
1901 return false;
1902 return Success(RefValue, E);
1903 }
1904 return true;
1905 }
1906
1907 bool VisitBinaryOperator(const BinaryOperator *E) {
1908 switch (E->getOpcode()) {
1909 default:
1910 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
1911
1912 case BO_PtrMemD:
1913 case BO_PtrMemI:
1914 return HandleMemberPointerAccess(this->Info, E, Result);
1915 }
1916 }
1917
1918 bool VisitCastExpr(const CastExpr *E) {
1919 switch (E->getCastKind()) {
1920 default:
1921 return ExprEvaluatorBaseTy::VisitCastExpr(E);
1922
1923 case CK_DerivedToBase:
1924 case CK_UncheckedDerivedToBase: {
1925 if (!this->Visit(E->getSubExpr()))
1926 return false;
1927 if (!CheckValidLValue())
1928 return false;
1929
1930 // Now figure out the necessary offset to add to the base LV to get from
1931 // the derived class to the base class.
1932 QualType Type = E->getSubExpr()->getType();
1933
1934 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1935 PathE = E->path_end(); PathI != PathE; ++PathI) {
1936 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
1937 *PathI))
1938 return false;
1939 Type = (*PathI)->getType();
1940 }
1941
1942 return true;
1943 }
1944 }
1945 }
1946};
1947}
1948
1949//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001950// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001951//
1952// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
1953// function designators (in C), decl references to void objects (in C), and
1954// temporaries (if building with -Wno-address-of-temporary).
1955//
1956// LValue evaluation produces values comprising a base expression of one of the
1957// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00001958// - Declarations
1959// * VarDecl
1960// * FunctionDecl
1961// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00001962// * CompoundLiteralExpr in C
1963// * StringLiteral
1964// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00001965// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00001966// * ObjCEncodeExpr
1967// * AddrLabelExpr
1968// * BlockExpr
1969// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00001970// - Locals and temporaries
1971// * Any Expr, with a Frame indicating the function in which the temporary was
1972// evaluated.
1973// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00001974//===----------------------------------------------------------------------===//
1975namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001976class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00001977 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00001978public:
Richard Smith027bf112011-11-17 22:56:20 +00001979 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
1980 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001981
Richard Smith11562c52011-10-28 17:51:58 +00001982 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
1983
Peter Collingbournee9200682011-05-13 03:29:01 +00001984 bool VisitDeclRefExpr(const DeclRefExpr *E);
1985 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001986 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001987 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1988 bool VisitMemberExpr(const MemberExpr *E);
1989 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
1990 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
1991 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
1992 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001993
Peter Collingbournee9200682011-05-13 03:29:01 +00001994 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00001995 switch (E->getCastKind()) {
1996 default:
Richard Smith027bf112011-11-17 22:56:20 +00001997 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001998
Eli Friedmance3e02a2011-10-11 00:13:24 +00001999 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002000 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002001 if (!Visit(E->getSubExpr()))
2002 return false;
2003 Result.Designator.setInvalid();
2004 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002005
Richard Smith027bf112011-11-17 22:56:20 +00002006 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002007 if (!Visit(E->getSubExpr()))
2008 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002009 if (!CheckValidLValue())
2010 return false;
2011 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002012 }
2013 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00002014
Eli Friedman449fe542009-03-23 04:56:01 +00002015 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00002016
Eli Friedman9a156e52008-11-12 09:44:48 +00002017};
2018} // end anonymous namespace
2019
Richard Smith11562c52011-10-28 17:51:58 +00002020/// Evaluate an expression as an lvalue. This can be legitimately called on
2021/// expressions which are not glvalues, in a few cases:
2022/// * function designators in C,
2023/// * "extern void" objects,
2024/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002025static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002026 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2027 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2028 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002029 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002030}
2031
Peter Collingbournee9200682011-05-13 03:29:01 +00002032bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002033 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2034 return Success(FD);
2035 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002036 return VisitVarDecl(E, VD);
2037 return Error(E);
2038}
Richard Smith733237d2011-10-24 23:14:33 +00002039
Richard Smith11562c52011-10-28 17:51:58 +00002040bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002041 if (!VD->getType()->isReferenceType()) {
2042 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002043 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002044 return true;
2045 }
Richard Smithce40ad62011-11-12 22:28:03 +00002046 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002047 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002048
Richard Smith0b0a0b62011-10-29 20:57:55 +00002049 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002050 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2051 return false;
2052 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002053}
2054
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002055bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2056 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002057 if (E->GetTemporaryExpr()->isRValue()) {
2058 if (E->getType()->isRecordType() && E->getType()->isLiteralType())
2059 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2060
2061 Result.set(E, Info.CurrentCall);
2062 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2063 Result, E->GetTemporaryExpr());
2064 }
2065
2066 // Materialization of an lvalue temporary occurs when we need to force a copy
2067 // (for instance, if it's a bitfield).
2068 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2069 if (!Visit(E->GetTemporaryExpr()))
2070 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002071 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002072 Info.CurrentCall->Temporaries[E]))
2073 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002074 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002075 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002076}
2077
Peter Collingbournee9200682011-05-13 03:29:01 +00002078bool
2079LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002080 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2081 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2082 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002083 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002084}
2085
Peter Collingbournee9200682011-05-13 03:29:01 +00002086bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002087 // Handle static data members.
2088 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2089 VisitIgnoredValue(E->getBase());
2090 return VisitVarDecl(E, VD);
2091 }
2092
Richard Smith254a73d2011-10-28 22:34:42 +00002093 // Handle static member functions.
2094 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2095 if (MD->isStatic()) {
2096 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002097 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002098 }
2099 }
2100
Richard Smithd62306a2011-11-10 06:34:14 +00002101 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002102 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002103}
2104
Peter Collingbournee9200682011-05-13 03:29:01 +00002105bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002106 // FIXME: Deal with vectors as array subscript bases.
2107 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002108 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002109
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002110 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002111 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002112
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002113 APSInt Index;
2114 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002115 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002116 int64_t IndexValue
2117 = Index.isSigned() ? Index.getSExtValue()
2118 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002119
Richard Smith027bf112011-11-17 22:56:20 +00002120 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002121 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002122}
Eli Friedman9a156e52008-11-12 09:44:48 +00002123
Peter Collingbournee9200682011-05-13 03:29:01 +00002124bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002125 // FIXME: In C++11, require the result to be a valid lvalue.
John McCall45d55e42010-05-07 21:00:08 +00002126 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002127}
2128
Eli Friedman9a156e52008-11-12 09:44:48 +00002129//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002130// Pointer Evaluation
2131//===----------------------------------------------------------------------===//
2132
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002133namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002134class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002135 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002136 LValue &Result;
2137
Peter Collingbournee9200682011-05-13 03:29:01 +00002138 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002139 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002140 return true;
2141 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002142public:
Mike Stump11289f42009-09-09 15:08:12 +00002143
John McCall45d55e42010-05-07 21:00:08 +00002144 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002145 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002146
Richard Smith0b0a0b62011-10-29 20:57:55 +00002147 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002148 Result.setFrom(V);
2149 return true;
2150 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002151 bool ValueInitialization(const Expr *E) {
2152 return Success((Expr*)0);
2153 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002154
John McCall45d55e42010-05-07 21:00:08 +00002155 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002156 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002157 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002158 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002159 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002160 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002161 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002162 bool VisitCallExpr(const CallExpr *E);
2163 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002164 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002165 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002166 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002167 }
Richard Smithd62306a2011-11-10 06:34:14 +00002168 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2169 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002170 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002171 Result = *Info.CurrentCall->This;
2172 return true;
2173 }
John McCallc07a0c72011-02-17 10:25:35 +00002174
Eli Friedman449fe542009-03-23 04:56:01 +00002175 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002176};
Chris Lattner05706e882008-07-11 18:11:29 +00002177} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002178
John McCall45d55e42010-05-07 21:00:08 +00002179static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002180 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002181 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002182}
2183
John McCall45d55e42010-05-07 21:00:08 +00002184bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002185 if (E->getOpcode() != BO_Add &&
2186 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002187 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002188
Chris Lattner05706e882008-07-11 18:11:29 +00002189 const Expr *PExp = E->getLHS();
2190 const Expr *IExp = E->getRHS();
2191 if (IExp->getType()->isPointerType())
2192 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002193
John McCall45d55e42010-05-07 21:00:08 +00002194 if (!EvaluatePointer(PExp, Result, Info))
2195 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002196
John McCall45d55e42010-05-07 21:00:08 +00002197 llvm::APSInt Offset;
2198 if (!EvaluateInteger(IExp, Offset, Info))
2199 return false;
2200 int64_t AdditionalOffset
2201 = Offset.isSigned() ? Offset.getSExtValue()
2202 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002203 if (E->getOpcode() == BO_Sub)
2204 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002205
Richard Smithd62306a2011-11-10 06:34:14 +00002206 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith027bf112011-11-17 22:56:20 +00002207 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002208 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002209}
Eli Friedman9a156e52008-11-12 09:44:48 +00002210
John McCall45d55e42010-05-07 21:00:08 +00002211bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2212 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002213}
Mike Stump11289f42009-09-09 15:08:12 +00002214
Peter Collingbournee9200682011-05-13 03:29:01 +00002215bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2216 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002217
Eli Friedman847a2bc2009-12-27 05:43:15 +00002218 switch (E->getCastKind()) {
2219 default:
2220 break;
2221
John McCalle3027922010-08-25 11:45:40 +00002222 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002223 case CK_CPointerToObjCPointerCast:
2224 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002225 case CK_AnyPointerToBlockPointerCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002226 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2227 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2228 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00002229 if (!E->getType()->isVoidPointerType()) {
2230 if (SubExpr->getType()->isVoidPointerType())
2231 CCEDiag(E, diag::note_constexpr_invalid_cast)
2232 << 3 << SubExpr->getType();
2233 else
2234 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2235 }
Richard Smith96e0c102011-11-04 02:25:55 +00002236 if (!Visit(SubExpr))
2237 return false;
2238 Result.Designator.setInvalid();
2239 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002240
Anders Carlsson18275092010-10-31 20:41:46 +00002241 case CK_DerivedToBase:
2242 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002243 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002244 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002245 if (!Result.Base && Result.Offset.isZero())
2246 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002247
Richard Smithd62306a2011-11-10 06:34:14 +00002248 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002249 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002250 QualType Type =
2251 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002252
Richard Smithd62306a2011-11-10 06:34:14 +00002253 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002254 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithd62306a2011-11-10 06:34:14 +00002255 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002256 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002257 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002258 }
2259
Anders Carlsson18275092010-10-31 20:41:46 +00002260 return true;
2261 }
2262
Richard Smith027bf112011-11-17 22:56:20 +00002263 case CK_BaseToDerived:
2264 if (!Visit(E->getSubExpr()))
2265 return false;
2266 if (!Result.Base && Result.Offset.isZero())
2267 return true;
2268 return HandleBaseToDerivedCast(Info, E, Result);
2269
Richard Smith0b0a0b62011-10-29 20:57:55 +00002270 case CK_NullToPointer:
2271 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002272
John McCalle3027922010-08-25 11:45:40 +00002273 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00002274 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2275
Richard Smith0b0a0b62011-10-29 20:57:55 +00002276 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002277 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002278 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002279
John McCall45d55e42010-05-07 21:00:08 +00002280 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002281 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2282 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002283 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002284 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002285 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002286 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002287 return true;
2288 } else {
2289 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002290 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002291 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002292 }
2293 }
John McCalle3027922010-08-25 11:45:40 +00002294 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002295 if (SubExpr->isGLValue()) {
2296 if (!EvaluateLValue(SubExpr, Result, Info))
2297 return false;
2298 } else {
2299 Result.set(SubExpr, Info.CurrentCall);
2300 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2301 Info, Result, SubExpr))
2302 return false;
2303 }
Richard Smith96e0c102011-11-04 02:25:55 +00002304 // The result is a pointer to the first element of the array.
2305 Result.Designator.addIndex(0);
2306 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002307
John McCalle3027922010-08-25 11:45:40 +00002308 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002309 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002310 }
2311
Richard Smith11562c52011-10-28 17:51:58 +00002312 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002313}
Chris Lattner05706e882008-07-11 18:11:29 +00002314
Peter Collingbournee9200682011-05-13 03:29:01 +00002315bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002316 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002317 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002318
Peter Collingbournee9200682011-05-13 03:29:01 +00002319 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002320}
Chris Lattner05706e882008-07-11 18:11:29 +00002321
2322//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002323// Member Pointer Evaluation
2324//===----------------------------------------------------------------------===//
2325
2326namespace {
2327class MemberPointerExprEvaluator
2328 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2329 MemberPtr &Result;
2330
2331 bool Success(const ValueDecl *D) {
2332 Result = MemberPtr(D);
2333 return true;
2334 }
2335public:
2336
2337 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2338 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2339
2340 bool Success(const CCValue &V, const Expr *E) {
2341 Result.setFrom(V);
2342 return true;
2343 }
Richard Smith027bf112011-11-17 22:56:20 +00002344 bool ValueInitialization(const Expr *E) {
2345 return Success((const ValueDecl*)0);
2346 }
2347
2348 bool VisitCastExpr(const CastExpr *E);
2349 bool VisitUnaryAddrOf(const UnaryOperator *E);
2350};
2351} // end anonymous namespace
2352
2353static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2354 EvalInfo &Info) {
2355 assert(E->isRValue() && E->getType()->isMemberPointerType());
2356 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2357}
2358
2359bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2360 switch (E->getCastKind()) {
2361 default:
2362 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2363
2364 case CK_NullToMemberPointer:
2365 return ValueInitialization(E);
2366
2367 case CK_BaseToDerivedMemberPointer: {
2368 if (!Visit(E->getSubExpr()))
2369 return false;
2370 if (E->path_empty())
2371 return true;
2372 // Base-to-derived member pointer casts store the path in derived-to-base
2373 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2374 // the wrong end of the derived->base arc, so stagger the path by one class.
2375 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2376 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2377 PathI != PathE; ++PathI) {
2378 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2379 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2380 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002381 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002382 }
2383 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2384 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002385 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002386 return true;
2387 }
2388
2389 case CK_DerivedToBaseMemberPointer:
2390 if (!Visit(E->getSubExpr()))
2391 return false;
2392 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2393 PathE = E->path_end(); PathI != PathE; ++PathI) {
2394 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2395 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2396 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002397 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002398 }
2399 return true;
2400 }
2401}
2402
2403bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2404 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2405 // member can be formed.
2406 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2407}
2408
2409//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002410// Record Evaluation
2411//===----------------------------------------------------------------------===//
2412
2413namespace {
2414 class RecordExprEvaluator
2415 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2416 const LValue &This;
2417 APValue &Result;
2418 public:
2419
2420 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2421 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2422
2423 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002424 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002425 }
Richard Smithd62306a2011-11-10 06:34:14 +00002426
Richard Smithe97cbd72011-11-11 04:05:33 +00002427 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002428 bool VisitInitListExpr(const InitListExpr *E);
2429 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2430 };
2431}
2432
Richard Smithe97cbd72011-11-11 04:05:33 +00002433bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2434 switch (E->getCastKind()) {
2435 default:
2436 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2437
2438 case CK_ConstructorConversion:
2439 return Visit(E->getSubExpr());
2440
2441 case CK_DerivedToBase:
2442 case CK_UncheckedDerivedToBase: {
2443 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002444 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002445 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002446 if (!DerivedObject.isStruct())
2447 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00002448
2449 // Derived-to-base rvalue conversion: just slice off the derived part.
2450 APValue *Value = &DerivedObject;
2451 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2452 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2453 PathE = E->path_end(); PathI != PathE; ++PathI) {
2454 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2455 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2456 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2457 RD = Base;
2458 }
2459 Result = *Value;
2460 return true;
2461 }
2462 }
2463}
2464
Richard Smithd62306a2011-11-10 06:34:14 +00002465bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2466 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2467 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2468
2469 if (RD->isUnion()) {
2470 Result = APValue(E->getInitializedFieldInUnion());
2471 if (!E->getNumInits())
2472 return true;
2473 LValue Subobject = This;
2474 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2475 &Layout);
2476 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2477 Subobject, E->getInit(0));
2478 }
2479
2480 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2481 "initializer list for class with base classes");
2482 Result = APValue(APValue::UninitStruct(), 0,
2483 std::distance(RD->field_begin(), RD->field_end()));
2484 unsigned ElementNo = 0;
2485 for (RecordDecl::field_iterator Field = RD->field_begin(),
2486 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2487 // Anonymous bit-fields are not considered members of the class for
2488 // purposes of aggregate initialization.
2489 if (Field->isUnnamedBitfield())
2490 continue;
2491
2492 LValue Subobject = This;
2493 HandleLValueMember(Info, Subobject, *Field, &Layout);
2494
2495 if (ElementNo < E->getNumInits()) {
2496 if (!EvaluateConstantExpression(
2497 Result.getStructField((*Field)->getFieldIndex()),
2498 Info, Subobject, E->getInit(ElementNo++)))
2499 return false;
2500 } else {
2501 // Perform an implicit value-initialization for members beyond the end of
2502 // the initializer list.
2503 ImplicitValueInitExpr VIE(Field->getType());
2504 if (!EvaluateConstantExpression(
2505 Result.getStructField((*Field)->getFieldIndex()),
2506 Info, Subobject, &VIE))
2507 return false;
2508 }
2509 }
2510
2511 return true;
2512}
2513
2514bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2515 const CXXConstructorDecl *FD = E->getConstructor();
2516 const FunctionDecl *Definition = 0;
2517 FD->getBody(Definition);
2518
2519 if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002520 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002521
2522 // FIXME: Elide the copy/move construction wherever we can.
2523 if (E->isElidable())
2524 if (const MaterializeTemporaryExpr *ME
2525 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2526 return Visit(ME->GetTemporaryExpr());
2527
2528 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002529 return HandleConstructorCall(E, This, Args,
2530 cast<CXXConstructorDecl>(Definition), Info,
2531 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002532}
2533
2534static bool EvaluateRecord(const Expr *E, const LValue &This,
2535 APValue &Result, EvalInfo &Info) {
2536 assert(E->isRValue() && E->getType()->isRecordType() &&
2537 E->getType()->isLiteralType() &&
2538 "can't evaluate expression as a record rvalue");
2539 return RecordExprEvaluator(Info, This, Result).Visit(E);
2540}
2541
2542//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002543// Temporary Evaluation
2544//
2545// Temporaries are represented in the AST as rvalues, but generally behave like
2546// lvalues. The full-object of which the temporary is a subobject is implicitly
2547// materialized so that a reference can bind to it.
2548//===----------------------------------------------------------------------===//
2549namespace {
2550class TemporaryExprEvaluator
2551 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
2552public:
2553 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
2554 LValueExprEvaluatorBaseTy(Info, Result) {}
2555
2556 /// Visit an expression which constructs the value of this temporary.
2557 bool VisitConstructExpr(const Expr *E) {
2558 Result.set(E, Info.CurrentCall);
2559 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2560 Result, E);
2561 }
2562
2563 bool VisitCastExpr(const CastExpr *E) {
2564 switch (E->getCastKind()) {
2565 default:
2566 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2567
2568 case CK_ConstructorConversion:
2569 return VisitConstructExpr(E->getSubExpr());
2570 }
2571 }
2572 bool VisitInitListExpr(const InitListExpr *E) {
2573 return VisitConstructExpr(E);
2574 }
2575 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2576 return VisitConstructExpr(E);
2577 }
2578 bool VisitCallExpr(const CallExpr *E) {
2579 return VisitConstructExpr(E);
2580 }
2581};
2582} // end anonymous namespace
2583
2584/// Evaluate an expression of record type as a temporary.
2585static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
2586 assert(E->isRValue() && E->getType()->isRecordType() &&
2587 E->getType()->isLiteralType());
2588 return TemporaryExprEvaluator(Info, Result).Visit(E);
2589}
2590
2591//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002592// Vector Evaluation
2593//===----------------------------------------------------------------------===//
2594
2595namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002596 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00002597 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
2598 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002599 public:
Mike Stump11289f42009-09-09 15:08:12 +00002600
Richard Smith2d406342011-10-22 21:10:00 +00002601 VectorExprEvaluator(EvalInfo &info, APValue &Result)
2602 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002603
Richard Smith2d406342011-10-22 21:10:00 +00002604 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
2605 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
2606 // FIXME: remove this APValue copy.
2607 Result = APValue(V.data(), V.size());
2608 return true;
2609 }
Richard Smithed5165f2011-11-04 05:33:44 +00002610 bool Success(const CCValue &V, const Expr *E) {
2611 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00002612 Result = V;
2613 return true;
2614 }
Richard Smith2d406342011-10-22 21:10:00 +00002615 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002616
Richard Smith2d406342011-10-22 21:10:00 +00002617 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00002618 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00002619 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00002620 bool VisitInitListExpr(const InitListExpr *E);
2621 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002622 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00002623 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00002624 // shufflevector, ExtVectorElementExpr
2625 // (Note that these require implementing conversions
2626 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002627 };
2628} // end anonymous namespace
2629
2630static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002631 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00002632 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002633}
2634
Richard Smith2d406342011-10-22 21:10:00 +00002635bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2636 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002637 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002638
Richard Smith161f09a2011-12-06 22:44:34 +00002639 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00002640 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002641
Eli Friedmanc757de22011-03-25 00:43:55 +00002642 switch (E->getCastKind()) {
2643 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00002644 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00002645 if (SETy->isIntegerType()) {
2646 APSInt IntResult;
2647 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002648 return false;
Richard Smith2d406342011-10-22 21:10:00 +00002649 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00002650 } else if (SETy->isRealFloatingType()) {
2651 APFloat F(0.0);
2652 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002653 return false;
Richard Smith2d406342011-10-22 21:10:00 +00002654 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00002655 } else {
Richard Smith2d406342011-10-22 21:10:00 +00002656 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002657 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002658
2659 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00002660 SmallVector<APValue, 4> Elts(NElts, Val);
2661 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00002662 }
Eli Friedmanc757de22011-03-25 00:43:55 +00002663 default:
Richard Smith11562c52011-10-28 17:51:58 +00002664 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002665 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002666}
2667
Richard Smith2d406342011-10-22 21:10:00 +00002668bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002669VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00002670 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002671 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00002672 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002673
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002674 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002675 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002676
John McCall875679e2010-06-11 17:54:15 +00002677 // If a vector is initialized with a single element, that value
2678 // becomes every element of the vector, not just the first.
2679 // This is the behavior described in the IBM AltiVec documentation.
2680 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00002681
2682 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00002683 // vector (OpenCL 6.1.6).
2684 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00002685 return Visit(E->getInit(0));
2686
John McCall875679e2010-06-11 17:54:15 +00002687 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002688 if (EltTy->isIntegerType()) {
2689 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00002690 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002691 return false;
John McCall875679e2010-06-11 17:54:15 +00002692 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002693 } else {
2694 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00002695 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002696 return false;
John McCall875679e2010-06-11 17:54:15 +00002697 InitValue = APValue(f);
2698 }
2699 for (unsigned i = 0; i < NumElements; i++) {
2700 Elements.push_back(InitValue);
2701 }
2702 } else {
2703 for (unsigned i = 0; i < NumElements; i++) {
2704 if (EltTy->isIntegerType()) {
2705 llvm::APSInt sInt(32);
2706 if (i < NumInits) {
2707 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002708 return false;
John McCall875679e2010-06-11 17:54:15 +00002709 } else {
2710 sInt = Info.Ctx.MakeIntValue(0, EltTy);
2711 }
2712 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00002713 } else {
John McCall875679e2010-06-11 17:54:15 +00002714 llvm::APFloat f(0.0);
2715 if (i < NumInits) {
2716 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002717 return false;
John McCall875679e2010-06-11 17:54:15 +00002718 } else {
2719 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
2720 }
2721 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00002722 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002723 }
2724 }
Richard Smith2d406342011-10-22 21:10:00 +00002725 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002726}
2727
Richard Smith2d406342011-10-22 21:10:00 +00002728bool
2729VectorExprEvaluator::ValueInitialization(const Expr *E) {
2730 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00002731 QualType EltTy = VT->getElementType();
2732 APValue ZeroElement;
2733 if (EltTy->isIntegerType())
2734 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
2735 else
2736 ZeroElement =
2737 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
2738
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002739 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00002740 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002741}
2742
Richard Smith2d406342011-10-22 21:10:00 +00002743bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00002744 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00002745 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002746}
2747
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002748//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00002749// Array Evaluation
2750//===----------------------------------------------------------------------===//
2751
2752namespace {
2753 class ArrayExprEvaluator
2754 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00002755 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00002756 APValue &Result;
2757 public:
2758
Richard Smithd62306a2011-11-10 06:34:14 +00002759 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
2760 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00002761
2762 bool Success(const APValue &V, const Expr *E) {
2763 assert(V.isArray() && "Expected array type");
2764 Result = V;
2765 return true;
2766 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002767
Richard Smithd62306a2011-11-10 06:34:14 +00002768 bool ValueInitialization(const Expr *E) {
2769 const ConstantArrayType *CAT =
2770 Info.Ctx.getAsConstantArrayType(E->getType());
2771 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002772 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002773
2774 Result = APValue(APValue::UninitArray(), 0,
2775 CAT->getSize().getZExtValue());
2776 if (!Result.hasArrayFiller()) return true;
2777
2778 // Value-initialize all elements.
2779 LValue Subobject = This;
2780 Subobject.Designator.addIndex(0);
2781 ImplicitValueInitExpr VIE(CAT->getElementType());
2782 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
2783 Subobject, &VIE);
2784 }
2785
Richard Smithf3e9e432011-11-07 09:22:26 +00002786 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00002787 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002788 };
2789} // end anonymous namespace
2790
Richard Smithd62306a2011-11-10 06:34:14 +00002791static bool EvaluateArray(const Expr *E, const LValue &This,
2792 APValue &Result, EvalInfo &Info) {
Richard Smithf3e9e432011-11-07 09:22:26 +00002793 assert(E->isRValue() && E->getType()->isArrayType() &&
2794 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00002795 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002796}
2797
2798bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2799 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2800 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002801 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002802
2803 Result = APValue(APValue::UninitArray(), E->getNumInits(),
2804 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00002805 LValue Subobject = This;
2806 Subobject.Designator.addIndex(0);
2807 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00002808 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00002809 I != End; ++I, ++Index) {
2810 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
2811 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00002812 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002813 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
2814 return false;
2815 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002816
2817 if (!Result.hasArrayFiller()) return true;
2818 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00002819 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
2820 // but sometimes does:
2821 // struct S { constexpr S() : p(&p) {} void *p; };
2822 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00002823 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00002824 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00002825}
2826
Richard Smith027bf112011-11-17 22:56:20 +00002827bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2828 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2829 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002830 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002831
2832 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
2833 if (!Result.hasArrayFiller())
2834 return true;
2835
2836 const CXXConstructorDecl *FD = E->getConstructor();
2837 const FunctionDecl *Definition = 0;
2838 FD->getBody(Definition);
2839
2840 if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002841 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002842
2843 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
2844 // but sometimes does:
2845 // struct S { constexpr S() : p(&p) {} void *p; };
2846 // S s[10];
2847 LValue Subobject = This;
2848 Subobject.Designator.addIndex(0);
2849 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002850 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00002851 cast<CXXConstructorDecl>(Definition),
2852 Info, Result.getArrayFiller());
2853}
2854
Richard Smithf3e9e432011-11-07 09:22:26 +00002855//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002856// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002857//
2858// As a GNU extension, we support casting pointers to sufficiently-wide integer
2859// types and back in constant folding. Integer values are thus represented
2860// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00002861//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002862
2863namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002864class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002865 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002866 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002867public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00002868 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002869 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002870
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002871 bool Success(const llvm::APSInt &SI, const Expr *E) {
2872 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002873 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002874 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002875 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002876 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002877 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00002878 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002879 return true;
2880 }
2881
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002882 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00002883 assert(E->getType()->isIntegralOrEnumerationType() &&
2884 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002885 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002886 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00002887 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002888 Result.getInt().setIsUnsigned(
2889 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002890 return true;
2891 }
2892
2893 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00002894 assert(E->getType()->isIntegralOrEnumerationType() &&
2895 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00002896 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002897 return true;
2898 }
2899
Ken Dyckdbc01912011-03-11 02:13:43 +00002900 bool Success(CharUnits Size, const Expr *E) {
2901 return Success(Size.getQuantity(), E);
2902 }
2903
Richard Smith0b0a0b62011-10-29 20:57:55 +00002904 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00002905 if (V.isLValue()) {
2906 Result = V;
2907 return true;
2908 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002909 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002910 }
Mike Stump11289f42009-09-09 15:08:12 +00002911
Richard Smith4ce706a2011-10-11 21:43:33 +00002912 bool ValueInitialization(const Expr *E) { return Success(0, E); }
2913
Peter Collingbournee9200682011-05-13 03:29:01 +00002914 //===--------------------------------------------------------------------===//
2915 // Visitor Methods
2916 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002917
Chris Lattner7174bf32008-07-12 00:38:25 +00002918 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002919 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00002920 }
2921 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002922 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00002923 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002924
2925 bool CheckReferencedDecl(const Expr *E, const Decl *D);
2926 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002927 if (CheckReferencedDecl(E, E->getDecl()))
2928 return true;
2929
2930 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002931 }
2932 bool VisitMemberExpr(const MemberExpr *E) {
2933 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00002934 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002935 return true;
2936 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002937
2938 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002939 }
2940
Peter Collingbournee9200682011-05-13 03:29:01 +00002941 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00002942 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00002943 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00002944 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00002945
Peter Collingbournee9200682011-05-13 03:29:01 +00002946 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002947 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00002948
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002949 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002950 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002951 }
Mike Stump11289f42009-09-09 15:08:12 +00002952
Richard Smith4ce706a2011-10-11 21:43:33 +00002953 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00002954 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002955 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00002956 }
2957
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002958 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002959 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002960 }
2961
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002962 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
2963 return Success(E->getValue(), E);
2964 }
2965
John Wiegley6242b6a2011-04-28 00:16:57 +00002966 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2967 return Success(E->getValue(), E);
2968 }
2969
John Wiegleyf9f65842011-04-25 06:54:41 +00002970 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2971 return Success(E->getValue(), E);
2972 }
2973
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002974 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00002975 bool VisitUnaryImag(const UnaryOperator *E);
2976
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002977 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002978 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002979
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002980private:
Ken Dyck160146e2010-01-27 17:10:57 +00002981 CharUnits GetAlignOfExpr(const Expr *E);
2982 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00002983 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00002984 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00002985 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00002986};
Chris Lattner05706e882008-07-11 18:11:29 +00002987} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002988
Richard Smith11562c52011-10-28 17:51:58 +00002989/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
2990/// produce either the integer value or a pointer.
2991///
2992/// GCC has a heinous extension which folds casts between pointer types and
2993/// pointer-sized integral types. We support this by allowing the evaluation of
2994/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
2995/// Some simple arithmetic on such values is supported (they are treated much
2996/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00002997static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00002998 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002999 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003000 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00003001}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003002
Richard Smithf57d8cb2011-12-09 22:58:01 +00003003static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003004 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003005 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00003006 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003007 if (!Val.isInt()) {
3008 // FIXME: It would be better to produce the diagnostic for casting
3009 // a pointer to an integer.
Richard Smith92b1ce02011-12-12 09:28:41 +00003010 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003011 return false;
3012 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003013 Result = Val.getInt();
3014 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003015}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003016
Richard Smithf57d8cb2011-12-09 22:58:01 +00003017/// Check whether the given declaration can be directly converted to an integral
3018/// rvalue. If not, no diagnostic is produced; there are other things we can
3019/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003020bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003021 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003022 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003023 // Check for signedness/width mismatches between E type and ECD value.
3024 bool SameSign = (ECD->getInitVal().isSigned()
3025 == E->getType()->isSignedIntegerOrEnumerationType());
3026 bool SameWidth = (ECD->getInitVal().getBitWidth()
3027 == Info.Ctx.getIntWidth(E->getType()));
3028 if (SameSign && SameWidth)
3029 return Success(ECD->getInitVal(), E);
3030 else {
3031 // Get rid of mismatch (otherwise Success assertions will fail)
3032 // by computing a new value matching the type of E.
3033 llvm::APSInt Val = ECD->getInitVal();
3034 if (!SameSign)
3035 Val.setIsSigned(!ECD->getInitVal().isSigned());
3036 if (!SameWidth)
3037 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3038 return Success(Val, E);
3039 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003040 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003041 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003042}
3043
Chris Lattner86ee2862008-10-06 06:40:35 +00003044/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3045/// as GCC.
3046static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3047 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003048 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003049 enum gcc_type_class {
3050 no_type_class = -1,
3051 void_type_class, integer_type_class, char_type_class,
3052 enumeral_type_class, boolean_type_class,
3053 pointer_type_class, reference_type_class, offset_type_class,
3054 real_type_class, complex_type_class,
3055 function_type_class, method_type_class,
3056 record_type_class, union_type_class,
3057 array_type_class, string_type_class,
3058 lang_type_class
3059 };
Mike Stump11289f42009-09-09 15:08:12 +00003060
3061 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003062 // ideal, however it is what gcc does.
3063 if (E->getNumArgs() == 0)
3064 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003065
Chris Lattner86ee2862008-10-06 06:40:35 +00003066 QualType ArgTy = E->getArg(0)->getType();
3067 if (ArgTy->isVoidType())
3068 return void_type_class;
3069 else if (ArgTy->isEnumeralType())
3070 return enumeral_type_class;
3071 else if (ArgTy->isBooleanType())
3072 return boolean_type_class;
3073 else if (ArgTy->isCharType())
3074 return string_type_class; // gcc doesn't appear to use char_type_class
3075 else if (ArgTy->isIntegerType())
3076 return integer_type_class;
3077 else if (ArgTy->isPointerType())
3078 return pointer_type_class;
3079 else if (ArgTy->isReferenceType())
3080 return reference_type_class;
3081 else if (ArgTy->isRealType())
3082 return real_type_class;
3083 else if (ArgTy->isComplexType())
3084 return complex_type_class;
3085 else if (ArgTy->isFunctionType())
3086 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003087 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003088 return record_type_class;
3089 else if (ArgTy->isUnionType())
3090 return union_type_class;
3091 else if (ArgTy->isArrayType())
3092 return array_type_class;
3093 else if (ArgTy->isUnionType())
3094 return union_type_class;
3095 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003096 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003097 return -1;
3098}
3099
John McCall95007602010-05-10 23:27:23 +00003100/// Retrieves the "underlying object type" of the given expression,
3101/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003102QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3103 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3104 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003105 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003106 } else if (const Expr *E = B.get<const Expr*>()) {
3107 if (isa<CompoundLiteralExpr>(E))
3108 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003109 }
3110
3111 return QualType();
3112}
3113
Peter Collingbournee9200682011-05-13 03:29:01 +00003114bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003115 // TODO: Perhaps we should let LLVM lower this?
3116 LValue Base;
3117 if (!EvaluatePointer(E->getArg(0), Base, Info))
3118 return false;
3119
3120 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003121 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003122
Richard Smithce40ad62011-11-12 22:28:03 +00003123 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003124 if (T.isNull() ||
3125 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003126 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003127 T->isVariablyModifiedType() ||
3128 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003129 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003130
3131 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3132 CharUnits Offset = Base.getLValueOffset();
3133
3134 if (!Offset.isNegative() && Offset <= Size)
3135 Size -= Offset;
3136 else
3137 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003138 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003139}
3140
Peter Collingbournee9200682011-05-13 03:29:01 +00003141bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003142 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003143 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003144 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003145
3146 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003147 if (TryEvaluateBuiltinObjectSize(E))
3148 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003149
Eric Christopher99469702010-01-19 22:58:35 +00003150 // If evaluating the argument has side-effects we can't determine
3151 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003152 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003153 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003154 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003155 return Success(0, E);
3156 }
Mike Stump876387b2009-10-27 22:09:17 +00003157
Richard Smithf57d8cb2011-12-09 22:58:01 +00003158 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003159 }
3160
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003161 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003162 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003163
Richard Smith10c7c902011-12-09 02:04:48 +00003164 case Builtin::BI__builtin_constant_p: {
3165 const Expr *Arg = E->getArg(0);
3166 QualType ArgType = Arg->getType();
3167 // __builtin_constant_p always has one operand. The rules which gcc follows
3168 // are not precisely documented, but are as follows:
3169 //
3170 // - If the operand is of integral, floating, complex or enumeration type,
3171 // and can be folded to a known value of that type, it returns 1.
3172 // - If the operand and can be folded to a pointer to the first character
3173 // of a string literal (or such a pointer cast to an integral type), it
3174 // returns 1.
3175 //
3176 // Otherwise, it returns 0.
3177 //
3178 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3179 // its support for this does not currently work.
3180 int IsConstant = 0;
3181 if (ArgType->isIntegralOrEnumerationType()) {
3182 // Note, a pointer cast to an integral type is only a constant if it is
3183 // a pointer to the first character of a string literal.
3184 Expr::EvalResult Result;
3185 if (Arg->EvaluateAsRValue(Result, Info.Ctx) && !Result.HasSideEffects) {
3186 APValue &V = Result.Val;
3187 if (V.getKind() == APValue::LValue) {
3188 if (const Expr *E = V.getLValueBase().dyn_cast<const Expr*>())
3189 IsConstant = isa<StringLiteral>(E) && V.getLValueOffset().isZero();
3190 } else {
3191 IsConstant = 1;
3192 }
3193 }
3194 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3195 IsConstant = Arg->isEvaluatable(Info.Ctx);
3196 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3197 LValue LV;
3198 // Use a separate EvalInfo: ignore constexpr parameter and 'this' bindings
3199 // during the check.
3200 Expr::EvalStatus Status;
3201 EvalInfo SubInfo(Info.Ctx, Status);
3202 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, SubInfo)
3203 : EvaluatePointer(Arg, LV, SubInfo)) &&
3204 !Status.HasSideEffects)
3205 if (const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>())
3206 IsConstant = isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3207 }
3208
3209 return Success(IsConstant, E);
3210 }
Chris Lattnerd545ad12009-09-23 06:06:36 +00003211 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003212 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003213 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003214 return Success(Operand, E);
3215 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003216
3217 case Builtin::BI__builtin_expect:
3218 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003219
3220 case Builtin::BIstrlen:
3221 case Builtin::BI__builtin_strlen:
3222 // As an extension, we support strlen() and __builtin_strlen() as constant
3223 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003224 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003225 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3226 // The string literal may have embedded null characters. Find the first
3227 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003228 StringRef Str = S->getString();
3229 StringRef::size_type Pos = Str.find(0);
3230 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003231 Str = Str.substr(0, Pos);
3232
3233 return Success(Str.size(), E);
3234 }
3235
Richard Smithf57d8cb2011-12-09 22:58:01 +00003236 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003237
3238 case Builtin::BI__atomic_is_lock_free: {
3239 APSInt SizeVal;
3240 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3241 return false;
3242
3243 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3244 // of two less than the maximum inline atomic width, we know it is
3245 // lock-free. If the size isn't a power of two, or greater than the
3246 // maximum alignment where we promote atomics, we know it is not lock-free
3247 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3248 // the answer can only be determined at runtime; for example, 16-byte
3249 // atomics have lock-free implementations on some, but not all,
3250 // x86-64 processors.
3251
3252 // Check power-of-two.
3253 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3254 if (!Size.isPowerOfTwo())
3255#if 0
3256 // FIXME: Suppress this folding until the ABI for the promotion width
3257 // settles.
3258 return Success(0, E);
3259#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003260 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003261#endif
3262
3263#if 0
3264 // Check against promotion width.
3265 // FIXME: Suppress this folding until the ABI for the promotion width
3266 // settles.
3267 unsigned PromoteWidthBits =
3268 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3269 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3270 return Success(0, E);
3271#endif
3272
3273 // Check against inlining width.
3274 unsigned InlineWidthBits =
3275 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3276 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3277 return Success(1, E);
3278
Richard Smithf57d8cb2011-12-09 22:58:01 +00003279 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003280 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003281 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003282}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003283
Richard Smith8b3497e2011-10-31 01:37:14 +00003284static bool HasSameBase(const LValue &A, const LValue &B) {
3285 if (!A.getLValueBase())
3286 return !B.getLValueBase();
3287 if (!B.getLValueBase())
3288 return false;
3289
Richard Smithce40ad62011-11-12 22:28:03 +00003290 if (A.getLValueBase().getOpaqueValue() !=
3291 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003292 const Decl *ADecl = GetLValueBaseDecl(A);
3293 if (!ADecl)
3294 return false;
3295 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003296 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003297 return false;
3298 }
3299
3300 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003301 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003302}
3303
Chris Lattnere13042c2008-07-11 19:10:17 +00003304bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003305 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003306 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003307
John McCalle3027922010-08-25 11:45:40 +00003308 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003309 VisitIgnoredValue(E->getLHS());
3310 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003311 }
3312
3313 if (E->isLogicalOp()) {
3314 // These need to be handled specially because the operands aren't
3315 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003316 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003317
Richard Smith11562c52011-10-28 17:51:58 +00003318 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003319 // We were able to evaluate the LHS, see if we can get away with not
3320 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003321 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003322 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003323
Richard Smith11562c52011-10-28 17:51:58 +00003324 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003325 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003326 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003327 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003328 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003329 }
3330 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003331 // FIXME: If both evaluations fail, we should produce the diagnostic from
3332 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3333 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003334 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003335 // We can't evaluate the LHS; however, sometimes the result
3336 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003337 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003338 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003339 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00003340 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003341
3342 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003343 }
3344 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00003345 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00003346
Eli Friedman5a332ea2008-11-13 06:09:17 +00003347 return false;
3348 }
3349
Anders Carlssonacc79812008-11-16 07:17:21 +00003350 QualType LHSTy = E->getLHS()->getType();
3351 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003352
3353 if (LHSTy->isAnyComplexType()) {
3354 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00003355 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003356
3357 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3358 return false;
3359
3360 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3361 return false;
3362
3363 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00003364 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003365 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00003366 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003367 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3368
John McCalle3027922010-08-25 11:45:40 +00003369 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003370 return Success((CR_r == APFloat::cmpEqual &&
3371 CR_i == APFloat::cmpEqual), E);
3372 else {
John McCalle3027922010-08-25 11:45:40 +00003373 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003374 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00003375 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003376 CR_r == APFloat::cmpLessThan ||
3377 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00003378 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003379 CR_i == APFloat::cmpLessThan ||
3380 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003381 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003382 } else {
John McCalle3027922010-08-25 11:45:40 +00003383 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003384 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3385 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3386 else {
John McCalle3027922010-08-25 11:45:40 +00003387 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003388 "Invalid compex comparison.");
3389 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3390 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3391 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003392 }
3393 }
Mike Stump11289f42009-09-09 15:08:12 +00003394
Anders Carlssonacc79812008-11-16 07:17:21 +00003395 if (LHSTy->isRealFloatingType() &&
3396 RHSTy->isRealFloatingType()) {
3397 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00003398
Anders Carlssonacc79812008-11-16 07:17:21 +00003399 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3400 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003401
Anders Carlssonacc79812008-11-16 07:17:21 +00003402 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3403 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003404
Anders Carlssonacc79812008-11-16 07:17:21 +00003405 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00003406
Anders Carlssonacc79812008-11-16 07:17:21 +00003407 switch (E->getOpcode()) {
3408 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003409 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00003410 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003411 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00003412 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003413 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00003414 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003415 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003416 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00003417 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003418 E);
John McCalle3027922010-08-25 11:45:40 +00003419 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003420 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003421 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00003422 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00003423 || CR == APFloat::cmpLessThan
3424 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00003425 }
Anders Carlssonacc79812008-11-16 07:17:21 +00003426 }
Mike Stump11289f42009-09-09 15:08:12 +00003427
Eli Friedmana38da572009-04-28 19:17:36 +00003428 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003429 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00003430 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003431 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3432 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003433
John McCall45d55e42010-05-07 21:00:08 +00003434 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003435 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3436 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003437
Richard Smith8b3497e2011-10-31 01:37:14 +00003438 // Reject differing bases from the normal codepath; we special-case
3439 // comparisons to null.
3440 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00003441 // Inequalities and subtractions between unrelated pointers have
3442 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00003443 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003444 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003445 // A constant address may compare equal to the address of a symbol.
3446 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00003447 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003448 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3449 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003450 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003451 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00003452 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00003453 // distinct. However, we do know that the address of a literal will be
3454 // non-null.
3455 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
3456 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003457 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003458 // We can't tell whether weak symbols will end up pointing to the same
3459 // object.
3460 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003461 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003462 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00003463 // (Note that clang defaults to -fmerge-all-constants, which can
3464 // lead to inconsistent results for comparisons involving the address
3465 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00003466 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00003467 }
Eli Friedman64004332009-03-23 04:38:34 +00003468
Richard Smithf3e9e432011-11-07 09:22:26 +00003469 // FIXME: Implement the C++11 restrictions:
3470 // - Pointer subtractions must be on elements of the same array.
3471 // - Pointer comparisons must be between members with the same access.
3472
John McCalle3027922010-08-25 11:45:40 +00003473 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00003474 QualType Type = E->getLHS()->getType();
3475 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003476
Richard Smithd62306a2011-11-10 06:34:14 +00003477 CharUnits ElementSize;
3478 if (!HandleSizeof(Info, ElementType, ElementSize))
3479 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003480
Richard Smithd62306a2011-11-10 06:34:14 +00003481 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00003482 RHSValue.getLValueOffset();
3483 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003484 }
Richard Smith8b3497e2011-10-31 01:37:14 +00003485
3486 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
3487 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
3488 switch (E->getOpcode()) {
3489 default: llvm_unreachable("missing comparison operator");
3490 case BO_LT: return Success(LHSOffset < RHSOffset, E);
3491 case BO_GT: return Success(LHSOffset > RHSOffset, E);
3492 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
3493 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
3494 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
3495 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003496 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003497 }
3498 }
Douglas Gregorb90df602010-06-16 00:17:44 +00003499 if (!LHSTy->isIntegralOrEnumerationType() ||
3500 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00003501 // We can't continue from here for non-integral types.
3502 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003503 }
3504
Anders Carlsson9c181652008-07-08 14:35:21 +00003505 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00003506 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00003507 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003508 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00003509
Richard Smith11562c52011-10-28 17:51:58 +00003510 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003511 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003512 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00003513
3514 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00003515 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00003516 CharUnits AdditionalOffset = CharUnits::fromQuantity(
3517 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00003518 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00003519 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00003520 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00003521 LHSVal.getLValueOffset() -= AdditionalOffset;
3522 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00003523 return true;
3524 }
3525
3526 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00003527 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00003528 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003529 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
3530 LHSVal.getInt().getZExtValue());
3531 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00003532 return true;
3533 }
3534
3535 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00003536 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003537 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003538
Richard Smith11562c52011-10-28 17:51:58 +00003539 APSInt &LHS = LHSVal.getInt();
3540 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00003541
Anders Carlsson9c181652008-07-08 14:35:21 +00003542 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003543 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003544 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003545 case BO_Mul: return Success(LHS * RHS, E);
3546 case BO_Add: return Success(LHS + RHS, E);
3547 case BO_Sub: return Success(LHS - RHS, E);
3548 case BO_And: return Success(LHS & RHS, E);
3549 case BO_Xor: return Success(LHS ^ RHS, E);
3550 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003551 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00003552 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003553 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00003554 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003555 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00003556 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003557 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00003558 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003559 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00003560 // During constant-folding, a negative shift is an opposite shift.
3561 if (RHS.isSigned() && RHS.isNegative()) {
3562 RHS = -RHS;
3563 goto shift_right;
3564 }
3565
3566 shift_left:
3567 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00003568 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3569 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003570 }
John McCalle3027922010-08-25 11:45:40 +00003571 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00003572 // During constant-folding, a negative shift is an opposite shift.
3573 if (RHS.isSigned() && RHS.isNegative()) {
3574 RHS = -RHS;
3575 goto shift_left;
3576 }
3577
3578 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00003579 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00003580 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3581 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003582 }
Mike Stump11289f42009-09-09 15:08:12 +00003583
Richard Smith11562c52011-10-28 17:51:58 +00003584 case BO_LT: return Success(LHS < RHS, E);
3585 case BO_GT: return Success(LHS > RHS, E);
3586 case BO_LE: return Success(LHS <= RHS, E);
3587 case BO_GE: return Success(LHS >= RHS, E);
3588 case BO_EQ: return Success(LHS == RHS, E);
3589 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00003590 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003591}
3592
Ken Dyck160146e2010-01-27 17:10:57 +00003593CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003594 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3595 // the result is the size of the referenced type."
3596 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3597 // result shall be the alignment of the referenced type."
3598 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3599 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00003600
3601 // __alignof is defined to return the preferred alignment.
3602 return Info.Ctx.toCharUnitsFromBits(
3603 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00003604}
3605
Ken Dyck160146e2010-01-27 17:10:57 +00003606CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00003607 E = E->IgnoreParens();
3608
3609 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00003610 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00003611 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003612 return Info.Ctx.getDeclAlign(DRE->getDecl(),
3613 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00003614
Chris Lattner68061312009-01-24 21:53:27 +00003615 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003616 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
3617 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00003618
Chris Lattner24aeeab2009-01-24 21:09:06 +00003619 return GetAlignOfType(E->getType());
3620}
3621
3622
Peter Collingbournee190dee2011-03-11 19:24:49 +00003623/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
3624/// a result as the expression's type.
3625bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
3626 const UnaryExprOrTypeTraitExpr *E) {
3627 switch(E->getKind()) {
3628 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00003629 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00003630 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003631 else
Ken Dyckdbc01912011-03-11 02:13:43 +00003632 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003633 }
Eli Friedman64004332009-03-23 04:38:34 +00003634
Peter Collingbournee190dee2011-03-11 19:24:49 +00003635 case UETT_VecStep: {
3636 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00003637
Peter Collingbournee190dee2011-03-11 19:24:49 +00003638 if (Ty->isVectorType()) {
3639 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00003640
Peter Collingbournee190dee2011-03-11 19:24:49 +00003641 // The vec_step built-in functions that take a 3-component
3642 // vector return 4. (OpenCL 1.1 spec 6.11.12)
3643 if (n == 3)
3644 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00003645
Peter Collingbournee190dee2011-03-11 19:24:49 +00003646 return Success(n, E);
3647 } else
3648 return Success(1, E);
3649 }
3650
3651 case UETT_SizeOf: {
3652 QualType SrcTy = E->getTypeOfArgument();
3653 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3654 // the result is the size of the referenced type."
3655 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3656 // result shall be the alignment of the referenced type."
3657 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
3658 SrcTy = Ref->getPointeeType();
3659
Richard Smithd62306a2011-11-10 06:34:14 +00003660 CharUnits Sizeof;
3661 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00003662 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003663 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003664 }
3665 }
3666
3667 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003668 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003669}
3670
Peter Collingbournee9200682011-05-13 03:29:01 +00003671bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00003672 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00003673 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00003674 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003675 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00003676 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00003677 for (unsigned i = 0; i != n; ++i) {
3678 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
3679 switch (ON.getKind()) {
3680 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00003681 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00003682 APSInt IdxResult;
3683 if (!EvaluateInteger(Idx, IdxResult, Info))
3684 return false;
3685 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
3686 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003687 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003688 CurrentType = AT->getElementType();
3689 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
3690 Result += IdxResult.getSExtValue() * ElementSize;
3691 break;
3692 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00003693
Douglas Gregor882211c2010-04-28 22:16:22 +00003694 case OffsetOfExpr::OffsetOfNode::Field: {
3695 FieldDecl *MemberDecl = ON.getField();
3696 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003697 if (!RT)
3698 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003699 RecordDecl *RD = RT->getDecl();
3700 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00003701 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00003702 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00003703 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00003704 CurrentType = MemberDecl->getType().getNonReferenceType();
3705 break;
3706 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00003707
Douglas Gregor882211c2010-04-28 22:16:22 +00003708 case OffsetOfExpr::OffsetOfNode::Identifier:
3709 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003710 return Error(OOE);
3711
Douglas Gregord1702062010-04-29 00:18:15 +00003712 case OffsetOfExpr::OffsetOfNode::Base: {
3713 CXXBaseSpecifier *BaseSpec = ON.getBase();
3714 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003715 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003716
3717 // Find the layout of the class whose base we are looking into.
3718 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003719 if (!RT)
3720 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003721 RecordDecl *RD = RT->getDecl();
3722 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
3723
3724 // Find the base class itself.
3725 CurrentType = BaseSpec->getType();
3726 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
3727 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003728 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003729
3730 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00003731 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00003732 break;
3733 }
Douglas Gregor882211c2010-04-28 22:16:22 +00003734 }
3735 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003736 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003737}
3738
Chris Lattnere13042c2008-07-11 19:10:17 +00003739bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003740 switch (E->getOpcode()) {
3741 default:
3742 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
3743 // See C99 6.6p3.
3744 return Error(E);
3745 case UO_Extension:
3746 // FIXME: Should extension allow i-c-e extension expressions in its scope?
3747 // If so, we could clear the diagnostic ID.
3748 return Visit(E->getSubExpr());
3749 case UO_Plus:
3750 // The result is just the value.
3751 return Visit(E->getSubExpr());
3752 case UO_Minus: {
3753 if (!Visit(E->getSubExpr()))
3754 return false;
3755 if (!Result.isInt()) return Error(E);
3756 return Success(-Result.getInt(), E);
3757 }
3758 case UO_Not: {
3759 if (!Visit(E->getSubExpr()))
3760 return false;
3761 if (!Result.isInt()) return Error(E);
3762 return Success(~Result.getInt(), E);
3763 }
3764 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00003765 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00003766 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00003767 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003768 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003769 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003770 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003771}
Mike Stump11289f42009-09-09 15:08:12 +00003772
Chris Lattner477c4be2008-07-12 01:15:53 +00003773/// HandleCast - This is used to evaluate implicit or explicit casts where the
3774/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00003775bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
3776 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00003777 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00003778 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00003779
Eli Friedmanc757de22011-03-25 00:43:55 +00003780 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00003781 case CK_BaseToDerived:
3782 case CK_DerivedToBase:
3783 case CK_UncheckedDerivedToBase:
3784 case CK_Dynamic:
3785 case CK_ToUnion:
3786 case CK_ArrayToPointerDecay:
3787 case CK_FunctionToPointerDecay:
3788 case CK_NullToPointer:
3789 case CK_NullToMemberPointer:
3790 case CK_BaseToDerivedMemberPointer:
3791 case CK_DerivedToBaseMemberPointer:
3792 case CK_ConstructorConversion:
3793 case CK_IntegralToPointer:
3794 case CK_ToVoid:
3795 case CK_VectorSplat:
3796 case CK_IntegralToFloating:
3797 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00003798 case CK_CPointerToObjCPointerCast:
3799 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00003800 case CK_AnyPointerToBlockPointerCast:
3801 case CK_ObjCObjectLValueCast:
3802 case CK_FloatingRealToComplex:
3803 case CK_FloatingComplexToReal:
3804 case CK_FloatingComplexCast:
3805 case CK_FloatingComplexToIntegralComplex:
3806 case CK_IntegralRealToComplex:
3807 case CK_IntegralComplexCast:
3808 case CK_IntegralComplexToFloatingComplex:
3809 llvm_unreachable("invalid cast kind for integral value");
3810
Eli Friedman9faf2f92011-03-25 19:07:11 +00003811 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00003812 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00003813 case CK_LValueBitCast:
3814 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00003815 case CK_ARCProduceObject:
3816 case CK_ARCConsumeObject:
3817 case CK_ARCReclaimReturnedObject:
3818 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003819 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003820
3821 case CK_LValueToRValue:
3822 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00003823 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003824
3825 case CK_MemberPointerToBoolean:
3826 case CK_PointerToBoolean:
3827 case CK_IntegralToBoolean:
3828 case CK_FloatingToBoolean:
3829 case CK_FloatingComplexToBoolean:
3830 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00003831 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00003832 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00003833 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003834 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003835 }
3836
Eli Friedmanc757de22011-03-25 00:43:55 +00003837 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00003838 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00003839 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00003840
Eli Friedman742421e2009-02-20 01:15:07 +00003841 if (!Result.isInt()) {
3842 // Only allow casts of lvalues if they are lossless.
3843 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
3844 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003845
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003846 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003847 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00003848 }
Mike Stump11289f42009-09-09 15:08:12 +00003849
Eli Friedmanc757de22011-03-25 00:43:55 +00003850 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003851 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3852
John McCall45d55e42010-05-07 21:00:08 +00003853 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00003854 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00003855 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00003856
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003857 if (LV.getLValueBase()) {
3858 // Only allow based lvalue casts if they are lossless.
3859 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003860 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003861
Richard Smithcf74da72011-11-16 07:18:12 +00003862 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00003863 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003864 return true;
3865 }
3866
Ken Dyck02990832010-01-15 12:37:54 +00003867 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
3868 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003869 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003870 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003871
Eli Friedmanc757de22011-03-25 00:43:55 +00003872 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00003873 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00003874 if (!EvaluateComplex(SubExpr, C, Info))
3875 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00003876 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00003877 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00003878
Eli Friedmanc757de22011-03-25 00:43:55 +00003879 case CK_FloatingToIntegral: {
3880 APFloat F(0.0);
3881 if (!EvaluateFloat(SubExpr, F, Info))
3882 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00003883
Eli Friedmanc757de22011-03-25 00:43:55 +00003884 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
3885 }
3886 }
Mike Stump11289f42009-09-09 15:08:12 +00003887
Eli Friedmanc757de22011-03-25 00:43:55 +00003888 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003889 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00003890}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003891
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003892bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3893 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00003894 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003895 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
3896 return false;
3897 if (!LV.isComplexInt())
3898 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003899 return Success(LV.getComplexIntReal(), E);
3900 }
3901
3902 return Visit(E->getSubExpr());
3903}
3904
Eli Friedman4e7a2412009-02-27 04:45:43 +00003905bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003906 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00003907 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003908 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
3909 return false;
3910 if (!LV.isComplexInt())
3911 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003912 return Success(LV.getComplexIntImag(), E);
3913 }
3914
Richard Smith4a678122011-10-24 18:44:57 +00003915 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00003916 return Success(0, E);
3917}
3918
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003919bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
3920 return Success(E->getPackLength(), E);
3921}
3922
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003923bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
3924 return Success(E->getValue(), E);
3925}
3926
Chris Lattner05706e882008-07-11 18:11:29 +00003927//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00003928// Float Evaluation
3929//===----------------------------------------------------------------------===//
3930
3931namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003932class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003933 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00003934 APFloat &Result;
3935public:
3936 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003937 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00003938
Richard Smith0b0a0b62011-10-29 20:57:55 +00003939 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003940 Result = V.getFloat();
3941 return true;
3942 }
Eli Friedman24c01542008-08-22 00:06:13 +00003943
Richard Smith4ce706a2011-10-11 21:43:33 +00003944 bool ValueInitialization(const Expr *E) {
3945 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
3946 return true;
3947 }
3948
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003949 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00003950
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003951 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00003952 bool VisitBinaryOperator(const BinaryOperator *E);
3953 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003954 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00003955
John McCallb1fb0d32010-05-07 22:08:54 +00003956 bool VisitUnaryReal(const UnaryOperator *E);
3957 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00003958
John McCallb1fb0d32010-05-07 22:08:54 +00003959 // FIXME: Missing: array subscript of vector, member of vector,
3960 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00003961};
3962} // end anonymous namespace
3963
3964static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003965 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003966 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00003967}
3968
Jay Foad39c79802011-01-12 09:06:06 +00003969static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00003970 QualType ResultTy,
3971 const Expr *Arg,
3972 bool SNaN,
3973 llvm::APFloat &Result) {
3974 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
3975 if (!S) return false;
3976
3977 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
3978
3979 llvm::APInt fill;
3980
3981 // Treat empty strings as if they were zero.
3982 if (S->getString().empty())
3983 fill = llvm::APInt(32, 0);
3984 else if (S->getString().getAsInteger(0, fill))
3985 return false;
3986
3987 if (SNaN)
3988 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
3989 else
3990 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
3991 return true;
3992}
3993
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003994bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003995 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003996 default:
3997 return ExprEvaluatorBaseTy::VisitCallExpr(E);
3998
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003999 case Builtin::BI__builtin_huge_val:
4000 case Builtin::BI__builtin_huge_valf:
4001 case Builtin::BI__builtin_huge_vall:
4002 case Builtin::BI__builtin_inf:
4003 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004004 case Builtin::BI__builtin_infl: {
4005 const llvm::fltSemantics &Sem =
4006 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00004007 Result = llvm::APFloat::getInf(Sem);
4008 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004009 }
Mike Stump11289f42009-09-09 15:08:12 +00004010
John McCall16291492010-02-28 13:00:19 +00004011 case Builtin::BI__builtin_nans:
4012 case Builtin::BI__builtin_nansf:
4013 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004014 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4015 true, Result))
4016 return Error(E);
4017 return true;
John McCall16291492010-02-28 13:00:19 +00004018
Chris Lattner0b7282e2008-10-06 06:31:58 +00004019 case Builtin::BI__builtin_nan:
4020 case Builtin::BI__builtin_nanf:
4021 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00004022 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00004023 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004024 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4025 false, Result))
4026 return Error(E);
4027 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004028
4029 case Builtin::BI__builtin_fabs:
4030 case Builtin::BI__builtin_fabsf:
4031 case Builtin::BI__builtin_fabsl:
4032 if (!EvaluateFloat(E->getArg(0), Result, Info))
4033 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004034
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004035 if (Result.isNegative())
4036 Result.changeSign();
4037 return true;
4038
Mike Stump11289f42009-09-09 15:08:12 +00004039 case Builtin::BI__builtin_copysign:
4040 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004041 case Builtin::BI__builtin_copysignl: {
4042 APFloat RHS(0.);
4043 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4044 !EvaluateFloat(E->getArg(1), RHS, Info))
4045 return false;
4046 Result.copySign(RHS);
4047 return true;
4048 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004049 }
4050}
4051
John McCallb1fb0d32010-05-07 22:08:54 +00004052bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004053 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4054 ComplexValue CV;
4055 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4056 return false;
4057 Result = CV.FloatReal;
4058 return true;
4059 }
4060
4061 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004062}
4063
4064bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004065 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4066 ComplexValue CV;
4067 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4068 return false;
4069 Result = CV.FloatImag;
4070 return true;
4071 }
4072
Richard Smith4a678122011-10-24 18:44:57 +00004073 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004074 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4075 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004076 return true;
4077}
4078
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004079bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004080 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004081 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004082 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004083 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004084 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004085 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4086 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004087 Result.changeSign();
4088 return true;
4089 }
4090}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004091
Eli Friedman24c01542008-08-22 00:06:13 +00004092bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004093 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4094 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004095
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004096 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004097 if (!EvaluateFloat(E->getLHS(), Result, Info))
4098 return false;
4099 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4100 return false;
4101
4102 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004103 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004104 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004105 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4106 return true;
John McCalle3027922010-08-25 11:45:40 +00004107 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004108 Result.add(RHS, APFloat::rmNearestTiesToEven);
4109 return true;
John McCalle3027922010-08-25 11:45:40 +00004110 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004111 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4112 return true;
John McCalle3027922010-08-25 11:45:40 +00004113 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004114 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4115 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004116 }
4117}
4118
4119bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4120 Result = E->getValue();
4121 return true;
4122}
4123
Peter Collingbournee9200682011-05-13 03:29:01 +00004124bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4125 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004126
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004127 switch (E->getCastKind()) {
4128 default:
Richard Smith11562c52011-10-28 17:51:58 +00004129 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004130
4131 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004132 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004133 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004134 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004135 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004136 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00004137 return true;
4138 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004139
4140 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004141 if (!Visit(SubExpr))
4142 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004143 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
4144 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00004145 return true;
4146 }
John McCalld7646252010-11-14 08:17:51 +00004147
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004148 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004149 ComplexValue V;
4150 if (!EvaluateComplex(SubExpr, V, Info))
4151 return false;
4152 Result = V.getComplexFloatReal();
4153 return true;
4154 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004155 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004156
Richard Smithf57d8cb2011-12-09 22:58:01 +00004157 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004158}
4159
Eli Friedman24c01542008-08-22 00:06:13 +00004160//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004161// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004162//===----------------------------------------------------------------------===//
4163
4164namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004165class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004166 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004167 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004168
Anders Carlsson537969c2008-11-16 20:27:53 +00004169public:
John McCall93d91dc2010-05-07 17:22:02 +00004170 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004171 : ExprEvaluatorBaseTy(info), Result(Result) {}
4172
Richard Smith0b0a0b62011-10-29 20:57:55 +00004173 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004174 Result.setFrom(V);
4175 return true;
4176 }
Mike Stump11289f42009-09-09 15:08:12 +00004177
Anders Carlsson537969c2008-11-16 20:27:53 +00004178 //===--------------------------------------------------------------------===//
4179 // Visitor Methods
4180 //===--------------------------------------------------------------------===//
4181
Peter Collingbournee9200682011-05-13 03:29:01 +00004182 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00004183
Peter Collingbournee9200682011-05-13 03:29:01 +00004184 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004185
John McCall93d91dc2010-05-07 17:22:02 +00004186 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004187 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004188 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00004189};
4190} // end anonymous namespace
4191
John McCall93d91dc2010-05-07 17:22:02 +00004192static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4193 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004194 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004195 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004196}
4197
Peter Collingbournee9200682011-05-13 03:29:01 +00004198bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4199 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004200
4201 if (SubExpr->getType()->isRealFloatingType()) {
4202 Result.makeComplexFloat();
4203 APFloat &Imag = Result.FloatImag;
4204 if (!EvaluateFloat(SubExpr, Imag, Info))
4205 return false;
4206
4207 Result.FloatReal = APFloat(Imag.getSemantics());
4208 return true;
4209 } else {
4210 assert(SubExpr->getType()->isIntegerType() &&
4211 "Unexpected imaginary literal.");
4212
4213 Result.makeComplexInt();
4214 APSInt &Imag = Result.IntImag;
4215 if (!EvaluateInteger(SubExpr, Imag, Info))
4216 return false;
4217
4218 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4219 return true;
4220 }
4221}
4222
Peter Collingbournee9200682011-05-13 03:29:01 +00004223bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004224
John McCallfcef3cf2010-12-14 17:51:41 +00004225 switch (E->getCastKind()) {
4226 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004227 case CK_BaseToDerived:
4228 case CK_DerivedToBase:
4229 case CK_UncheckedDerivedToBase:
4230 case CK_Dynamic:
4231 case CK_ToUnion:
4232 case CK_ArrayToPointerDecay:
4233 case CK_FunctionToPointerDecay:
4234 case CK_NullToPointer:
4235 case CK_NullToMemberPointer:
4236 case CK_BaseToDerivedMemberPointer:
4237 case CK_DerivedToBaseMemberPointer:
4238 case CK_MemberPointerToBoolean:
4239 case CK_ConstructorConversion:
4240 case CK_IntegralToPointer:
4241 case CK_PointerToIntegral:
4242 case CK_PointerToBoolean:
4243 case CK_ToVoid:
4244 case CK_VectorSplat:
4245 case CK_IntegralCast:
4246 case CK_IntegralToBoolean:
4247 case CK_IntegralToFloating:
4248 case CK_FloatingToIntegral:
4249 case CK_FloatingToBoolean:
4250 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004251 case CK_CPointerToObjCPointerCast:
4252 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004253 case CK_AnyPointerToBlockPointerCast:
4254 case CK_ObjCObjectLValueCast:
4255 case CK_FloatingComplexToReal:
4256 case CK_FloatingComplexToBoolean:
4257 case CK_IntegralComplexToReal:
4258 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004259 case CK_ARCProduceObject:
4260 case CK_ARCConsumeObject:
4261 case CK_ARCReclaimReturnedObject:
4262 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004263 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004264
John McCallfcef3cf2010-12-14 17:51:41 +00004265 case CK_LValueToRValue:
4266 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004267 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004268
4269 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004270 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004271 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004272 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004273
4274 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004275 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004276 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004277 return false;
4278
John McCallfcef3cf2010-12-14 17:51:41 +00004279 Result.makeComplexFloat();
4280 Result.FloatImag = APFloat(Real.getSemantics());
4281 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004282 }
4283
John McCallfcef3cf2010-12-14 17:51:41 +00004284 case CK_FloatingComplexCast: {
4285 if (!Visit(E->getSubExpr()))
4286 return false;
4287
4288 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4289 QualType From
4290 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4291
4292 Result.FloatReal
4293 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
4294 Result.FloatImag
4295 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
4296 return true;
4297 }
4298
4299 case CK_FloatingComplexToIntegralComplex: {
4300 if (!Visit(E->getSubExpr()))
4301 return false;
4302
4303 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4304 QualType From
4305 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4306 Result.makeComplexInt();
4307 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
4308 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
4309 return true;
4310 }
4311
4312 case CK_IntegralRealToComplex: {
4313 APSInt &Real = Result.IntReal;
4314 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4315 return false;
4316
4317 Result.makeComplexInt();
4318 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4319 return true;
4320 }
4321
4322 case CK_IntegralComplexCast: {
4323 if (!Visit(E->getSubExpr()))
4324 return false;
4325
4326 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4327 QualType From
4328 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4329
4330 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4331 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4332 return true;
4333 }
4334
4335 case CK_IntegralComplexToFloatingComplex: {
4336 if (!Visit(E->getSubExpr()))
4337 return false;
4338
4339 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4340 QualType From
4341 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4342 Result.makeComplexFloat();
4343 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
4344 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
4345 return true;
4346 }
4347 }
4348
4349 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004350 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004351}
4352
John McCall93d91dc2010-05-07 17:22:02 +00004353bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004354 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00004355 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4356
John McCall93d91dc2010-05-07 17:22:02 +00004357 if (!Visit(E->getLHS()))
4358 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004359
John McCall93d91dc2010-05-07 17:22:02 +00004360 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004361 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00004362 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004363
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004364 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4365 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004366 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004367 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004368 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004369 if (Result.isComplexFloat()) {
4370 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4371 APFloat::rmNearestTiesToEven);
4372 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4373 APFloat::rmNearestTiesToEven);
4374 } else {
4375 Result.getComplexIntReal() += RHS.getComplexIntReal();
4376 Result.getComplexIntImag() += RHS.getComplexIntImag();
4377 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004378 break;
John McCalle3027922010-08-25 11:45:40 +00004379 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004380 if (Result.isComplexFloat()) {
4381 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4382 APFloat::rmNearestTiesToEven);
4383 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4384 APFloat::rmNearestTiesToEven);
4385 } else {
4386 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4387 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4388 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004389 break;
John McCalle3027922010-08-25 11:45:40 +00004390 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004391 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00004392 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004393 APFloat &LHS_r = LHS.getComplexFloatReal();
4394 APFloat &LHS_i = LHS.getComplexFloatImag();
4395 APFloat &RHS_r = RHS.getComplexFloatReal();
4396 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00004397
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004398 APFloat Tmp = LHS_r;
4399 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4400 Result.getComplexFloatReal() = Tmp;
4401 Tmp = LHS_i;
4402 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4403 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4404
4405 Tmp = LHS_r;
4406 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4407 Result.getComplexFloatImag() = Tmp;
4408 Tmp = LHS_i;
4409 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4410 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4411 } else {
John McCall93d91dc2010-05-07 17:22:02 +00004412 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00004413 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004414 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4415 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00004416 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004417 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4418 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4419 }
4420 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004421 case BO_Div:
4422 if (Result.isComplexFloat()) {
4423 ComplexValue LHS = Result;
4424 APFloat &LHS_r = LHS.getComplexFloatReal();
4425 APFloat &LHS_i = LHS.getComplexFloatImag();
4426 APFloat &RHS_r = RHS.getComplexFloatReal();
4427 APFloat &RHS_i = RHS.getComplexFloatImag();
4428 APFloat &Res_r = Result.getComplexFloatReal();
4429 APFloat &Res_i = Result.getComplexFloatImag();
4430
4431 APFloat Den = RHS_r;
4432 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4433 APFloat Tmp = RHS_i;
4434 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4435 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4436
4437 Res_r = LHS_r;
4438 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4439 Tmp = LHS_i;
4440 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4441 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4442 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4443
4444 Res_i = LHS_i;
4445 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4446 Tmp = LHS_r;
4447 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4448 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4449 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4450 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004451 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
4452 return Error(E, diag::note_expr_divide_by_zero);
4453
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004454 ComplexValue LHS = Result;
4455 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4456 RHS.getComplexIntImag() * RHS.getComplexIntImag();
4457 Result.getComplexIntReal() =
4458 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
4459 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
4460 Result.getComplexIntImag() =
4461 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
4462 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
4463 }
4464 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004465 }
4466
John McCall93d91dc2010-05-07 17:22:02 +00004467 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004468}
4469
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004470bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4471 // Get the operand value into 'Result'.
4472 if (!Visit(E->getSubExpr()))
4473 return false;
4474
4475 switch (E->getOpcode()) {
4476 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004477 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004478 case UO_Extension:
4479 return true;
4480 case UO_Plus:
4481 // The result is always just the subexpr.
4482 return true;
4483 case UO_Minus:
4484 if (Result.isComplexFloat()) {
4485 Result.getComplexFloatReal().changeSign();
4486 Result.getComplexFloatImag().changeSign();
4487 }
4488 else {
4489 Result.getComplexIntReal() = -Result.getComplexIntReal();
4490 Result.getComplexIntImag() = -Result.getComplexIntImag();
4491 }
4492 return true;
4493 case UO_Not:
4494 if (Result.isComplexFloat())
4495 Result.getComplexFloatImag().changeSign();
4496 else
4497 Result.getComplexIntImag() = -Result.getComplexIntImag();
4498 return true;
4499 }
4500}
4501
Anders Carlsson537969c2008-11-16 20:27:53 +00004502//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00004503// Void expression evaluation, primarily for a cast to void on the LHS of a
4504// comma operator
4505//===----------------------------------------------------------------------===//
4506
4507namespace {
4508class VoidExprEvaluator
4509 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
4510public:
4511 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
4512
4513 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00004514
4515 bool VisitCastExpr(const CastExpr *E) {
4516 switch (E->getCastKind()) {
4517 default:
4518 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4519 case CK_ToVoid:
4520 VisitIgnoredValue(E->getSubExpr());
4521 return true;
4522 }
4523 }
4524};
4525} // end anonymous namespace
4526
4527static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
4528 assert(E->isRValue() && E->getType()->isVoidType());
4529 return VoidExprEvaluator(Info).Visit(E);
4530}
4531
4532//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00004533// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00004534//===----------------------------------------------------------------------===//
4535
Richard Smith0b0a0b62011-10-29 20:57:55 +00004536static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004537 // In C, function designators are not lvalues, but we evaluate them as if they
4538 // are.
4539 if (E->isGLValue() || E->getType()->isFunctionType()) {
4540 LValue LV;
4541 if (!EvaluateLValue(E, LV, Info))
4542 return false;
4543 LV.moveInto(Result);
4544 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004545 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004546 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004547 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004548 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004549 return false;
John McCall45d55e42010-05-07 21:00:08 +00004550 } else if (E->getType()->hasPointerRepresentation()) {
4551 LValue LV;
4552 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004553 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004554 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00004555 } else if (E->getType()->isRealFloatingType()) {
4556 llvm::APFloat F(0.0);
4557 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004558 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004559 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00004560 } else if (E->getType()->isAnyComplexType()) {
4561 ComplexValue C;
4562 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004563 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004564 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00004565 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004566 MemberPtr P;
4567 if (!EvaluateMemberPointer(E, P, Info))
4568 return false;
4569 P.moveInto(Result);
4570 return true;
Richard Smithed5165f2011-11-04 05:33:44 +00004571 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004572 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004573 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004574 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00004575 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004576 Result = Info.CurrentCall->Temporaries[E];
Richard Smithed5165f2011-11-04 05:33:44 +00004577 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004578 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004579 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004580 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
4581 return false;
4582 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00004583 } else if (E->getType()->isVoidType()) {
4584 if (!EvaluateVoid(E, Info))
4585 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004586 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00004587 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00004588 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004589 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004590
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00004591 return true;
4592}
4593
Richard Smithed5165f2011-11-04 05:33:44 +00004594/// EvaluateConstantExpression - Evaluate an expression as a constant expression
4595/// in-place in an APValue. In some cases, the in-place evaluation is essential,
4596/// since later initializers for an object can indirectly refer to subobjects
4597/// which were initialized earlier.
4598static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +00004599 const LValue &This, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004600 if (E->isRValue() && E->getType()->isLiteralType()) {
4601 // Evaluate arrays and record types in-place, so that later initializers can
4602 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00004603 if (E->getType()->isArrayType())
4604 return EvaluateArray(E, This, Result, Info);
4605 else if (E->getType()->isRecordType())
4606 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00004607 }
4608
4609 // For any other type, in-place evaluation is unimportant.
4610 CCValue CoreConstResult;
4611 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithf57d8cb2011-12-09 22:58:01 +00004612 CheckConstantExpression(Info, E, CoreConstResult, Result);
Richard Smithed5165f2011-11-04 05:33:44 +00004613}
4614
Richard Smithf57d8cb2011-12-09 22:58:01 +00004615/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
4616/// lvalue-to-rvalue cast if it is an lvalue.
4617static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
4618 CCValue Value;
4619 if (!::Evaluate(Value, Info, E))
4620 return false;
4621
4622 if (E->isGLValue()) {
4623 LValue LV;
4624 LV.setFrom(Value);
4625 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
4626 return false;
4627 }
4628
4629 // Check this core constant expression is a constant expression, and if so,
4630 // convert it to one.
4631 return CheckConstantExpression(Info, E, Value, Result);
4632}
Richard Smith11562c52011-10-28 17:51:58 +00004633
Richard Smith7b553f12011-10-29 00:50:52 +00004634/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00004635/// any crazy technique (that has nothing to do with language standards) that
4636/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00004637/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
4638/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00004639bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00004640 // Fast-path evaluations of integer literals, since we sometimes see files
4641 // containing vast quantities of these.
4642 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
4643 Result.Val = APValue(APSInt(L->getValue(),
4644 L->getType()->isUnsignedIntegerType()));
4645 return true;
4646 }
4647
Richard Smith5686e752011-11-10 03:30:42 +00004648 // FIXME: Evaluating initializers for large arrays can cause performance
4649 // problems, and we don't use such values yet. Once we have a more efficient
4650 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00004651 // The same problem affects large records.
4652 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
4653 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00004654 return false;
4655
Richard Smithd62306a2011-11-10 06:34:14 +00004656 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004657 EvalInfo Info(Ctx, Result);
4658 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00004659}
4660
Jay Foad39c79802011-01-12 09:06:06 +00004661bool Expr::EvaluateAsBooleanCondition(bool &Result,
4662 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00004663 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00004664 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00004665 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00004666 Result);
John McCall1be1c632010-01-05 23:42:56 +00004667}
4668
Richard Smithcaf33902011-10-10 18:28:20 +00004669bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00004670 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004671 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00004672 !ExprResult.Val.isInt())
Richard Smith11562c52011-10-28 17:51:58 +00004673 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004674
Richard Smith11562c52011-10-28 17:51:58 +00004675 Result = ExprResult.Val.getInt();
4676 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00004677}
4678
Jay Foad39c79802011-01-12 09:06:06 +00004679bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00004680 EvalInfo Info(Ctx, Result);
4681
John McCall45d55e42010-05-07 21:00:08 +00004682 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00004683 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithf57d8cb2011-12-09 22:58:01 +00004684 CheckLValueConstantExpression(Info, this, LV, Result.Val);
Eli Friedman7d45c482009-09-13 10:17:44 +00004685}
4686
Richard Smith7b553f12011-10-29 00:50:52 +00004687/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
4688/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00004689bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00004690 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00004691 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00004692}
Anders Carlsson59689ed2008-11-22 21:04:56 +00004693
Jay Foad39c79802011-01-12 09:06:06 +00004694bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00004695 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00004696}
4697
Richard Smithcaf33902011-10-10 18:28:20 +00004698APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004699 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004700 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00004701 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00004702 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004703 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00004704
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004705 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00004706}
John McCall864e3962010-05-07 05:32:02 +00004707
Abramo Bagnaraf8199452010-05-14 17:07:14 +00004708 bool Expr::EvalResult::isGlobalLValue() const {
4709 assert(Val.isLValue());
4710 return IsGlobalLValue(Val.getLValueBase());
4711 }
4712
4713
John McCall864e3962010-05-07 05:32:02 +00004714/// isIntegerConstantExpr - this recursive routine will test if an expression is
4715/// an integer constant expression.
4716
4717/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
4718/// comma, etc
4719///
4720/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
4721/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
4722/// cast+dereference.
4723
4724// CheckICE - This function does the fundamental ICE checking: the returned
4725// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
4726// Note that to reduce code duplication, this helper does no evaluation
4727// itself; the caller checks whether the expression is evaluatable, and
4728// in the rare cases where CheckICE actually cares about the evaluated
4729// value, it calls into Evalute.
4730//
4731// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00004732// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00004733// 1: This expression is not an ICE, but if it isn't evaluated, it's
4734// a legal subexpression for an ICE. This return value is used to handle
4735// the comma operator in C99 mode.
4736// 2: This expression is not an ICE, and is not a legal subexpression for one.
4737
Dan Gohman28ade552010-07-26 21:25:24 +00004738namespace {
4739
John McCall864e3962010-05-07 05:32:02 +00004740struct ICEDiag {
4741 unsigned Val;
4742 SourceLocation Loc;
4743
4744 public:
4745 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
4746 ICEDiag() : Val(0) {}
4747};
4748
Dan Gohman28ade552010-07-26 21:25:24 +00004749}
4750
4751static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00004752
4753static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
4754 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004755 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00004756 !EVResult.Val.isInt()) {
4757 return ICEDiag(2, E->getLocStart());
4758 }
4759 return NoDiag();
4760}
4761
4762static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
4763 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00004764 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00004765 return ICEDiag(2, E->getLocStart());
4766 }
4767
4768 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00004769#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00004770#define STMT(Node, Base) case Expr::Node##Class:
4771#define EXPR(Node, Base)
4772#include "clang/AST/StmtNodes.inc"
4773 case Expr::PredefinedExprClass:
4774 case Expr::FloatingLiteralClass:
4775 case Expr::ImaginaryLiteralClass:
4776 case Expr::StringLiteralClass:
4777 case Expr::ArraySubscriptExprClass:
4778 case Expr::MemberExprClass:
4779 case Expr::CompoundAssignOperatorClass:
4780 case Expr::CompoundLiteralExprClass:
4781 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00004782 case Expr::DesignatedInitExprClass:
4783 case Expr::ImplicitValueInitExprClass:
4784 case Expr::ParenListExprClass:
4785 case Expr::VAArgExprClass:
4786 case Expr::AddrLabelExprClass:
4787 case Expr::StmtExprClass:
4788 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00004789 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00004790 case Expr::CXXDynamicCastExprClass:
4791 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00004792 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00004793 case Expr::CXXNullPtrLiteralExprClass:
4794 case Expr::CXXThisExprClass:
4795 case Expr::CXXThrowExprClass:
4796 case Expr::CXXNewExprClass:
4797 case Expr::CXXDeleteExprClass:
4798 case Expr::CXXPseudoDestructorExprClass:
4799 case Expr::UnresolvedLookupExprClass:
4800 case Expr::DependentScopeDeclRefExprClass:
4801 case Expr::CXXConstructExprClass:
4802 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00004803 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00004804 case Expr::CXXTemporaryObjectExprClass:
4805 case Expr::CXXUnresolvedConstructExprClass:
4806 case Expr::CXXDependentScopeMemberExprClass:
4807 case Expr::UnresolvedMemberExprClass:
4808 case Expr::ObjCStringLiteralClass:
4809 case Expr::ObjCEncodeExprClass:
4810 case Expr::ObjCMessageExprClass:
4811 case Expr::ObjCSelectorExprClass:
4812 case Expr::ObjCProtocolExprClass:
4813 case Expr::ObjCIvarRefExprClass:
4814 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00004815 case Expr::ObjCIsaExprClass:
4816 case Expr::ShuffleVectorExprClass:
4817 case Expr::BlockExprClass:
4818 case Expr::BlockDeclRefExprClass:
4819 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00004820 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004821 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00004822 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00004823 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00004824 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00004825 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00004826 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004827 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00004828 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00004829 return ICEDiag(2, E->getLocStart());
4830
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004831 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00004832 case Expr::GNUNullExprClass:
4833 // GCC considers the GNU __null value to be an integral constant expression.
4834 return NoDiag();
4835
John McCall7c454bb2011-07-15 05:09:51 +00004836 case Expr::SubstNonTypeTemplateParmExprClass:
4837 return
4838 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
4839
John McCall864e3962010-05-07 05:32:02 +00004840 case Expr::ParenExprClass:
4841 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00004842 case Expr::GenericSelectionExprClass:
4843 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00004844 case Expr::IntegerLiteralClass:
4845 case Expr::CharacterLiteralClass:
4846 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00004847 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00004848 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004849 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00004850 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00004851 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00004852 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00004853 return NoDiag();
4854 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00004855 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00004856 // C99 6.6/3 allows function calls within unevaluated subexpressions of
4857 // constant expressions, but they can never be ICEs because an ICE cannot
4858 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00004859 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004860 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00004861 return CheckEvalInICE(E, Ctx);
4862 return ICEDiag(2, E->getLocStart());
4863 }
4864 case Expr::DeclRefExprClass:
4865 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
4866 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00004867 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00004868 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4869
4870 // Parameter variables are never constants. Without this check,
4871 // getAnyInitializer() can find a default argument, which leads
4872 // to chaos.
4873 if (isa<ParmVarDecl>(D))
4874 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4875
4876 // C++ 7.1.5.1p2
4877 // A variable of non-volatile const-qualified integral or enumeration
4878 // type initialized by an ICE can be used in ICEs.
4879 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00004880 if (!Dcl->getType()->isIntegralOrEnumerationType())
4881 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4882
John McCall864e3962010-05-07 05:32:02 +00004883 // Look for a declaration of this variable that has an initializer.
4884 const VarDecl *ID = 0;
4885 const Expr *Init = Dcl->getAnyInitializer(ID);
4886 if (Init) {
4887 if (ID->isInitKnownICE()) {
4888 // We have already checked whether this subexpression is an
4889 // integral constant expression.
4890 if (ID->isInitICE())
4891 return NoDiag();
4892 else
4893 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4894 }
4895
4896 // It's an ICE whether or not the definition we found is
4897 // out-of-line. See DR 721 and the discussion in Clang PR
4898 // 6206 for details.
4899
4900 if (Dcl->isCheckingICE()) {
4901 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4902 }
4903
4904 Dcl->setCheckingICE();
4905 ICEDiag Result = CheckICE(Init, Ctx);
4906 // Cache the result of the ICE test.
4907 Dcl->setInitKnownICE(Result.Val == 0);
4908 return Result;
4909 }
4910 }
4911 }
4912 return ICEDiag(2, E->getLocStart());
4913 case Expr::UnaryOperatorClass: {
4914 const UnaryOperator *Exp = cast<UnaryOperator>(E);
4915 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004916 case UO_PostInc:
4917 case UO_PostDec:
4918 case UO_PreInc:
4919 case UO_PreDec:
4920 case UO_AddrOf:
4921 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00004922 // C99 6.6/3 allows increment and decrement within unevaluated
4923 // subexpressions of constant expressions, but they can never be ICEs
4924 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00004925 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00004926 case UO_Extension:
4927 case UO_LNot:
4928 case UO_Plus:
4929 case UO_Minus:
4930 case UO_Not:
4931 case UO_Real:
4932 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00004933 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00004934 }
4935
4936 // OffsetOf falls through here.
4937 }
4938 case Expr::OffsetOfExprClass: {
4939 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00004940 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00004941 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00004942 // compliance: we should warn earlier for offsetof expressions with
4943 // array subscripts that aren't ICEs, and if the array subscripts
4944 // are ICEs, the value of the offsetof must be an integer constant.
4945 return CheckEvalInICE(E, Ctx);
4946 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00004947 case Expr::UnaryExprOrTypeTraitExprClass: {
4948 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
4949 if ((Exp->getKind() == UETT_SizeOf) &&
4950 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00004951 return ICEDiag(2, E->getLocStart());
4952 return NoDiag();
4953 }
4954 case Expr::BinaryOperatorClass: {
4955 const BinaryOperator *Exp = cast<BinaryOperator>(E);
4956 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004957 case BO_PtrMemD:
4958 case BO_PtrMemI:
4959 case BO_Assign:
4960 case BO_MulAssign:
4961 case BO_DivAssign:
4962 case BO_RemAssign:
4963 case BO_AddAssign:
4964 case BO_SubAssign:
4965 case BO_ShlAssign:
4966 case BO_ShrAssign:
4967 case BO_AndAssign:
4968 case BO_XorAssign:
4969 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00004970 // C99 6.6/3 allows assignments within unevaluated subexpressions of
4971 // constant expressions, but they can never be ICEs because an ICE cannot
4972 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00004973 return ICEDiag(2, E->getLocStart());
4974
John McCalle3027922010-08-25 11:45:40 +00004975 case BO_Mul:
4976 case BO_Div:
4977 case BO_Rem:
4978 case BO_Add:
4979 case BO_Sub:
4980 case BO_Shl:
4981 case BO_Shr:
4982 case BO_LT:
4983 case BO_GT:
4984 case BO_LE:
4985 case BO_GE:
4986 case BO_EQ:
4987 case BO_NE:
4988 case BO_And:
4989 case BO_Xor:
4990 case BO_Or:
4991 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00004992 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
4993 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00004994 if (Exp->getOpcode() == BO_Div ||
4995 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00004996 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00004997 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00004998 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00004999 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005000 if (REval == 0)
5001 return ICEDiag(1, E->getLocStart());
5002 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00005003 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005004 if (LEval.isMinSignedValue())
5005 return ICEDiag(1, E->getLocStart());
5006 }
5007 }
5008 }
John McCalle3027922010-08-25 11:45:40 +00005009 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00005010 if (Ctx.getLangOptions().C99) {
5011 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5012 // if it isn't evaluated.
5013 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5014 return ICEDiag(1, E->getLocStart());
5015 } else {
5016 // In both C89 and C++, commas in ICEs are illegal.
5017 return ICEDiag(2, E->getLocStart());
5018 }
5019 }
5020 if (LHSResult.Val >= RHSResult.Val)
5021 return LHSResult;
5022 return RHSResult;
5023 }
John McCalle3027922010-08-25 11:45:40 +00005024 case BO_LAnd:
5025 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00005026 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5027 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5028 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5029 // Rare case where the RHS has a comma "side-effect"; we need
5030 // to actually check the condition to see whether the side
5031 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00005032 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00005033 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00005034 return RHSResult;
5035 return NoDiag();
5036 }
5037
5038 if (LHSResult.Val >= RHSResult.Val)
5039 return LHSResult;
5040 return RHSResult;
5041 }
5042 }
5043 }
5044 case Expr::ImplicitCastExprClass:
5045 case Expr::CStyleCastExprClass:
5046 case Expr::CXXFunctionalCastExprClass:
5047 case Expr::CXXStaticCastExprClass:
5048 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005049 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005050 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005051 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00005052 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00005053 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
5054 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00005055 switch (cast<CastExpr>(E)->getCastKind()) {
5056 case CK_LValueToRValue:
5057 case CK_NoOp:
5058 case CK_IntegralToBoolean:
5059 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005060 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005061 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005062 return ICEDiag(2, E->getLocStart());
5063 }
John McCall864e3962010-05-07 05:32:02 +00005064 }
John McCallc07a0c72011-02-17 10:25:35 +00005065 case Expr::BinaryConditionalOperatorClass: {
5066 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5067 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5068 if (CommonResult.Val == 2) return CommonResult;
5069 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5070 if (FalseResult.Val == 2) return FalseResult;
5071 if (CommonResult.Val == 1) return CommonResult;
5072 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005073 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005074 return FalseResult;
5075 }
John McCall864e3962010-05-07 05:32:02 +00005076 case Expr::ConditionalOperatorClass: {
5077 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5078 // If the condition (ignoring parens) is a __builtin_constant_p call,
5079 // then only the true side is actually considered in an integer constant
5080 // expression, and it is fully evaluated. This is an important GNU
5081 // extension. See GCC PR38377 for discussion.
5082 if (const CallExpr *CallCE
5083 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smithd62306a2011-11-10 06:34:14 +00005084 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCall864e3962010-05-07 05:32:02 +00005085 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005086 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005087 !EVResult.Val.isInt()) {
5088 return ICEDiag(2, E->getLocStart());
5089 }
5090 return NoDiag();
5091 }
5092 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005093 if (CondResult.Val == 2)
5094 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005095
Richard Smithf57d8cb2011-12-09 22:58:01 +00005096 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5097 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005098
John McCall864e3962010-05-07 05:32:02 +00005099 if (TrueResult.Val == 2)
5100 return TrueResult;
5101 if (FalseResult.Val == 2)
5102 return FalseResult;
5103 if (CondResult.Val == 1)
5104 return CondResult;
5105 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5106 return NoDiag();
5107 // Rare case where the diagnostics depend on which side is evaluated
5108 // Note that if we get here, CondResult is 0, and at least one of
5109 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005110 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005111 return FalseResult;
5112 }
5113 return TrueResult;
5114 }
5115 case Expr::CXXDefaultArgExprClass:
5116 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5117 case Expr::ChooseExprClass: {
5118 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5119 }
5120 }
5121
5122 // Silence a GCC warning
5123 return ICEDiag(2, E->getLocStart());
5124}
5125
Richard Smithf57d8cb2011-12-09 22:58:01 +00005126/// Evaluate an expression as a C++11 integral constant expression.
5127static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5128 const Expr *E,
5129 llvm::APSInt *Value,
5130 SourceLocation *Loc) {
5131 if (!E->getType()->isIntegralOrEnumerationType()) {
5132 if (Loc) *Loc = E->getExprLoc();
5133 return false;
5134 }
5135
5136 Expr::EvalResult Result;
Richard Smith92b1ce02011-12-12 09:28:41 +00005137 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5138 Result.Diag = &Diags;
5139 EvalInfo Info(Ctx, Result);
5140
5141 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5142 if (!Diags.empty()) {
5143 IsICE = false;
5144 if (Loc) *Loc = Diags[0].first;
5145 } else if (!IsICE && Loc) {
5146 *Loc = E->getExprLoc();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005147 }
Richard Smith92b1ce02011-12-12 09:28:41 +00005148
5149 if (!IsICE)
5150 return false;
5151
5152 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5153 if (Value) *Value = Result.Val.getInt();
5154 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005155}
5156
Richard Smith92b1ce02011-12-12 09:28:41 +00005157bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005158 if (Ctx.getLangOptions().CPlusPlus0x)
5159 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5160
John McCall864e3962010-05-07 05:32:02 +00005161 ICEDiag d = CheckICE(this, Ctx);
5162 if (d.Val != 0) {
5163 if (Loc) *Loc = d.Loc;
5164 return false;
5165 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005166 return true;
5167}
5168
5169bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5170 SourceLocation *Loc, bool isEvaluated) const {
5171 if (Ctx.getLangOptions().CPlusPlus0x)
5172 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5173
5174 if (!isIntegerConstantExpr(Ctx, Loc))
5175 return false;
5176 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005177 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005178 return true;
5179}