blob: c095f2166d65391b5ce04e499cd3073dc314eaeb [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 Smith4e4c78ff2011-10-31 05:52:43 +0000251 struct EvalInfo {
252 const ASTContext &Ctx;
253
254 /// EvalStatus - Contains information about the evaluation.
255 Expr::EvalStatus &EvalStatus;
256
257 /// CurrentCall - The top of the constexpr call stack.
258 CallStackFrame *CurrentCall;
259
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000260 /// CallStackDepth - The number of calls in the call stack right now.
261 unsigned CallStackDepth;
262
263 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
264 /// OpaqueValues - Values used as the common expression in a
265 /// BinaryConditionalOperator.
266 MapTy OpaqueValues;
267
268 /// BottomFrame - The frame in which evaluation started. This must be
269 /// initialized last.
270 CallStackFrame BottomFrame;
271
Richard Smithd62306a2011-11-10 06:34:14 +0000272 /// EvaluatingDecl - This is the declaration whose initializer is being
273 /// evaluated, if any.
274 const VarDecl *EvaluatingDecl;
275
276 /// EvaluatingDeclValue - This is the value being constructed for the
277 /// declaration whose initializer is being evaluated, if any.
278 APValue *EvaluatingDeclValue;
279
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000280
281 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith9a568822011-11-21 19:36:32 +0000282 : Ctx(C), EvalStatus(S), CurrentCall(0), CallStackDepth(0),
Richard Smithd62306a2011-11-10 06:34:14 +0000283 BottomFrame(*this, 0, 0), EvaluatingDecl(0), EvaluatingDeclValue(0) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000284
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000285 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
286 MapTy::const_iterator i = OpaqueValues.find(e);
287 if (i == OpaqueValues.end()) return 0;
288 return &i->second;
289 }
290
Richard Smithd62306a2011-11-10 06:34:14 +0000291 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
292 EvaluatingDecl = VD;
293 EvaluatingDeclValue = &Value;
294 }
295
Richard Smith9a568822011-11-21 19:36:32 +0000296 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
297
298 bool atCallLimit() const {
299 return CallStackDepth > getLangOpts().ConstexprCallDepth;
300 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000301 };
302
Richard Smithd62306a2011-11-10 06:34:14 +0000303 CallStackFrame::CallStackFrame(EvalInfo &Info, const LValue *This,
304 const CCValue *Arguments)
305 : Info(Info), Caller(Info.CurrentCall), This(This), Arguments(Arguments) {
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000306 Info.CurrentCall = this;
307 ++Info.CallStackDepth;
308 }
309
310 CallStackFrame::~CallStackFrame() {
311 assert(Info.CurrentCall == this && "calls retired out of order");
312 --Info.CallStackDepth;
313 Info.CurrentCall = Caller;
314 }
315
John McCall93d91dc2010-05-07 17:22:02 +0000316 struct ComplexValue {
317 private:
318 bool IsInt;
319
320 public:
321 APSInt IntReal, IntImag;
322 APFloat FloatReal, FloatImag;
323
324 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
325
326 void makeComplexFloat() { IsInt = false; }
327 bool isComplexFloat() const { return !IsInt; }
328 APFloat &getComplexFloatReal() { return FloatReal; }
329 APFloat &getComplexFloatImag() { return FloatImag; }
330
331 void makeComplexInt() { IsInt = true; }
332 bool isComplexInt() const { return IsInt; }
333 APSInt &getComplexIntReal() { return IntReal; }
334 APSInt &getComplexIntImag() { return IntImag; }
335
Richard Smith0b0a0b62011-10-29 20:57:55 +0000336 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000337 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000338 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000339 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000340 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000341 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000342 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000343 assert(v.isComplexFloat() || v.isComplexInt());
344 if (v.isComplexFloat()) {
345 makeComplexFloat();
346 FloatReal = v.getComplexFloatReal();
347 FloatImag = v.getComplexFloatImag();
348 } else {
349 makeComplexInt();
350 IntReal = v.getComplexIntReal();
351 IntImag = v.getComplexIntImag();
352 }
353 }
John McCall93d91dc2010-05-07 17:22:02 +0000354 };
John McCall45d55e42010-05-07 21:00:08 +0000355
356 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000357 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000358 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000359 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000360 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000361
Richard Smithce40ad62011-11-12 22:28:03 +0000362 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000363 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000364 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000365 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000366 SubobjectDesignator &getLValueDesignator() { return Designator; }
367 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000368
Richard Smith0b0a0b62011-10-29 20:57:55 +0000369 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000370 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000371 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000372 void setFrom(const CCValue &V) {
373 assert(V.isLValue());
374 Base = V.getLValueBase();
375 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000376 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000377 Designator = V.getLValueDesignator();
378 }
379
Richard Smithce40ad62011-11-12 22:28:03 +0000380 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
381 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000382 Offset = CharUnits::Zero();
383 Frame = F;
384 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000385 }
John McCall45d55e42010-05-07 21:00:08 +0000386 };
Richard Smith027bf112011-11-17 22:56:20 +0000387
388 struct MemberPtr {
389 MemberPtr() {}
390 explicit MemberPtr(const ValueDecl *Decl) :
391 DeclAndIsDerivedMember(Decl, false), Path() {}
392
393 /// The member or (direct or indirect) field referred to by this member
394 /// pointer, or 0 if this is a null member pointer.
395 const ValueDecl *getDecl() const {
396 return DeclAndIsDerivedMember.getPointer();
397 }
398 /// Is this actually a member of some type derived from the relevant class?
399 bool isDerivedMember() const {
400 return DeclAndIsDerivedMember.getInt();
401 }
402 /// Get the class which the declaration actually lives in.
403 const CXXRecordDecl *getContainingRecord() const {
404 return cast<CXXRecordDecl>(
405 DeclAndIsDerivedMember.getPointer()->getDeclContext());
406 }
407
408 void moveInto(CCValue &V) const {
409 V = CCValue(getDecl(), isDerivedMember(), Path);
410 }
411 void setFrom(const CCValue &V) {
412 assert(V.isMemberPointer());
413 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
414 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
415 Path.clear();
416 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
417 Path.insert(Path.end(), P.begin(), P.end());
418 }
419
420 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
421 /// whether the member is a member of some class derived from the class type
422 /// of the member pointer.
423 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
424 /// Path - The path of base/derived classes from the member declaration's
425 /// class (exclusive) to the class type of the member pointer (inclusive).
426 SmallVector<const CXXRecordDecl*, 4> Path;
427
428 /// Perform a cast towards the class of the Decl (either up or down the
429 /// hierarchy).
430 bool castBack(const CXXRecordDecl *Class) {
431 assert(!Path.empty());
432 const CXXRecordDecl *Expected;
433 if (Path.size() >= 2)
434 Expected = Path[Path.size() - 2];
435 else
436 Expected = getContainingRecord();
437 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
438 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
439 // if B does not contain the original member and is not a base or
440 // derived class of the class containing the original member, the result
441 // of the cast is undefined.
442 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
443 // (D::*). We consider that to be a language defect.
444 return false;
445 }
446 Path.pop_back();
447 return true;
448 }
449 /// Perform a base-to-derived member pointer cast.
450 bool castToDerived(const CXXRecordDecl *Derived) {
451 if (!getDecl())
452 return true;
453 if (!isDerivedMember()) {
454 Path.push_back(Derived);
455 return true;
456 }
457 if (!castBack(Derived))
458 return false;
459 if (Path.empty())
460 DeclAndIsDerivedMember.setInt(false);
461 return true;
462 }
463 /// Perform a derived-to-base member pointer cast.
464 bool castToBase(const CXXRecordDecl *Base) {
465 if (!getDecl())
466 return true;
467 if (Path.empty())
468 DeclAndIsDerivedMember.setInt(true);
469 if (isDerivedMember()) {
470 Path.push_back(Base);
471 return true;
472 }
473 return castBack(Base);
474 }
475 };
John McCall93d91dc2010-05-07 17:22:02 +0000476}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000477
Richard Smith0b0a0b62011-10-29 20:57:55 +0000478static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000479static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +0000480 const LValue &This, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000481static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
482static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000483static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
484 EvalInfo &Info);
485static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000486static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000487static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000488 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000489static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000490static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000491
492//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000493// Misc utilities
494//===----------------------------------------------------------------------===//
495
Richard Smithd62306a2011-11-10 06:34:14 +0000496/// Should this call expression be treated as a string literal?
497static bool IsStringLiteralCall(const CallExpr *E) {
498 unsigned Builtin = E->isBuiltinCall();
499 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
500 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
501}
502
Richard Smithce40ad62011-11-12 22:28:03 +0000503static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000504 // C++11 [expr.const]p3 An address constant expression is a prvalue core
505 // constant expression of pointer type that evaluates to...
506
507 // ... a null pointer value, or a prvalue core constant expression of type
508 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000509 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000510
Richard Smithce40ad62011-11-12 22:28:03 +0000511 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
512 // ... the address of an object with static storage duration,
513 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
514 return VD->hasGlobalStorage();
515 // ... the address of a function,
516 return isa<FunctionDecl>(D);
517 }
518
519 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000520 switch (E->getStmtClass()) {
521 default:
522 return false;
Richard Smithd62306a2011-11-10 06:34:14 +0000523 case Expr::CompoundLiteralExprClass:
524 return cast<CompoundLiteralExpr>(E)->isFileScope();
525 // A string literal has static storage duration.
526 case Expr::StringLiteralClass:
527 case Expr::PredefinedExprClass:
528 case Expr::ObjCStringLiteralClass:
529 case Expr::ObjCEncodeExprClass:
530 return true;
531 case Expr::CallExprClass:
532 return IsStringLiteralCall(cast<CallExpr>(E));
533 // For GCC compatibility, &&label has static storage duration.
534 case Expr::AddrLabelExprClass:
535 return true;
536 // A Block literal expression may be used as the initialization value for
537 // Block variables at global or local static scope.
538 case Expr::BlockExprClass:
539 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
540 }
John McCall95007602010-05-10 23:27:23 +0000541}
542
Richard Smith80815602011-11-07 05:07:52 +0000543/// Check that this reference or pointer core constant expression is a valid
544/// value for a constant expression. Type T should be either LValue or CCValue.
545template<typename T>
546static bool CheckLValueConstantExpression(const T &LVal, APValue &Value) {
547 if (!IsGlobalLValue(LVal.getLValueBase()))
548 return false;
549
550 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
551 // A constant expression must refer to an object or be a null pointer.
Richard Smith027bf112011-11-17 22:56:20 +0000552 if (Designator.Invalid ||
Richard Smith80815602011-11-07 05:07:52 +0000553 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smith80815602011-11-07 05:07:52 +0000554 // FIXME: This is not a constant expression.
555 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
556 APValue::NoLValuePath());
557 return true;
558 }
559
560 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smith027bf112011-11-17 22:56:20 +0000561 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith80815602011-11-07 05:07:52 +0000562 return true;
563}
564
Richard Smith0b0a0b62011-10-29 20:57:55 +0000565/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000566/// constant expression, and if it is, produce the corresponding constant value.
567static bool CheckConstantExpression(const CCValue &CCValue, APValue &Value) {
Richard Smith80815602011-11-07 05:07:52 +0000568 if (!CCValue.isLValue()) {
569 Value = CCValue;
570 return true;
571 }
572 return CheckLValueConstantExpression(CCValue, Value);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000573}
574
Richard Smith83c68212011-10-31 05:11:32 +0000575const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000576 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000577}
578
579static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000580 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000581}
582
Richard Smithcecf1842011-11-01 21:06:14 +0000583static bool IsWeakLValue(const LValue &Value) {
584 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000585 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000586}
587
Richard Smith027bf112011-11-17 22:56:20 +0000588static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000589 // A null base expression indicates a null pointer. These are always
590 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000591 if (!Value.getLValueBase()) {
592 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000593 return true;
594 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000595
John McCall95007602010-05-10 23:27:23 +0000596 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000597 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000598 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000599
Richard Smith027bf112011-11-17 22:56:20 +0000600 // We have a non-null base. These are generally known to be true, but if it's
601 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000602 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000603 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000604 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000605}
606
Richard Smith0b0a0b62011-10-29 20:57:55 +0000607static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000608 switch (Val.getKind()) {
609 case APValue::Uninitialized:
610 return false;
611 case APValue::Int:
612 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000613 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000614 case APValue::Float:
615 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000616 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000617 case APValue::ComplexInt:
618 Result = Val.getComplexIntReal().getBoolValue() ||
619 Val.getComplexIntImag().getBoolValue();
620 return true;
621 case APValue::ComplexFloat:
622 Result = !Val.getComplexFloatReal().isZero() ||
623 !Val.getComplexFloatImag().isZero();
624 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000625 case APValue::LValue:
626 return EvalPointerValueAsBool(Val, Result);
627 case APValue::MemberPointer:
628 Result = Val.getMemberPointerDecl();
629 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000630 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000631 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000632 case APValue::Struct:
633 case APValue::Union:
Richard Smith11562c52011-10-28 17:51:58 +0000634 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000635 }
636
Richard Smith11562c52011-10-28 17:51:58 +0000637 llvm_unreachable("unknown APValue kind");
638}
639
640static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
641 EvalInfo &Info) {
642 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000643 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000644 if (!Evaluate(Val, Info, E))
645 return false;
646 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000647}
648
Mike Stump11289f42009-09-09 15:08:12 +0000649static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000650 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000651 unsigned DestWidth = Ctx.getIntWidth(DestType);
652 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000653 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000654
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000655 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000656 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000657 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000658 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
659 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000660}
661
Mike Stump11289f42009-09-09 15:08:12 +0000662static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000663 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000664 bool ignored;
665 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000666 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000667 APFloat::rmNearestTiesToEven, &ignored);
668 return Result;
669}
670
Mike Stump11289f42009-09-09 15:08:12 +0000671static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000672 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000673 unsigned DestWidth = Ctx.getIntWidth(DestType);
674 APSInt Result = Value;
675 // Figure out if this is a truncate, extend or noop cast.
676 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000677 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000678 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000679 return Result;
680}
681
Mike Stump11289f42009-09-09 15:08:12 +0000682static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000683 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000684
685 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
686 Result.convertFromAPInt(Value, Value.isSigned(),
687 APFloat::rmNearestTiesToEven);
688 return Result;
689}
690
Richard Smith027bf112011-11-17 22:56:20 +0000691static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
692 const CXXRecordDecl *&MostDerivedType,
693 unsigned &MostDerivedPathLength,
694 bool &MostDerivedIsArrayElement) {
695 const SubobjectDesignator &D = LVal.Designator;
696 if (D.Invalid || !LVal.Base)
Richard Smithd62306a2011-11-10 06:34:14 +0000697 return false;
698
Richard Smith027bf112011-11-17 22:56:20 +0000699 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smithd62306a2011-11-10 06:34:14 +0000700
701 // Find path prefix which leads to the most-derived subobject.
Richard Smithd62306a2011-11-10 06:34:14 +0000702 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smith027bf112011-11-17 22:56:20 +0000703 MostDerivedPathLength = 0;
704 MostDerivedIsArrayElement = false;
Richard Smithd62306a2011-11-10 06:34:14 +0000705
706 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
707 bool IsArray = T && T->isArrayType();
708 if (IsArray)
709 T = T->getBaseElementTypeUnsafe();
710 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
711 T = FD->getType().getTypePtr();
712 else
713 T = 0;
714
715 if (T) {
716 MostDerivedType = T->getAsCXXRecordDecl();
717 MostDerivedPathLength = I + 1;
718 MostDerivedIsArrayElement = IsArray;
719 }
720 }
721
Richard Smithd62306a2011-11-10 06:34:14 +0000722 // (B*)&d + 1 has no most-derived object.
723 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
724 return false;
725
Richard Smith027bf112011-11-17 22:56:20 +0000726 return MostDerivedType != 0;
727}
728
729static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
730 const RecordDecl *TruncatedType,
731 unsigned TruncatedElements,
732 bool IsArrayElement) {
733 SubobjectDesignator &D = Result.Designator;
734 const RecordDecl *RD = TruncatedType;
735 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +0000736 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
737 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +0000738 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +0000739 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +0000740 else
Richard Smithd62306a2011-11-10 06:34:14 +0000741 Result.Offset -= Layout.getBaseClassOffset(Base);
742 RD = Base;
743 }
Richard Smith027bf112011-11-17 22:56:20 +0000744 D.Entries.resize(TruncatedElements);
745 D.ArrayElement = IsArrayElement;
746}
747
748/// If the given LValue refers to a base subobject of some object, find the most
749/// derived object and the corresponding complete record type. This is necessary
750/// in order to find the offset of a virtual base class.
751static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
752 const CXXRecordDecl *&MostDerivedType) {
753 unsigned MostDerivedPathLength;
754 bool MostDerivedIsArrayElement;
755 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
756 MostDerivedPathLength, MostDerivedIsArrayElement))
757 return false;
758
759 // Remove the trailing base class path entries and their offsets.
760 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
761 MostDerivedIsArrayElement);
Richard Smithd62306a2011-11-10 06:34:14 +0000762 return true;
763}
764
765static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
766 const CXXRecordDecl *Derived,
767 const CXXRecordDecl *Base,
768 const ASTRecordLayout *RL = 0) {
769 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
770 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
771 Obj.Designator.addDecl(Base, /*Virtual*/ false);
772}
773
774static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
775 const CXXRecordDecl *DerivedDecl,
776 const CXXBaseSpecifier *Base) {
777 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
778
779 if (!Base->isVirtual()) {
780 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
781 return true;
782 }
783
784 // Extract most-derived object and corresponding type.
785 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
786 return false;
787
788 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
789 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
790 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
791 return true;
792}
793
794/// Update LVal to refer to the given field, which must be a member of the type
795/// currently described by LVal.
796static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
797 const FieldDecl *FD,
798 const ASTRecordLayout *RL = 0) {
799 if (!RL)
800 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
801
802 unsigned I = FD->getFieldIndex();
803 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
804 LVal.Designator.addDecl(FD);
805}
806
807/// Get the size of the given type in char units.
808static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
809 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
810 // extension.
811 if (Type->isVoidType() || Type->isFunctionType()) {
812 Size = CharUnits::One();
813 return true;
814 }
815
816 if (!Type->isConstantSizeType()) {
817 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
818 return false;
819 }
820
821 Size = Info.Ctx.getTypeSizeInChars(Type);
822 return true;
823}
824
825/// Update a pointer value to model pointer arithmetic.
826/// \param Info - Information about the ongoing evaluation.
827/// \param LVal - The pointer value to be updated.
828/// \param EltTy - The pointee type represented by LVal.
829/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
830static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
831 QualType EltTy, int64_t Adjustment) {
832 CharUnits SizeOfPointee;
833 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
834 return false;
835
836 // Compute the new offset in the appropriate width.
837 LVal.Offset += Adjustment * SizeOfPointee;
838 LVal.Designator.adjustIndex(Adjustment);
839 return true;
840}
841
Richard Smith27908702011-10-24 17:54:18 +0000842/// Try to evaluate the initializer for a variable declaration.
Richard Smithce40ad62011-11-12 22:28:03 +0000843static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +0000844 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000845 // If this is a parameter to an active constexpr function call, perform
846 // argument substitution.
847 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithfec09922011-11-01 16:57:24 +0000848 if (!Frame || !Frame->Arguments)
849 return false;
850 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
851 return true;
Richard Smith254a73d2011-10-28 22:34:42 +0000852 }
Richard Smith27908702011-10-24 17:54:18 +0000853
Richard Smithd62306a2011-11-10 06:34:14 +0000854 // If we're currently evaluating the initializer of this declaration, use that
855 // in-flight value.
856 if (Info.EvaluatingDecl == VD) {
857 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
858 return !Result.isUninit();
859 }
860
Richard Smithcecf1842011-11-01 21:06:14 +0000861 // Never evaluate the initializer of a weak variable. We can't be sure that
862 // this is the definition which will be used.
Lang Hamesd42bb472011-12-05 20:16:26 +0000863 if (VD->isWeak())
Richard Smithcecf1842011-11-01 21:06:14 +0000864 return false;
865
Richard Smith27908702011-10-24 17:54:18 +0000866 const Expr *Init = VD->getAnyInitializer();
Richard Smithec8dcd22011-11-08 01:31:09 +0000867 if (!Init || Init->isValueDependent())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000868 return false;
Richard Smith27908702011-10-24 17:54:18 +0000869
Richard Smith0b0a0b62011-10-29 20:57:55 +0000870 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smithfec09922011-11-01 16:57:24 +0000871 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000872 return !Result.isUninit();
873 }
Richard Smith27908702011-10-24 17:54:18 +0000874
875 if (VD->isEvaluatingValue())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000876 return false;
Richard Smith27908702011-10-24 17:54:18 +0000877
878 VD->setEvaluatingValue();
879
Richard Smith0b0a0b62011-10-29 20:57:55 +0000880 Expr::EvalStatus EStatus;
881 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smithd62306a2011-11-10 06:34:14 +0000882 APValue EvalResult;
883 InitInfo.setEvaluatingDecl(VD, EvalResult);
884 LValue LVal;
Richard Smithce40ad62011-11-12 22:28:03 +0000885 LVal.set(VD);
Richard Smith11562c52011-10-28 17:51:58 +0000886 // FIXME: The caller will need to know whether the value was a constant
887 // expression. If not, we should propagate up a diagnostic.
Richard Smithd62306a2011-11-10 06:34:14 +0000888 if (!EvaluateConstantExpression(EvalResult, InitInfo, LVal, Init)) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000889 // FIXME: If the evaluation failure was not permanent (for instance, if we
890 // hit a variable with no declaration yet, or a constexpr function with no
891 // definition yet), the standard is unclear as to how we should behave.
892 //
893 // Either the initializer should be evaluated when the variable is defined,
894 // or a failed evaluation of the initializer should be reattempted each time
895 // it is used.
Richard Smith27908702011-10-24 17:54:18 +0000896 VD->setEvaluatedValue(APValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000897 return false;
898 }
Richard Smith27908702011-10-24 17:54:18 +0000899
Richard Smithed5165f2011-11-04 05:33:44 +0000900 VD->setEvaluatedValue(EvalResult);
901 Result = CCValue(EvalResult, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000902 return true;
Richard Smith27908702011-10-24 17:54:18 +0000903}
904
Richard Smith11562c52011-10-28 17:51:58 +0000905static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000906 Qualifiers Quals = T.getQualifiers();
907 return Quals.hasConst() && !Quals.hasVolatile();
908}
909
Richard Smithe97cbd72011-11-11 04:05:33 +0000910/// Get the base index of the given base class within an APValue representing
911/// the given derived class.
912static unsigned getBaseIndex(const CXXRecordDecl *Derived,
913 const CXXRecordDecl *Base) {
914 Base = Base->getCanonicalDecl();
915 unsigned Index = 0;
916 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
917 E = Derived->bases_end(); I != E; ++I, ++Index) {
918 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
919 return Index;
920 }
921
922 llvm_unreachable("base class missing from derived class's bases list");
923}
924
Richard Smithf3e9e432011-11-07 09:22:26 +0000925/// Extract the designated sub-object of an rvalue.
926static bool ExtractSubobject(EvalInfo &Info, CCValue &Obj, QualType ObjType,
927 const SubobjectDesignator &Sub, QualType SubType) {
928 if (Sub.Invalid || Sub.OnePastTheEnd)
929 return false;
Richard Smith6804be52011-11-11 08:28:03 +0000930 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +0000931 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +0000932
933 assert(!Obj.isLValue() && "extracting subobject of lvalue");
934 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +0000935 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +0000936 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000937 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +0000938 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +0000939 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
940 if (!CAT)
941 return false;
942 uint64_t Index = Sub.Entries[I].ArrayIndex;
943 if (CAT->getSize().ule(Index))
944 return false;
945 if (O->getArrayInitializedElts() > Index)
946 O = &O->getArrayInitializedElt(Index);
947 else
948 O = &O->getArrayFiller();
949 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +0000950 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
951 // Next subobject is a class, struct or union field.
952 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
953 if (RD->isUnion()) {
954 const FieldDecl *UnionField = O->getUnionField();
955 if (!UnionField ||
956 UnionField->getCanonicalDecl() != Field->getCanonicalDecl())
957 return false;
958 O = &O->getUnionValue();
959 } else
960 O = &O->getStructField(Field->getFieldIndex());
961 ObjType = Field->getType();
Richard Smithf3e9e432011-11-07 09:22:26 +0000962 } else {
Richard Smithd62306a2011-11-10 06:34:14 +0000963 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +0000964 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
965 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
966 O = &O->getStructBase(getBaseIndex(Derived, Base));
967 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +0000968 }
Richard Smithd62306a2011-11-10 06:34:14 +0000969
970 if (O->isUninit())
971 return false;
Richard Smithf3e9e432011-11-07 09:22:26 +0000972 }
973
Richard Smithf3e9e432011-11-07 09:22:26 +0000974 Obj = CCValue(*O, CCValue::GlobalValue());
975 return true;
976}
977
Richard Smithd62306a2011-11-10 06:34:14 +0000978/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
979/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
980/// for looking up the glvalue referred to by an entity of reference type.
981///
982/// \param Info - Information about the ongoing evaluation.
983/// \param Type - The type we expect this conversion to produce.
984/// \param LVal - The glvalue on which we are attempting to perform this action.
985/// \param RVal - The produced value will be placed here.
Richard Smithf3e9e432011-11-07 09:22:26 +0000986static bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
987 const LValue &LVal, CCValue &RVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000988 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +0000989 CallStackFrame *Frame = LVal.Frame;
Richard Smith11562c52011-10-28 17:51:58 +0000990
991 // FIXME: Indirection through a null pointer deserves a diagnostic.
Richard Smithce40ad62011-11-12 22:28:03 +0000992 if (!LVal.Base)
Richard Smith11562c52011-10-28 17:51:58 +0000993 return false;
994
Richard Smithce40ad62011-11-12 22:28:03 +0000995 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +0000996 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
997 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +0000998 // expressions are constant expressions too. Inside constexpr functions,
999 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001000 // In C, such things can also be folded, although they are not ICEs.
1001 //
Richard Smith254a73d2011-10-28 22:34:42 +00001002 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
1003 // interpretation of C++11 suggests that volatile parameters are OK if
1004 // they're never read (there's no prohibition against constructing volatile
1005 // objects in constant expressions), but lvalue-to-rvalue conversions on
1006 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +00001007 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smitha08acd82011-11-07 03:22:51 +00001008 if (!VD || VD->isInvalidDecl())
Richard Smith96e0c102011-11-04 02:25:55 +00001009 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00001010 QualType VT = VD->getType();
Richard Smith96e0c102011-11-04 02:25:55 +00001011 if (!isa<ParmVarDecl>(VD)) {
1012 if (!IsConstNonVolatile(VT))
1013 return false;
Richard Smitha08acd82011-11-07 03:22:51 +00001014 // FIXME: Allow folding of values of any literal type in all languages.
1015 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
1016 !VD->isConstexpr())
Richard Smith96e0c102011-11-04 02:25:55 +00001017 return false;
1018 }
Richard Smithce40ad62011-11-12 22:28:03 +00001019 if (!EvaluateVarDeclInit(Info, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001020 return false;
1021
Richard Smith0b0a0b62011-10-29 20:57:55 +00001022 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf3e9e432011-11-07 09:22:26 +00001023 return ExtractSubobject(Info, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001024
1025 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1026 // conversion. This happens when the declaration and the lvalue should be
1027 // considered synonymous, for instance when initializing an array of char
1028 // from a string literal. Continue as if the initializer lvalue was the
1029 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001030 assert(RVal.getLValueOffset().isZero() &&
1031 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001032 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001033 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001034 }
1035
Richard Smith96e0c102011-11-04 02:25:55 +00001036 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1037 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1038 const SubobjectDesignator &Designator = LVal.Designator;
1039 if (Designator.Invalid || Designator.Entries.size() != 1)
1040 return false;
1041
1042 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001043 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith96e0c102011-11-04 02:25:55 +00001044 if (Index > S->getLength())
1045 return false;
1046 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1047 Type->isUnsignedIntegerType());
1048 if (Index < S->getLength())
1049 Value = S->getCodeUnit(Index);
1050 RVal = CCValue(Value);
1051 return true;
1052 }
1053
Richard Smithf3e9e432011-11-07 09:22:26 +00001054 if (Frame) {
1055 // If this is a temporary expression with a nontrivial initializer, grab the
1056 // value from the relevant stack frame.
1057 RVal = Frame->Temporaries[Base];
1058 } else if (const CompoundLiteralExpr *CLE
1059 = dyn_cast<CompoundLiteralExpr>(Base)) {
1060 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1061 // initializer until now for such expressions. Such an expression can't be
1062 // an ICE in C, so this only matters for fold.
1063 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1064 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1065 return false;
1066 } else
Richard Smith96e0c102011-11-04 02:25:55 +00001067 return false;
1068
Richard Smithf3e9e432011-11-07 09:22:26 +00001069 return ExtractSubobject(Info, RVal, Base->getType(), LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001070}
1071
Richard Smithe97cbd72011-11-11 04:05:33 +00001072/// Build an lvalue for the object argument of a member function call.
1073static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1074 LValue &This) {
1075 if (Object->getType()->isPointerType())
1076 return EvaluatePointer(Object, This, Info);
1077
1078 if (Object->isGLValue())
1079 return EvaluateLValue(Object, This, Info);
1080
Richard Smith027bf112011-11-17 22:56:20 +00001081 if (Object->getType()->isLiteralType())
1082 return EvaluateTemporary(Object, This, Info);
1083
1084 return false;
1085}
1086
1087/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1088/// lvalue referring to the result.
1089///
1090/// \param Info - Information about the ongoing evaluation.
1091/// \param BO - The member pointer access operation.
1092/// \param LV - Filled in with a reference to the resulting object.
1093/// \param IncludeMember - Specifies whether the member itself is included in
1094/// the resulting LValue subobject designator. This is not possible when
1095/// creating a bound member function.
1096/// \return The field or method declaration to which the member pointer refers,
1097/// or 0 if evaluation fails.
1098static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1099 const BinaryOperator *BO,
1100 LValue &LV,
1101 bool IncludeMember = true) {
1102 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1103
1104 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1105 return 0;
1106
1107 MemberPtr MemPtr;
1108 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1109 return 0;
1110
1111 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1112 // member value, the behavior is undefined.
1113 if (!MemPtr.getDecl())
1114 return 0;
1115
1116 if (MemPtr.isDerivedMember()) {
1117 // This is a member of some derived class. Truncate LV appropriately.
1118 const CXXRecordDecl *MostDerivedType;
1119 unsigned MostDerivedPathLength;
1120 bool MostDerivedIsArrayElement;
1121 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1122 MostDerivedIsArrayElement))
1123 return 0;
1124
1125 // The end of the derived-to-base path for the base object must match the
1126 // derived-to-base path for the member pointer.
1127 if (MostDerivedPathLength + MemPtr.Path.size() >
1128 LV.Designator.Entries.size())
1129 return 0;
1130 unsigned PathLengthToMember =
1131 LV.Designator.Entries.size() - MemPtr.Path.size();
1132 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1133 const CXXRecordDecl *LVDecl = getAsBaseClass(
1134 LV.Designator.Entries[PathLengthToMember + I]);
1135 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1136 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1137 return 0;
1138 }
1139
1140 // Truncate the lvalue to the appropriate derived class.
1141 bool ResultIsArray = false;
1142 if (PathLengthToMember == MostDerivedPathLength)
1143 ResultIsArray = MostDerivedIsArrayElement;
1144 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1145 PathLengthToMember, ResultIsArray);
1146 } else if (!MemPtr.Path.empty()) {
1147 // Extend the LValue path with the member pointer's path.
1148 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1149 MemPtr.Path.size() + IncludeMember);
1150
1151 // Walk down to the appropriate base class.
1152 QualType LVType = BO->getLHS()->getType();
1153 if (const PointerType *PT = LVType->getAs<PointerType>())
1154 LVType = PT->getPointeeType();
1155 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1156 assert(RD && "member pointer access on non-class-type expression");
1157 // The first class in the path is that of the lvalue.
1158 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1159 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1160 HandleLValueDirectBase(Info, LV, RD, Base);
1161 RD = Base;
1162 }
1163 // Finally cast to the class containing the member.
1164 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1165 }
1166
1167 // Add the member. Note that we cannot build bound member functions here.
1168 if (IncludeMember) {
1169 // FIXME: Deal with IndirectFieldDecls.
1170 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1171 if (!FD) return 0;
1172 HandleLValueMember(Info, LV, FD);
1173 }
1174
1175 return MemPtr.getDecl();
1176}
1177
1178/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1179/// the provided lvalue, which currently refers to the base object.
1180static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1181 LValue &Result) {
1182 const CXXRecordDecl *MostDerivedType;
1183 unsigned MostDerivedPathLength;
1184 bool MostDerivedIsArrayElement;
1185
1186 // Check this cast doesn't take us outside the object.
1187 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1188 MostDerivedPathLength,
1189 MostDerivedIsArrayElement))
1190 return false;
1191 SubobjectDesignator &D = Result.Designator;
1192 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1193 return false;
1194
1195 // Check the type of the final cast. We don't need to check the path,
1196 // since a cast can only be formed if the path is unique.
1197 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1198 bool ResultIsArray = false;
1199 QualType TargetQT = E->getType();
1200 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1201 TargetQT = PT->getPointeeType();
1202 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1203 const CXXRecordDecl *FinalType;
1204 if (NewEntriesSize == MostDerivedPathLength) {
1205 ResultIsArray = MostDerivedIsArrayElement;
1206 FinalType = MostDerivedType;
1207 } else
1208 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1209 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1210 return false;
1211
1212 // Truncate the lvalue to the appropriate derived class.
1213 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1214 ResultIsArray);
1215 return true;
Richard Smithe97cbd72011-11-11 04:05:33 +00001216}
1217
Mike Stump876387b2009-10-27 22:09:17 +00001218namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001219enum EvalStmtResult {
1220 /// Evaluation failed.
1221 ESR_Failed,
1222 /// Hit a 'return' statement.
1223 ESR_Returned,
1224 /// Evaluation succeeded.
1225 ESR_Succeeded
1226};
1227}
1228
1229// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001230static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001231 const Stmt *S) {
1232 switch (S->getStmtClass()) {
1233 default:
1234 return ESR_Failed;
1235
1236 case Stmt::NullStmtClass:
1237 case Stmt::DeclStmtClass:
1238 return ESR_Succeeded;
1239
1240 case Stmt::ReturnStmtClass:
1241 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
1242 return ESR_Returned;
1243 return ESR_Failed;
1244
1245 case Stmt::CompoundStmtClass: {
1246 const CompoundStmt *CS = cast<CompoundStmt>(S);
1247 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1248 BE = CS->body_end(); BI != BE; ++BI) {
1249 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1250 if (ESR != ESR_Succeeded)
1251 return ESR;
1252 }
1253 return ESR_Succeeded;
1254 }
1255 }
1256}
1257
Richard Smithd62306a2011-11-10 06:34:14 +00001258namespace {
Richard Smith60494462011-11-11 05:48:57 +00001259typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001260}
1261
1262/// EvaluateArgs - Evaluate the arguments to a function call.
1263static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1264 EvalInfo &Info) {
1265 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1266 I != E; ++I)
1267 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1268 return false;
1269 return true;
1270}
1271
Richard Smith254a73d2011-10-28 22:34:42 +00001272/// Evaluate a function call.
Richard Smithe97cbd72011-11-11 04:05:33 +00001273static bool HandleFunctionCall(const LValue *This, ArrayRef<const Expr*> Args,
1274 const Stmt *Body, EvalInfo &Info,
1275 CCValue &Result) {
Richard Smith9a568822011-11-21 19:36:32 +00001276 if (Info.atCallLimit())
Richard Smith254a73d2011-10-28 22:34:42 +00001277 return false;
1278
Richard Smithd62306a2011-11-10 06:34:14 +00001279 ArgVector ArgValues(Args.size());
1280 if (!EvaluateArgs(Args, ArgValues, Info))
1281 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001282
Richard Smithd62306a2011-11-10 06:34:14 +00001283 CallStackFrame Frame(Info, This, ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001284 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1285}
1286
Richard Smithd62306a2011-11-10 06:34:14 +00001287/// Evaluate a constructor call.
Richard Smithe97cbd72011-11-11 04:05:33 +00001288static bool HandleConstructorCall(const LValue &This,
1289 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001290 const CXXConstructorDecl *Definition,
Richard Smithe97cbd72011-11-11 04:05:33 +00001291 EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +00001292 APValue &Result) {
Richard Smith9a568822011-11-21 19:36:32 +00001293 if (Info.atCallLimit())
Richard Smithd62306a2011-11-10 06:34:14 +00001294 return false;
1295
1296 ArgVector ArgValues(Args.size());
1297 if (!EvaluateArgs(Args, ArgValues, Info))
1298 return false;
1299
1300 CallStackFrame Frame(Info, &This, ArgValues.data());
1301
1302 // If it's a delegating constructor, just delegate.
1303 if (Definition->isDelegatingConstructor()) {
1304 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1305 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1306 }
1307
1308 // Reserve space for the struct members.
1309 const CXXRecordDecl *RD = Definition->getParent();
1310 if (!RD->isUnion())
1311 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1312 std::distance(RD->field_begin(), RD->field_end()));
1313
1314 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1315
1316 unsigned BasesSeen = 0;
1317#ifndef NDEBUG
1318 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1319#endif
1320 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1321 E = Definition->init_end(); I != E; ++I) {
1322 if ((*I)->isBaseInitializer()) {
1323 QualType BaseType((*I)->getBaseClass(), 0);
1324#ifndef NDEBUG
1325 // Non-virtual base classes are initialized in the order in the class
1326 // definition. We cannot have a virtual base class for a literal type.
1327 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1328 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1329 "base class initializers not in expected order");
1330 ++BaseIt;
1331#endif
1332 LValue Subobject = This;
1333 HandleLValueDirectBase(Info, Subobject, RD,
1334 BaseType->getAsCXXRecordDecl(), &Layout);
1335 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1336 Subobject, (*I)->getInit()))
1337 return false;
1338 } else if (FieldDecl *FD = (*I)->getMember()) {
1339 LValue Subobject = This;
1340 HandleLValueMember(Info, Subobject, FD, &Layout);
1341 if (RD->isUnion()) {
1342 Result = APValue(FD);
1343 if (!EvaluateConstantExpression(Result.getUnionValue(), Info,
1344 Subobject, (*I)->getInit()))
1345 return false;
1346 } else if (!EvaluateConstantExpression(
1347 Result.getStructField(FD->getFieldIndex()),
1348 Info, Subobject, (*I)->getInit()))
1349 return false;
1350 } else {
1351 // FIXME: handle indirect field initializers
1352 return false;
1353 }
1354 }
1355
1356 return true;
1357}
1358
Richard Smith254a73d2011-10-28 22:34:42 +00001359namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001360class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001361 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001362 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001363public:
1364
Richard Smith725810a2011-10-16 21:26:27 +00001365 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001366
1367 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001368 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001369 return true;
1370 }
1371
Peter Collingbournee9200682011-05-13 03:29:01 +00001372 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1373 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001374 return Visit(E->getResultExpr());
1375 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001376 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001377 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001378 return true;
1379 return false;
1380 }
John McCall31168b02011-06-15 23:02:42 +00001381 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001382 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001383 return true;
1384 return false;
1385 }
1386 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001387 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001388 return true;
1389 return false;
1390 }
1391
Mike Stump876387b2009-10-27 22:09:17 +00001392 // We don't want to evaluate BlockExprs multiple times, as they generate
1393 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001394 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1395 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1396 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001397 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001398 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1399 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1400 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1401 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1402 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1403 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001404 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001405 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001406 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001407 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001408 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001409 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1410 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1411 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1412 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001413 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001414 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1415 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1416 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1417 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1418 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001419 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001420 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001421 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001422 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001423 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001424
1425 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001426 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001427 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1428 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001429 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001430 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001431 return false;
1432 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001433
Peter Collingbournee9200682011-05-13 03:29:01 +00001434 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001435};
1436
John McCallc07a0c72011-02-17 10:25:35 +00001437class OpaqueValueEvaluation {
1438 EvalInfo &info;
1439 OpaqueValueExpr *opaqueValue;
1440
1441public:
1442 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1443 Expr *value)
1444 : info(info), opaqueValue(opaqueValue) {
1445
1446 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00001447 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00001448 this->opaqueValue = 0;
1449 return;
1450 }
John McCallc07a0c72011-02-17 10:25:35 +00001451 }
1452
1453 bool hasError() const { return opaqueValue == 0; }
1454
1455 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00001456 // FIXME: This will not work for recursive constexpr functions using opaque
1457 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00001458 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1459 }
1460};
1461
Mike Stump876387b2009-10-27 22:09:17 +00001462} // end anonymous namespace
1463
Eli Friedman9a156e52008-11-12 09:44:48 +00001464//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00001465// Generic Evaluation
1466//===----------------------------------------------------------------------===//
1467namespace {
1468
1469template <class Derived, typename RetTy=void>
1470class ExprEvaluatorBase
1471 : public ConstStmtVisitor<Derived, RetTy> {
1472private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001473 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001474 return static_cast<Derived*>(this)->Success(V, E);
1475 }
1476 RetTy DerivedError(const Expr *E) {
1477 return static_cast<Derived*>(this)->Error(E);
1478 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001479 RetTy DerivedValueInitialization(const Expr *E) {
1480 return static_cast<Derived*>(this)->ValueInitialization(E);
1481 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001482
1483protected:
1484 EvalInfo &Info;
1485 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1486 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1487
Richard Smith4ce706a2011-10-11 21:43:33 +00001488 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
1489
Peter Collingbournee9200682011-05-13 03:29:01 +00001490public:
1491 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1492
1493 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00001494 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00001495 }
1496 RetTy VisitExpr(const Expr *E) {
1497 return DerivedError(E);
1498 }
1499
1500 RetTy VisitParenExpr(const ParenExpr *E)
1501 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1502 RetTy VisitUnaryExtension(const UnaryOperator *E)
1503 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1504 RetTy VisitUnaryPlus(const UnaryOperator *E)
1505 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1506 RetTy VisitChooseExpr(const ChooseExpr *E)
1507 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1508 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1509 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00001510 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1511 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00001512 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1513 { return StmtVisitorTy::Visit(E->getExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001514
Richard Smith027bf112011-11-17 22:56:20 +00001515 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1516 switch (E->getOpcode()) {
1517 default:
1518 return DerivedError(E);
1519
1520 case BO_Comma:
1521 VisitIgnoredValue(E->getLHS());
1522 return StmtVisitorTy::Visit(E->getRHS());
1523
1524 case BO_PtrMemD:
1525 case BO_PtrMemI: {
1526 LValue Obj;
1527 if (!HandleMemberPointerAccess(Info, E, Obj))
1528 return false;
1529 CCValue Result;
1530 if (!HandleLValueToRValueConversion(Info, E->getType(), Obj, Result))
1531 return false;
1532 return DerivedSuccess(Result, E);
1533 }
1534 }
1535 }
1536
Peter Collingbournee9200682011-05-13 03:29:01 +00001537 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1538 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1539 if (opaque.hasError())
1540 return DerivedError(E);
1541
1542 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00001543 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +00001544 return DerivedError(E);
1545
1546 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1547 }
1548
1549 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1550 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00001551 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +00001552 return DerivedError(E);
1553
Richard Smith11562c52011-10-28 17:51:58 +00001554 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00001555 return StmtVisitorTy::Visit(EvalExpr);
1556 }
1557
1558 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001559 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001560 if (!Value) {
1561 const Expr *Source = E->getSourceExpr();
1562 if (!Source)
1563 return DerivedError(E);
1564 if (Source == E) { // sanity checking.
1565 assert(0 && "OpaqueValueExpr recursively refers to itself");
1566 return DerivedError(E);
1567 }
1568 return StmtVisitorTy::Visit(Source);
1569 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001570 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001571 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001572
Richard Smith254a73d2011-10-28 22:34:42 +00001573 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00001574 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00001575 QualType CalleeType = Callee->getType();
1576
Richard Smith254a73d2011-10-28 22:34:42 +00001577 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00001578 LValue *This = 0, ThisVal;
1579 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00001580
Richard Smithe97cbd72011-11-11 04:05:33 +00001581 // Extract function decl and 'this' pointer from the callee.
1582 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smith027bf112011-11-17 22:56:20 +00001583 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
1584 // Explicit bound member calls, such as x.f() or p->g();
1585 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
1586 return DerivedError(ME->getBase());
1587 This = &ThisVal;
1588 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
1589 if (!FD)
1590 return DerivedError(ME);
1591 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
1592 // Indirect bound member calls ('.*' or '->*').
1593 const ValueDecl *Member = HandleMemberPointerAccess(Info, BE, ThisVal,
1594 false);
1595 This = &ThisVal;
1596 FD = dyn_cast_or_null<FunctionDecl>(Member);
1597 if (!FD)
1598 return DerivedError(Callee);
1599 } else
Richard Smithe97cbd72011-11-11 04:05:33 +00001600 return DerivedError(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00001601 } else if (CalleeType->isFunctionPointerType()) {
1602 CCValue Call;
1603 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
Richard Smithce40ad62011-11-12 22:28:03 +00001604 !Call.getLValueOffset().isZero())
Richard Smithe97cbd72011-11-11 04:05:33 +00001605 return DerivedError(Callee);
1606
Richard Smithce40ad62011-11-12 22:28:03 +00001607 FD = dyn_cast_or_null<FunctionDecl>(
1608 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00001609 if (!FD)
1610 return DerivedError(Callee);
1611
1612 // Overloaded operator calls to member functions are represented as normal
1613 // calls with '*this' as the first argument.
1614 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1615 if (MD && !MD->isStatic()) {
1616 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
1617 return false;
1618 This = &ThisVal;
1619 Args = Args.slice(1);
1620 }
1621
1622 // Don't call function pointers which have been cast to some other type.
1623 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
1624 return DerivedError(E);
1625 } else
Devang Patel63104ad2011-11-10 17:47:39 +00001626 return DerivedError(E);
Richard Smith254a73d2011-10-28 22:34:42 +00001627
1628 const FunctionDecl *Definition;
1629 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00001630 CCValue CCResult;
1631 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00001632
1633 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
Richard Smithe97cbd72011-11-11 04:05:33 +00001634 HandleFunctionCall(This, Args, Body, Info, CCResult) &&
Richard Smithed5165f2011-11-04 05:33:44 +00001635 CheckConstantExpression(CCResult, Result))
1636 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00001637
1638 return DerivedError(E);
1639 }
1640
Richard Smith11562c52011-10-28 17:51:58 +00001641 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1642 return StmtVisitorTy::Visit(E->getInitializer());
1643 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001644 RetTy VisitInitListExpr(const InitListExpr *E) {
1645 if (Info.getLangOpts().CPlusPlus0x) {
1646 if (E->getNumInits() == 0)
1647 return DerivedValueInitialization(E);
1648 if (E->getNumInits() == 1)
1649 return StmtVisitorTy::Visit(E->getInit(0));
1650 }
1651 return DerivedError(E);
1652 }
1653 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1654 return DerivedValueInitialization(E);
1655 }
1656 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1657 return DerivedValueInitialization(E);
1658 }
Richard Smith027bf112011-11-17 22:56:20 +00001659 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
1660 return DerivedValueInitialization(E);
1661 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001662
Richard Smithd62306a2011-11-10 06:34:14 +00001663 /// A member expression where the object is a prvalue is itself a prvalue.
1664 RetTy VisitMemberExpr(const MemberExpr *E) {
1665 assert(!E->isArrow() && "missing call to bound member function?");
1666
1667 CCValue Val;
1668 if (!Evaluate(Val, Info, E->getBase()))
1669 return false;
1670
1671 QualType BaseTy = E->getBase()->getType();
1672
1673 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1674 if (!FD) return false;
1675 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
1676 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1677 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1678
1679 SubobjectDesignator Designator;
1680 Designator.addDecl(FD);
1681
1682 return ExtractSubobject(Info, Val, BaseTy, Designator, E->getType()) &&
1683 DerivedSuccess(Val, E);
1684 }
1685
Richard Smith11562c52011-10-28 17:51:58 +00001686 RetTy VisitCastExpr(const CastExpr *E) {
1687 switch (E->getCastKind()) {
1688 default:
1689 break;
1690
1691 case CK_NoOp:
1692 return StmtVisitorTy::Visit(E->getSubExpr());
1693
1694 case CK_LValueToRValue: {
1695 LValue LVal;
1696 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001697 CCValue RVal;
Richard Smith11562c52011-10-28 17:51:58 +00001698 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
1699 return DerivedSuccess(RVal, E);
1700 }
1701 break;
1702 }
1703 }
1704
1705 return DerivedError(E);
1706 }
1707
Richard Smith4a678122011-10-24 18:44:57 +00001708 /// Visit a value which is evaluated, but whose value is ignored.
1709 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001710 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00001711 if (!Evaluate(Scratch, Info, E))
1712 Info.EvalStatus.HasSideEffects = true;
1713 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001714};
1715
1716}
1717
1718//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00001719// Common base class for lvalue and temporary evaluation.
1720//===----------------------------------------------------------------------===//
1721namespace {
1722template<class Derived>
1723class LValueExprEvaluatorBase
1724 : public ExprEvaluatorBase<Derived, bool> {
1725protected:
1726 LValue &Result;
1727 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
1728 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
1729
1730 bool Success(APValue::LValueBase B) {
1731 Result.set(B);
1732 return true;
1733 }
1734
1735public:
1736 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
1737 ExprEvaluatorBaseTy(Info), Result(Result) {}
1738
1739 bool Success(const CCValue &V, const Expr *E) {
1740 Result.setFrom(V);
1741 return true;
1742 }
1743 bool Error(const Expr *E) {
1744 return false;
1745 }
1746
1747 bool CheckValidLValue() {
1748 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
1749 // there are no null references, nor once-past-the-end references.
1750 // FIXME: Check for one-past-the-end array indices
1751 return Result.Base && !Result.Designator.Invalid &&
1752 !Result.Designator.OnePastTheEnd;
1753 }
1754
1755 bool VisitMemberExpr(const MemberExpr *E) {
1756 // Handle non-static data members.
1757 QualType BaseTy;
1758 if (E->isArrow()) {
1759 if (!EvaluatePointer(E->getBase(), Result, this->Info))
1760 return false;
1761 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
1762 } else {
1763 if (!this->Visit(E->getBase()))
1764 return false;
1765 BaseTy = E->getBase()->getType();
1766 }
1767 // FIXME: In C++11, require the result to be a valid lvalue.
1768
1769 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1770 // FIXME: Handle IndirectFieldDecls
1771 if (!FD) return false;
1772 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1773 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1774 (void)BaseTy;
1775
1776 HandleLValueMember(this->Info, Result, FD);
1777
1778 if (FD->getType()->isReferenceType()) {
1779 CCValue RefValue;
1780 if (!HandleLValueToRValueConversion(this->Info, FD->getType(), Result,
1781 RefValue))
1782 return false;
1783 return Success(RefValue, E);
1784 }
1785 return true;
1786 }
1787
1788 bool VisitBinaryOperator(const BinaryOperator *E) {
1789 switch (E->getOpcode()) {
1790 default:
1791 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
1792
1793 case BO_PtrMemD:
1794 case BO_PtrMemI:
1795 return HandleMemberPointerAccess(this->Info, E, Result);
1796 }
1797 }
1798
1799 bool VisitCastExpr(const CastExpr *E) {
1800 switch (E->getCastKind()) {
1801 default:
1802 return ExprEvaluatorBaseTy::VisitCastExpr(E);
1803
1804 case CK_DerivedToBase:
1805 case CK_UncheckedDerivedToBase: {
1806 if (!this->Visit(E->getSubExpr()))
1807 return false;
1808 if (!CheckValidLValue())
1809 return false;
1810
1811 // Now figure out the necessary offset to add to the base LV to get from
1812 // the derived class to the base class.
1813 QualType Type = E->getSubExpr()->getType();
1814
1815 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1816 PathE = E->path_end(); PathI != PathE; ++PathI) {
1817 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
1818 *PathI))
1819 return false;
1820 Type = (*PathI)->getType();
1821 }
1822
1823 return true;
1824 }
1825 }
1826 }
1827};
1828}
1829
1830//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001831// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001832//
1833// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
1834// function designators (in C), decl references to void objects (in C), and
1835// temporaries (if building with -Wno-address-of-temporary).
1836//
1837// LValue evaluation produces values comprising a base expression of one of the
1838// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00001839// - Declarations
1840// * VarDecl
1841// * FunctionDecl
1842// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00001843// * CompoundLiteralExpr in C
1844// * StringLiteral
1845// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00001846// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00001847// * ObjCEncodeExpr
1848// * AddrLabelExpr
1849// * BlockExpr
1850// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00001851// - Locals and temporaries
1852// * Any Expr, with a Frame indicating the function in which the temporary was
1853// evaluated.
1854// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00001855//===----------------------------------------------------------------------===//
1856namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001857class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00001858 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00001859public:
Richard Smith027bf112011-11-17 22:56:20 +00001860 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
1861 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001862
Richard Smith11562c52011-10-28 17:51:58 +00001863 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
1864
Peter Collingbournee9200682011-05-13 03:29:01 +00001865 bool VisitDeclRefExpr(const DeclRefExpr *E);
1866 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001867 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001868 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1869 bool VisitMemberExpr(const MemberExpr *E);
1870 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
1871 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
1872 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
1873 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001874
Peter Collingbournee9200682011-05-13 03:29:01 +00001875 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00001876 switch (E->getCastKind()) {
1877 default:
Richard Smith027bf112011-11-17 22:56:20 +00001878 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001879
Eli Friedmance3e02a2011-10-11 00:13:24 +00001880 case CK_LValueBitCast:
Richard Smith96e0c102011-11-04 02:25:55 +00001881 if (!Visit(E->getSubExpr()))
1882 return false;
1883 Result.Designator.setInvalid();
1884 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00001885
Richard Smith027bf112011-11-17 22:56:20 +00001886 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00001887 if (!Visit(E->getSubExpr()))
1888 return false;
Richard Smith027bf112011-11-17 22:56:20 +00001889 if (!CheckValidLValue())
1890 return false;
1891 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00001892 }
1893 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00001894
Eli Friedman449fe542009-03-23 04:56:01 +00001895 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00001896
Eli Friedman9a156e52008-11-12 09:44:48 +00001897};
1898} // end anonymous namespace
1899
Richard Smith11562c52011-10-28 17:51:58 +00001900/// Evaluate an expression as an lvalue. This can be legitimately called on
1901/// expressions which are not glvalues, in a few cases:
1902/// * function designators in C,
1903/// * "extern void" objects,
1904/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00001905static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001906 assert((E->isGLValue() || E->getType()->isFunctionType() ||
1907 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
1908 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00001909 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001910}
1911
Peter Collingbournee9200682011-05-13 03:29:01 +00001912bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00001913 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
1914 return Success(FD);
1915 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00001916 return VisitVarDecl(E, VD);
1917 return Error(E);
1918}
Richard Smith733237d2011-10-24 23:14:33 +00001919
Richard Smith11562c52011-10-28 17:51:58 +00001920bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00001921 if (!VD->getType()->isReferenceType()) {
1922 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00001923 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00001924 return true;
1925 }
Richard Smithce40ad62011-11-12 22:28:03 +00001926 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00001927 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00001928
Richard Smith0b0a0b62011-10-29 20:57:55 +00001929 CCValue V;
Richard Smithce40ad62011-11-12 22:28:03 +00001930 if (EvaluateVarDeclInit(Info, VD, Info.CurrentCall, V))
Richard Smith0b0a0b62011-10-29 20:57:55 +00001931 return Success(V, E);
Richard Smith11562c52011-10-28 17:51:58 +00001932
1933 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +00001934}
1935
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001936bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
1937 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00001938 if (E->GetTemporaryExpr()->isRValue()) {
1939 if (E->getType()->isRecordType() && E->getType()->isLiteralType())
1940 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
1941
1942 Result.set(E, Info.CurrentCall);
1943 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
1944 Result, E->GetTemporaryExpr());
1945 }
1946
1947 // Materialization of an lvalue temporary occurs when we need to force a copy
1948 // (for instance, if it's a bitfield).
1949 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
1950 if (!Visit(E->GetTemporaryExpr()))
1951 return false;
1952 if (!HandleLValueToRValueConversion(Info, E->getType(), Result,
1953 Info.CurrentCall->Temporaries[E]))
1954 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00001955 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00001956 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001957}
1958
Peter Collingbournee9200682011-05-13 03:29:01 +00001959bool
1960LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001961 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1962 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
1963 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00001964 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001965}
1966
Peter Collingbournee9200682011-05-13 03:29:01 +00001967bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001968 // Handle static data members.
1969 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
1970 VisitIgnoredValue(E->getBase());
1971 return VisitVarDecl(E, VD);
1972 }
1973
Richard Smith254a73d2011-10-28 22:34:42 +00001974 // Handle static member functions.
1975 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
1976 if (MD->isStatic()) {
1977 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00001978 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00001979 }
1980 }
1981
Richard Smithd62306a2011-11-10 06:34:14 +00001982 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00001983 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001984}
1985
Peter Collingbournee9200682011-05-13 03:29:01 +00001986bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001987 // FIXME: Deal with vectors as array subscript bases.
1988 if (E->getBase()->getType()->isVectorType())
1989 return false;
1990
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001991 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00001992 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001993
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001994 APSInt Index;
1995 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00001996 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001997 int64_t IndexValue
1998 = Index.isSigned() ? Index.getSExtValue()
1999 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002000
Richard Smith027bf112011-11-17 22:56:20 +00002001 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002002 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002003}
Eli Friedman9a156e52008-11-12 09:44:48 +00002004
Peter Collingbournee9200682011-05-13 03:29:01 +00002005bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002006 // FIXME: In C++11, require the result to be a valid lvalue.
John McCall45d55e42010-05-07 21:00:08 +00002007 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002008}
2009
Eli Friedman9a156e52008-11-12 09:44:48 +00002010//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002011// Pointer Evaluation
2012//===----------------------------------------------------------------------===//
2013
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002014namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002015class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002016 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002017 LValue &Result;
2018
Peter Collingbournee9200682011-05-13 03:29:01 +00002019 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002020 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002021 return true;
2022 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002023public:
Mike Stump11289f42009-09-09 15:08:12 +00002024
John McCall45d55e42010-05-07 21:00:08 +00002025 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002026 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002027
Richard Smith0b0a0b62011-10-29 20:57:55 +00002028 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002029 Result.setFrom(V);
2030 return true;
2031 }
2032 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +00002033 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002034 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002035 bool ValueInitialization(const Expr *E) {
2036 return Success((Expr*)0);
2037 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002038
John McCall45d55e42010-05-07 21:00:08 +00002039 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002040 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002041 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002042 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002043 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002044 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002045 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002046 bool VisitCallExpr(const CallExpr *E);
2047 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002048 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002049 return Success(E);
2050 return false;
Mike Stumpa6703322009-02-19 22:01:56 +00002051 }
Richard Smithd62306a2011-11-10 06:34:14 +00002052 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2053 if (!Info.CurrentCall->This)
2054 return false;
2055 Result = *Info.CurrentCall->This;
2056 return true;
2057 }
John McCallc07a0c72011-02-17 10:25:35 +00002058
Eli Friedman449fe542009-03-23 04:56:01 +00002059 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002060};
Chris Lattner05706e882008-07-11 18:11:29 +00002061} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002062
John McCall45d55e42010-05-07 21:00:08 +00002063static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002064 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002065 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002066}
2067
John McCall45d55e42010-05-07 21:00:08 +00002068bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002069 if (E->getOpcode() != BO_Add &&
2070 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002071 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002072
Chris Lattner05706e882008-07-11 18:11:29 +00002073 const Expr *PExp = E->getLHS();
2074 const Expr *IExp = E->getRHS();
2075 if (IExp->getType()->isPointerType())
2076 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002077
John McCall45d55e42010-05-07 21:00:08 +00002078 if (!EvaluatePointer(PExp, Result, Info))
2079 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002080
John McCall45d55e42010-05-07 21:00:08 +00002081 llvm::APSInt Offset;
2082 if (!EvaluateInteger(IExp, Offset, Info))
2083 return false;
2084 int64_t AdditionalOffset
2085 = Offset.isSigned() ? Offset.getSExtValue()
2086 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002087 if (E->getOpcode() == BO_Sub)
2088 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002089
Richard Smithd62306a2011-11-10 06:34:14 +00002090 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith027bf112011-11-17 22:56:20 +00002091 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002092 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002093}
Eli Friedman9a156e52008-11-12 09:44:48 +00002094
John McCall45d55e42010-05-07 21:00:08 +00002095bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2096 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002097}
Mike Stump11289f42009-09-09 15:08:12 +00002098
Peter Collingbournee9200682011-05-13 03:29:01 +00002099bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2100 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002101
Eli Friedman847a2bc2009-12-27 05:43:15 +00002102 switch (E->getCastKind()) {
2103 default:
2104 break;
2105
John McCalle3027922010-08-25 11:45:40 +00002106 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002107 case CK_CPointerToObjCPointerCast:
2108 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002109 case CK_AnyPointerToBlockPointerCast:
Richard Smith96e0c102011-11-04 02:25:55 +00002110 if (!Visit(SubExpr))
2111 return false;
2112 Result.Designator.setInvalid();
2113 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002114
Anders Carlsson18275092010-10-31 20:41:46 +00002115 case CK_DerivedToBase:
2116 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002117 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002118 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002119 if (!Result.Base && Result.Offset.isZero())
2120 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002121
Richard Smithd62306a2011-11-10 06:34:14 +00002122 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002123 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002124 QualType Type =
2125 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002126
Richard Smithd62306a2011-11-10 06:34:14 +00002127 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002128 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithd62306a2011-11-10 06:34:14 +00002129 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002130 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002131 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002132 }
2133
Anders Carlsson18275092010-10-31 20:41:46 +00002134 return true;
2135 }
2136
Richard Smith027bf112011-11-17 22:56:20 +00002137 case CK_BaseToDerived:
2138 if (!Visit(E->getSubExpr()))
2139 return false;
2140 if (!Result.Base && Result.Offset.isZero())
2141 return true;
2142 return HandleBaseToDerivedCast(Info, E, Result);
2143
Richard Smith0b0a0b62011-10-29 20:57:55 +00002144 case CK_NullToPointer:
2145 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002146
John McCalle3027922010-08-25 11:45:40 +00002147 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002148 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002149 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002150 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002151
John McCall45d55e42010-05-07 21:00:08 +00002152 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002153 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2154 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002155 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002156 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002157 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002158 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002159 return true;
2160 } else {
2161 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002162 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002163 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002164 }
2165 }
John McCalle3027922010-08-25 11:45:40 +00002166 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002167 if (SubExpr->isGLValue()) {
2168 if (!EvaluateLValue(SubExpr, Result, Info))
2169 return false;
2170 } else {
2171 Result.set(SubExpr, Info.CurrentCall);
2172 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2173 Info, Result, SubExpr))
2174 return false;
2175 }
Richard Smith96e0c102011-11-04 02:25:55 +00002176 // The result is a pointer to the first element of the array.
2177 Result.Designator.addIndex(0);
2178 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002179
John McCalle3027922010-08-25 11:45:40 +00002180 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002181 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002182 }
2183
Richard Smith11562c52011-10-28 17:51:58 +00002184 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002185}
Chris Lattner05706e882008-07-11 18:11:29 +00002186
Peter Collingbournee9200682011-05-13 03:29:01 +00002187bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002188 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002189 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002190
Peter Collingbournee9200682011-05-13 03:29:01 +00002191 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002192}
Chris Lattner05706e882008-07-11 18:11:29 +00002193
2194//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002195// Member Pointer Evaluation
2196//===----------------------------------------------------------------------===//
2197
2198namespace {
2199class MemberPointerExprEvaluator
2200 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2201 MemberPtr &Result;
2202
2203 bool Success(const ValueDecl *D) {
2204 Result = MemberPtr(D);
2205 return true;
2206 }
2207public:
2208
2209 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2210 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2211
2212 bool Success(const CCValue &V, const Expr *E) {
2213 Result.setFrom(V);
2214 return true;
2215 }
2216 bool Error(const Stmt *S) {
2217 return false;
2218 }
2219 bool ValueInitialization(const Expr *E) {
2220 return Success((const ValueDecl*)0);
2221 }
2222
2223 bool VisitCastExpr(const CastExpr *E);
2224 bool VisitUnaryAddrOf(const UnaryOperator *E);
2225};
2226} // end anonymous namespace
2227
2228static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2229 EvalInfo &Info) {
2230 assert(E->isRValue() && E->getType()->isMemberPointerType());
2231 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2232}
2233
2234bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2235 switch (E->getCastKind()) {
2236 default:
2237 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2238
2239 case CK_NullToMemberPointer:
2240 return ValueInitialization(E);
2241
2242 case CK_BaseToDerivedMemberPointer: {
2243 if (!Visit(E->getSubExpr()))
2244 return false;
2245 if (E->path_empty())
2246 return true;
2247 // Base-to-derived member pointer casts store the path in derived-to-base
2248 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2249 // the wrong end of the derived->base arc, so stagger the path by one class.
2250 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2251 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2252 PathI != PathE; ++PathI) {
2253 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2254 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2255 if (!Result.castToDerived(Derived))
2256 return false;
2257 }
2258 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2259 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
2260 return false;
2261 return true;
2262 }
2263
2264 case CK_DerivedToBaseMemberPointer:
2265 if (!Visit(E->getSubExpr()))
2266 return false;
2267 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2268 PathE = E->path_end(); PathI != PathE; ++PathI) {
2269 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2270 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2271 if (!Result.castToBase(Base))
2272 return false;
2273 }
2274 return true;
2275 }
2276}
2277
2278bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2279 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2280 // member can be formed.
2281 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2282}
2283
2284//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002285// Record Evaluation
2286//===----------------------------------------------------------------------===//
2287
2288namespace {
2289 class RecordExprEvaluator
2290 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2291 const LValue &This;
2292 APValue &Result;
2293 public:
2294
2295 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2296 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2297
2298 bool Success(const CCValue &V, const Expr *E) {
2299 return CheckConstantExpression(V, Result);
2300 }
2301 bool Error(const Expr *E) { return false; }
2302
Richard Smithe97cbd72011-11-11 04:05:33 +00002303 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002304 bool VisitInitListExpr(const InitListExpr *E);
2305 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2306 };
2307}
2308
Richard Smithe97cbd72011-11-11 04:05:33 +00002309bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2310 switch (E->getCastKind()) {
2311 default:
2312 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2313
2314 case CK_ConstructorConversion:
2315 return Visit(E->getSubExpr());
2316
2317 case CK_DerivedToBase:
2318 case CK_UncheckedDerivedToBase: {
2319 CCValue DerivedObject;
2320 if (!Evaluate(DerivedObject, Info, E->getSubExpr()) ||
2321 !DerivedObject.isStruct())
2322 return false;
2323
2324 // Derived-to-base rvalue conversion: just slice off the derived part.
2325 APValue *Value = &DerivedObject;
2326 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2327 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2328 PathE = E->path_end(); PathI != PathE; ++PathI) {
2329 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2330 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2331 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2332 RD = Base;
2333 }
2334 Result = *Value;
2335 return true;
2336 }
2337 }
2338}
2339
Richard Smithd62306a2011-11-10 06:34:14 +00002340bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2341 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2342 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2343
2344 if (RD->isUnion()) {
2345 Result = APValue(E->getInitializedFieldInUnion());
2346 if (!E->getNumInits())
2347 return true;
2348 LValue Subobject = This;
2349 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2350 &Layout);
2351 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2352 Subobject, E->getInit(0));
2353 }
2354
2355 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2356 "initializer list for class with base classes");
2357 Result = APValue(APValue::UninitStruct(), 0,
2358 std::distance(RD->field_begin(), RD->field_end()));
2359 unsigned ElementNo = 0;
2360 for (RecordDecl::field_iterator Field = RD->field_begin(),
2361 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2362 // Anonymous bit-fields are not considered members of the class for
2363 // purposes of aggregate initialization.
2364 if (Field->isUnnamedBitfield())
2365 continue;
2366
2367 LValue Subobject = This;
2368 HandleLValueMember(Info, Subobject, *Field, &Layout);
2369
2370 if (ElementNo < E->getNumInits()) {
2371 if (!EvaluateConstantExpression(
2372 Result.getStructField((*Field)->getFieldIndex()),
2373 Info, Subobject, E->getInit(ElementNo++)))
2374 return false;
2375 } else {
2376 // Perform an implicit value-initialization for members beyond the end of
2377 // the initializer list.
2378 ImplicitValueInitExpr VIE(Field->getType());
2379 if (!EvaluateConstantExpression(
2380 Result.getStructField((*Field)->getFieldIndex()),
2381 Info, Subobject, &VIE))
2382 return false;
2383 }
2384 }
2385
2386 return true;
2387}
2388
2389bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2390 const CXXConstructorDecl *FD = E->getConstructor();
2391 const FunctionDecl *Definition = 0;
2392 FD->getBody(Definition);
2393
2394 if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl())
2395 return false;
2396
2397 // FIXME: Elide the copy/move construction wherever we can.
2398 if (E->isElidable())
2399 if (const MaterializeTemporaryExpr *ME
2400 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2401 return Visit(ME->GetTemporaryExpr());
2402
2403 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithe97cbd72011-11-11 04:05:33 +00002404 return HandleConstructorCall(This, Args, cast<CXXConstructorDecl>(Definition),
2405 Info, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002406}
2407
2408static bool EvaluateRecord(const Expr *E, const LValue &This,
2409 APValue &Result, EvalInfo &Info) {
2410 assert(E->isRValue() && E->getType()->isRecordType() &&
2411 E->getType()->isLiteralType() &&
2412 "can't evaluate expression as a record rvalue");
2413 return RecordExprEvaluator(Info, This, Result).Visit(E);
2414}
2415
2416//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002417// Temporary Evaluation
2418//
2419// Temporaries are represented in the AST as rvalues, but generally behave like
2420// lvalues. The full-object of which the temporary is a subobject is implicitly
2421// materialized so that a reference can bind to it.
2422//===----------------------------------------------------------------------===//
2423namespace {
2424class TemporaryExprEvaluator
2425 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
2426public:
2427 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
2428 LValueExprEvaluatorBaseTy(Info, Result) {}
2429
2430 /// Visit an expression which constructs the value of this temporary.
2431 bool VisitConstructExpr(const Expr *E) {
2432 Result.set(E, Info.CurrentCall);
2433 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2434 Result, E);
2435 }
2436
2437 bool VisitCastExpr(const CastExpr *E) {
2438 switch (E->getCastKind()) {
2439 default:
2440 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2441
2442 case CK_ConstructorConversion:
2443 return VisitConstructExpr(E->getSubExpr());
2444 }
2445 }
2446 bool VisitInitListExpr(const InitListExpr *E) {
2447 return VisitConstructExpr(E);
2448 }
2449 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2450 return VisitConstructExpr(E);
2451 }
2452 bool VisitCallExpr(const CallExpr *E) {
2453 return VisitConstructExpr(E);
2454 }
2455};
2456} // end anonymous namespace
2457
2458/// Evaluate an expression of record type as a temporary.
2459static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
2460 assert(E->isRValue() && E->getType()->isRecordType() &&
2461 E->getType()->isLiteralType());
2462 return TemporaryExprEvaluator(Info, Result).Visit(E);
2463}
2464
2465//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002466// Vector Evaluation
2467//===----------------------------------------------------------------------===//
2468
2469namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002470 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00002471 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
2472 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002473 public:
Mike Stump11289f42009-09-09 15:08:12 +00002474
Richard Smith2d406342011-10-22 21:10:00 +00002475 VectorExprEvaluator(EvalInfo &info, APValue &Result)
2476 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002477
Richard Smith2d406342011-10-22 21:10:00 +00002478 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
2479 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
2480 // FIXME: remove this APValue copy.
2481 Result = APValue(V.data(), V.size());
2482 return true;
2483 }
Richard Smithed5165f2011-11-04 05:33:44 +00002484 bool Success(const CCValue &V, const Expr *E) {
2485 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00002486 Result = V;
2487 return true;
2488 }
2489 bool Error(const Expr *E) { return false; }
2490 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002491
Richard Smith2d406342011-10-22 21:10:00 +00002492 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00002493 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00002494 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00002495 bool VisitInitListExpr(const InitListExpr *E);
2496 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002497 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00002498 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00002499 // shufflevector, ExtVectorElementExpr
2500 // (Note that these require implementing conversions
2501 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002502 };
2503} // end anonymous namespace
2504
2505static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002506 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00002507 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002508}
2509
Richard Smith2d406342011-10-22 21:10:00 +00002510bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2511 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002512 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002513
Richard Smith161f09a2011-12-06 22:44:34 +00002514 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00002515 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002516
Eli Friedmanc757de22011-03-25 00:43:55 +00002517 switch (E->getCastKind()) {
2518 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00002519 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00002520 if (SETy->isIntegerType()) {
2521 APSInt IntResult;
2522 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00002523 return Error(E);
2524 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00002525 } else if (SETy->isRealFloatingType()) {
2526 APFloat F(0.0);
2527 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00002528 return Error(E);
2529 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00002530 } else {
Richard Smith2d406342011-10-22 21:10:00 +00002531 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002532 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002533
2534 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00002535 SmallVector<APValue, 4> Elts(NElts, Val);
2536 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00002537 }
Eli Friedmanc757de22011-03-25 00:43:55 +00002538 default:
Richard Smith11562c52011-10-28 17:51:58 +00002539 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002540 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002541}
2542
Richard Smith2d406342011-10-22 21:10:00 +00002543bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002544VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00002545 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002546 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00002547 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002548
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002549 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002550 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002551
John McCall875679e2010-06-11 17:54:15 +00002552 // If a vector is initialized with a single element, that value
2553 // becomes every element of the vector, not just the first.
2554 // This is the behavior described in the IBM AltiVec documentation.
2555 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00002556
2557 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00002558 // vector (OpenCL 6.1.6).
2559 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00002560 return Visit(E->getInit(0));
2561
John McCall875679e2010-06-11 17:54:15 +00002562 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002563 if (EltTy->isIntegerType()) {
2564 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00002565 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00002566 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00002567 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002568 } else {
2569 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00002570 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00002571 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00002572 InitValue = APValue(f);
2573 }
2574 for (unsigned i = 0; i < NumElements; i++) {
2575 Elements.push_back(InitValue);
2576 }
2577 } else {
2578 for (unsigned i = 0; i < NumElements; i++) {
2579 if (EltTy->isIntegerType()) {
2580 llvm::APSInt sInt(32);
2581 if (i < NumInits) {
2582 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00002583 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00002584 } else {
2585 sInt = Info.Ctx.MakeIntValue(0, EltTy);
2586 }
2587 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00002588 } else {
John McCall875679e2010-06-11 17:54:15 +00002589 llvm::APFloat f(0.0);
2590 if (i < NumInits) {
2591 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00002592 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00002593 } else {
2594 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
2595 }
2596 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00002597 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002598 }
2599 }
Richard Smith2d406342011-10-22 21:10:00 +00002600 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002601}
2602
Richard Smith2d406342011-10-22 21:10:00 +00002603bool
2604VectorExprEvaluator::ValueInitialization(const Expr *E) {
2605 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00002606 QualType EltTy = VT->getElementType();
2607 APValue ZeroElement;
2608 if (EltTy->isIntegerType())
2609 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
2610 else
2611 ZeroElement =
2612 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
2613
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002614 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00002615 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002616}
2617
Richard Smith2d406342011-10-22 21:10:00 +00002618bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00002619 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00002620 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002621}
2622
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002623//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00002624// Array Evaluation
2625//===----------------------------------------------------------------------===//
2626
2627namespace {
2628 class ArrayExprEvaluator
2629 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00002630 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00002631 APValue &Result;
2632 public:
2633
Richard Smithd62306a2011-11-10 06:34:14 +00002634 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
2635 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00002636
2637 bool Success(const APValue &V, const Expr *E) {
2638 assert(V.isArray() && "Expected array type");
2639 Result = V;
2640 return true;
2641 }
2642 bool Error(const Expr *E) { return false; }
2643
Richard Smithd62306a2011-11-10 06:34:14 +00002644 bool ValueInitialization(const Expr *E) {
2645 const ConstantArrayType *CAT =
2646 Info.Ctx.getAsConstantArrayType(E->getType());
2647 if (!CAT)
2648 return false;
2649
2650 Result = APValue(APValue::UninitArray(), 0,
2651 CAT->getSize().getZExtValue());
2652 if (!Result.hasArrayFiller()) return true;
2653
2654 // Value-initialize all elements.
2655 LValue Subobject = This;
2656 Subobject.Designator.addIndex(0);
2657 ImplicitValueInitExpr VIE(CAT->getElementType());
2658 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
2659 Subobject, &VIE);
2660 }
2661
Richard Smithf3e9e432011-11-07 09:22:26 +00002662 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00002663 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002664 };
2665} // end anonymous namespace
2666
Richard Smithd62306a2011-11-10 06:34:14 +00002667static bool EvaluateArray(const Expr *E, const LValue &This,
2668 APValue &Result, EvalInfo &Info) {
Richard Smithf3e9e432011-11-07 09:22:26 +00002669 assert(E->isRValue() && E->getType()->isArrayType() &&
2670 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00002671 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002672}
2673
2674bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2675 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2676 if (!CAT)
2677 return false;
2678
2679 Result = APValue(APValue::UninitArray(), E->getNumInits(),
2680 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00002681 LValue Subobject = This;
2682 Subobject.Designator.addIndex(0);
2683 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00002684 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00002685 I != End; ++I, ++Index) {
2686 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
2687 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00002688 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002689 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
2690 return false;
2691 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002692
2693 if (!Result.hasArrayFiller()) return true;
2694 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00002695 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
2696 // but sometimes does:
2697 // struct S { constexpr S() : p(&p) {} void *p; };
2698 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00002699 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00002700 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00002701}
2702
Richard Smith027bf112011-11-17 22:56:20 +00002703bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2704 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2705 if (!CAT)
2706 return false;
2707
2708 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
2709 if (!Result.hasArrayFiller())
2710 return true;
2711
2712 const CXXConstructorDecl *FD = E->getConstructor();
2713 const FunctionDecl *Definition = 0;
2714 FD->getBody(Definition);
2715
2716 if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl())
2717 return false;
2718
2719 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
2720 // but sometimes does:
2721 // struct S { constexpr S() : p(&p) {} void *p; };
2722 // S s[10];
2723 LValue Subobject = This;
2724 Subobject.Designator.addIndex(0);
2725 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
2726 return HandleConstructorCall(Subobject, Args,
2727 cast<CXXConstructorDecl>(Definition),
2728 Info, Result.getArrayFiller());
2729}
2730
Richard Smithf3e9e432011-11-07 09:22:26 +00002731//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002732// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002733//
2734// As a GNU extension, we support casting pointers to sufficiently-wide integer
2735// types and back in constant folding. Integer values are thus represented
2736// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00002737//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002738
2739namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002740class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002741 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002742 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002743public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00002744 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002745 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002746
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002747 bool Success(const llvm::APSInt &SI, const Expr *E) {
2748 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002749 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002750 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002751 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002752 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002753 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00002754 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002755 return true;
2756 }
2757
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002758 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00002759 assert(E->getType()->isIntegralOrEnumerationType() &&
2760 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002761 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002762 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00002763 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002764 Result.getInt().setIsUnsigned(
2765 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002766 return true;
2767 }
2768
2769 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00002770 assert(E->getType()->isIntegralOrEnumerationType() &&
2771 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00002772 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002773 return true;
2774 }
2775
Ken Dyckdbc01912011-03-11 02:13:43 +00002776 bool Success(CharUnits Size, const Expr *E) {
2777 return Success(Size.getQuantity(), E);
2778 }
2779
2780
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002781 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002782 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00002783 if (Info.EvalStatus.Diag == 0) {
2784 Info.EvalStatus.DiagLoc = L;
2785 Info.EvalStatus.Diag = D;
2786 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002787 }
Chris Lattner99415702008-07-12 00:14:42 +00002788 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00002789 }
Mike Stump11289f42009-09-09 15:08:12 +00002790
Richard Smith0b0a0b62011-10-29 20:57:55 +00002791 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00002792 if (V.isLValue()) {
2793 Result = V;
2794 return true;
2795 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002796 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002797 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002798 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002799 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002800 }
Mike Stump11289f42009-09-09 15:08:12 +00002801
Richard Smith4ce706a2011-10-11 21:43:33 +00002802 bool ValueInitialization(const Expr *E) { return Success(0, E); }
2803
Peter Collingbournee9200682011-05-13 03:29:01 +00002804 //===--------------------------------------------------------------------===//
2805 // Visitor Methods
2806 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002807
Chris Lattner7174bf32008-07-12 00:38:25 +00002808 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002809 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00002810 }
2811 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002812 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00002813 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002814
2815 bool CheckReferencedDecl(const Expr *E, const Decl *D);
2816 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002817 if (CheckReferencedDecl(E, E->getDecl()))
2818 return true;
2819
2820 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002821 }
2822 bool VisitMemberExpr(const MemberExpr *E) {
2823 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00002824 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002825 return true;
2826 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002827
2828 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002829 }
2830
Peter Collingbournee9200682011-05-13 03:29:01 +00002831 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00002832 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00002833 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00002834 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00002835
Peter Collingbournee9200682011-05-13 03:29:01 +00002836 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002837 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00002838
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002839 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002840 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002841 }
Mike Stump11289f42009-09-09 15:08:12 +00002842
Richard Smith4ce706a2011-10-11 21:43:33 +00002843 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00002844 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002845 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00002846 }
2847
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002848 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002849 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002850 }
2851
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002852 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
2853 return Success(E->getValue(), E);
2854 }
2855
John Wiegley6242b6a2011-04-28 00:16:57 +00002856 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2857 return Success(E->getValue(), E);
2858 }
2859
John Wiegleyf9f65842011-04-25 06:54:41 +00002860 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2861 return Success(E->getValue(), E);
2862 }
2863
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002864 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00002865 bool VisitUnaryImag(const UnaryOperator *E);
2866
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002867 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002868 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002869
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002870private:
Ken Dyck160146e2010-01-27 17:10:57 +00002871 CharUnits GetAlignOfExpr(const Expr *E);
2872 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00002873 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00002874 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00002875 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00002876};
Chris Lattner05706e882008-07-11 18:11:29 +00002877} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002878
Richard Smith11562c52011-10-28 17:51:58 +00002879/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
2880/// produce either the integer value or a pointer.
2881///
2882/// GCC has a heinous extension which folds casts between pointer types and
2883/// pointer-sized integral types. We support this by allowing the evaluation of
2884/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
2885/// Some simple arithmetic on such values is supported (they are treated much
2886/// like char*).
Richard Smith0b0a0b62011-10-29 20:57:55 +00002887static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
2888 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002889 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002890 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00002891}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002892
Daniel Dunbarce399542009-02-20 18:22:23 +00002893static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002894 CCValue Val;
Daniel Dunbarce399542009-02-20 18:22:23 +00002895 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
2896 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002897 Result = Val.getInt();
2898 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002899}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002900
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002901bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002902 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00002903 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002904 // Check for signedness/width mismatches between E type and ECD value.
2905 bool SameSign = (ECD->getInitVal().isSigned()
2906 == E->getType()->isSignedIntegerOrEnumerationType());
2907 bool SameWidth = (ECD->getInitVal().getBitWidth()
2908 == Info.Ctx.getIntWidth(E->getType()));
2909 if (SameSign && SameWidth)
2910 return Success(ECD->getInitVal(), E);
2911 else {
2912 // Get rid of mismatch (otherwise Success assertions will fail)
2913 // by computing a new value matching the type of E.
2914 llvm::APSInt Val = ECD->getInitVal();
2915 if (!SameSign)
2916 Val.setIsSigned(!ECD->getInitVal().isSigned());
2917 if (!SameWidth)
2918 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
2919 return Success(Val, E);
2920 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00002921 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002922 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00002923}
2924
Chris Lattner86ee2862008-10-06 06:40:35 +00002925/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
2926/// as GCC.
2927static int EvaluateBuiltinClassifyType(const CallExpr *E) {
2928 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002929 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00002930 enum gcc_type_class {
2931 no_type_class = -1,
2932 void_type_class, integer_type_class, char_type_class,
2933 enumeral_type_class, boolean_type_class,
2934 pointer_type_class, reference_type_class, offset_type_class,
2935 real_type_class, complex_type_class,
2936 function_type_class, method_type_class,
2937 record_type_class, union_type_class,
2938 array_type_class, string_type_class,
2939 lang_type_class
2940 };
Mike Stump11289f42009-09-09 15:08:12 +00002941
2942 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00002943 // ideal, however it is what gcc does.
2944 if (E->getNumArgs() == 0)
2945 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00002946
Chris Lattner86ee2862008-10-06 06:40:35 +00002947 QualType ArgTy = E->getArg(0)->getType();
2948 if (ArgTy->isVoidType())
2949 return void_type_class;
2950 else if (ArgTy->isEnumeralType())
2951 return enumeral_type_class;
2952 else if (ArgTy->isBooleanType())
2953 return boolean_type_class;
2954 else if (ArgTy->isCharType())
2955 return string_type_class; // gcc doesn't appear to use char_type_class
2956 else if (ArgTy->isIntegerType())
2957 return integer_type_class;
2958 else if (ArgTy->isPointerType())
2959 return pointer_type_class;
2960 else if (ArgTy->isReferenceType())
2961 return reference_type_class;
2962 else if (ArgTy->isRealType())
2963 return real_type_class;
2964 else if (ArgTy->isComplexType())
2965 return complex_type_class;
2966 else if (ArgTy->isFunctionType())
2967 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00002968 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00002969 return record_type_class;
2970 else if (ArgTy->isUnionType())
2971 return union_type_class;
2972 else if (ArgTy->isArrayType())
2973 return array_type_class;
2974 else if (ArgTy->isUnionType())
2975 return union_type_class;
2976 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00002977 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00002978 return -1;
2979}
2980
John McCall95007602010-05-10 23:27:23 +00002981/// Retrieves the "underlying object type" of the given expression,
2982/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00002983QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
2984 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2985 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00002986 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00002987 } else if (const Expr *E = B.get<const Expr*>()) {
2988 if (isa<CompoundLiteralExpr>(E))
2989 return E->getType();
John McCall95007602010-05-10 23:27:23 +00002990 }
2991
2992 return QualType();
2993}
2994
Peter Collingbournee9200682011-05-13 03:29:01 +00002995bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00002996 // TODO: Perhaps we should let LLVM lower this?
2997 LValue Base;
2998 if (!EvaluatePointer(E->getArg(0), Base, Info))
2999 return false;
3000
3001 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003002 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003003
Richard Smithce40ad62011-11-12 22:28:03 +00003004 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003005 if (T.isNull() ||
3006 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003007 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003008 T->isVariablyModifiedType() ||
3009 T->isDependentType())
3010 return false;
3011
3012 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3013 CharUnits Offset = Base.getLValueOffset();
3014
3015 if (!Offset.isNegative() && Offset <= Size)
3016 Size -= Offset;
3017 else
3018 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003019 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003020}
3021
Peter Collingbournee9200682011-05-13 03:29:01 +00003022bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003023 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003024 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003025 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003026
3027 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003028 if (TryEvaluateBuiltinObjectSize(E))
3029 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003030
Eric Christopher99469702010-01-19 22:58:35 +00003031 // If evaluating the argument has side-effects we can't determine
3032 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003033 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003034 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003035 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003036 return Success(0, E);
3037 }
Mike Stump876387b2009-10-27 22:09:17 +00003038
Mike Stump722cedf2009-10-26 18:35:08 +00003039 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
3040 }
3041
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003042 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003043 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003044
Richard Smith10c7c902011-12-09 02:04:48 +00003045 case Builtin::BI__builtin_constant_p: {
3046 const Expr *Arg = E->getArg(0);
3047 QualType ArgType = Arg->getType();
3048 // __builtin_constant_p always has one operand. The rules which gcc follows
3049 // are not precisely documented, but are as follows:
3050 //
3051 // - If the operand is of integral, floating, complex or enumeration type,
3052 // and can be folded to a known value of that type, it returns 1.
3053 // - If the operand and can be folded to a pointer to the first character
3054 // of a string literal (or such a pointer cast to an integral type), it
3055 // returns 1.
3056 //
3057 // Otherwise, it returns 0.
3058 //
3059 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3060 // its support for this does not currently work.
3061 int IsConstant = 0;
3062 if (ArgType->isIntegralOrEnumerationType()) {
3063 // Note, a pointer cast to an integral type is only a constant if it is
3064 // a pointer to the first character of a string literal.
3065 Expr::EvalResult Result;
3066 if (Arg->EvaluateAsRValue(Result, Info.Ctx) && !Result.HasSideEffects) {
3067 APValue &V = Result.Val;
3068 if (V.getKind() == APValue::LValue) {
3069 if (const Expr *E = V.getLValueBase().dyn_cast<const Expr*>())
3070 IsConstant = isa<StringLiteral>(E) && V.getLValueOffset().isZero();
3071 } else {
3072 IsConstant = 1;
3073 }
3074 }
3075 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3076 IsConstant = Arg->isEvaluatable(Info.Ctx);
3077 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3078 LValue LV;
3079 // Use a separate EvalInfo: ignore constexpr parameter and 'this' bindings
3080 // during the check.
3081 Expr::EvalStatus Status;
3082 EvalInfo SubInfo(Info.Ctx, Status);
3083 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, SubInfo)
3084 : EvaluatePointer(Arg, LV, SubInfo)) &&
3085 !Status.HasSideEffects)
3086 if (const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>())
3087 IsConstant = isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3088 }
3089
3090 return Success(IsConstant, E);
3091 }
Chris Lattnerd545ad12009-09-23 06:06:36 +00003092 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003093 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003094 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003095 return Success(Operand, E);
3096 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003097
3098 case Builtin::BI__builtin_expect:
3099 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003100
3101 case Builtin::BIstrlen:
3102 case Builtin::BI__builtin_strlen:
3103 // As an extension, we support strlen() and __builtin_strlen() as constant
3104 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003105 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003106 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3107 // The string literal may have embedded null characters. Find the first
3108 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003109 StringRef Str = S->getString();
3110 StringRef::size_type Pos = Str.find(0);
3111 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003112 Str = Str.substr(0, Pos);
3113
3114 return Success(Str.size(), E);
3115 }
3116
3117 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003118
3119 case Builtin::BI__atomic_is_lock_free: {
3120 APSInt SizeVal;
3121 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3122 return false;
3123
3124 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3125 // of two less than the maximum inline atomic width, we know it is
3126 // lock-free. If the size isn't a power of two, or greater than the
3127 // maximum alignment where we promote atomics, we know it is not lock-free
3128 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3129 // the answer can only be determined at runtime; for example, 16-byte
3130 // atomics have lock-free implementations on some, but not all,
3131 // x86-64 processors.
3132
3133 // Check power-of-two.
3134 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3135 if (!Size.isPowerOfTwo())
3136#if 0
3137 // FIXME: Suppress this folding until the ABI for the promotion width
3138 // settles.
3139 return Success(0, E);
3140#else
3141 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
3142#endif
3143
3144#if 0
3145 // Check against promotion width.
3146 // FIXME: Suppress this folding until the ABI for the promotion width
3147 // settles.
3148 unsigned PromoteWidthBits =
3149 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3150 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3151 return Success(0, E);
3152#endif
3153
3154 // Check against inlining width.
3155 unsigned InlineWidthBits =
3156 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3157 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3158 return Success(1, E);
3159
3160 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
3161 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003162 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003163}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003164
Richard Smith8b3497e2011-10-31 01:37:14 +00003165static bool HasSameBase(const LValue &A, const LValue &B) {
3166 if (!A.getLValueBase())
3167 return !B.getLValueBase();
3168 if (!B.getLValueBase())
3169 return false;
3170
Richard Smithce40ad62011-11-12 22:28:03 +00003171 if (A.getLValueBase().getOpaqueValue() !=
3172 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003173 const Decl *ADecl = GetLValueBaseDecl(A);
3174 if (!ADecl)
3175 return false;
3176 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003177 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003178 return false;
3179 }
3180
3181 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003182 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003183}
3184
Chris Lattnere13042c2008-07-11 19:10:17 +00003185bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003186 if (E->isAssignmentOp())
3187 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
3188
John McCalle3027922010-08-25 11:45:40 +00003189 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003190 VisitIgnoredValue(E->getLHS());
3191 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003192 }
3193
3194 if (E->isLogicalOp()) {
3195 // These need to be handled specially because the operands aren't
3196 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003197 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003198
Richard Smith11562c52011-10-28 17:51:58 +00003199 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003200 // We were able to evaluate the LHS, see if we can get away with not
3201 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003202 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003203 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003204
Richard Smith11562c52011-10-28 17:51:58 +00003205 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003206 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003207 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003208 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003209 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003210 }
3211 } else {
Richard Smith11562c52011-10-28 17:51:58 +00003212 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003213 // We can't evaluate the LHS; however, sometimes the result
3214 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00003215 if (rhsResult == (E->getOpcode() == BO_LOr) ||
3216 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003217 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003218 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00003219 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003220
3221 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003222 }
3223 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00003224 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00003225
Eli Friedman5a332ea2008-11-13 06:09:17 +00003226 return false;
3227 }
3228
Anders Carlssonacc79812008-11-16 07:17:21 +00003229 QualType LHSTy = E->getLHS()->getType();
3230 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003231
3232 if (LHSTy->isAnyComplexType()) {
3233 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00003234 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003235
3236 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3237 return false;
3238
3239 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3240 return false;
3241
3242 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00003243 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003244 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00003245 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003246 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3247
John McCalle3027922010-08-25 11:45:40 +00003248 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003249 return Success((CR_r == APFloat::cmpEqual &&
3250 CR_i == APFloat::cmpEqual), E);
3251 else {
John McCalle3027922010-08-25 11:45:40 +00003252 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003253 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00003254 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003255 CR_r == APFloat::cmpLessThan ||
3256 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00003257 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003258 CR_i == APFloat::cmpLessThan ||
3259 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003260 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003261 } else {
John McCalle3027922010-08-25 11:45:40 +00003262 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003263 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3264 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3265 else {
John McCalle3027922010-08-25 11:45:40 +00003266 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003267 "Invalid compex comparison.");
3268 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3269 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3270 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003271 }
3272 }
Mike Stump11289f42009-09-09 15:08:12 +00003273
Anders Carlssonacc79812008-11-16 07:17:21 +00003274 if (LHSTy->isRealFloatingType() &&
3275 RHSTy->isRealFloatingType()) {
3276 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00003277
Anders Carlssonacc79812008-11-16 07:17:21 +00003278 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3279 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003280
Anders Carlssonacc79812008-11-16 07:17:21 +00003281 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3282 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003283
Anders Carlssonacc79812008-11-16 07:17:21 +00003284 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00003285
Anders Carlssonacc79812008-11-16 07:17:21 +00003286 switch (E->getOpcode()) {
3287 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003288 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00003289 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003290 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00003291 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003292 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00003293 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003294 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003295 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00003296 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003297 E);
John McCalle3027922010-08-25 11:45:40 +00003298 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003299 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003300 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00003301 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00003302 || CR == APFloat::cmpLessThan
3303 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00003304 }
Anders Carlssonacc79812008-11-16 07:17:21 +00003305 }
Mike Stump11289f42009-09-09 15:08:12 +00003306
Eli Friedmana38da572009-04-28 19:17:36 +00003307 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003308 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00003309 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003310 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3311 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003312
John McCall45d55e42010-05-07 21:00:08 +00003313 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003314 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3315 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003316
Richard Smith8b3497e2011-10-31 01:37:14 +00003317 // Reject differing bases from the normal codepath; we special-case
3318 // comparisons to null.
3319 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00003320 // Inequalities and subtractions between unrelated pointers have
3321 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00003322 if (!E->isEqualityOp())
3323 return false;
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003324 // A constant address may compare equal to the address of a symbol.
3325 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00003326 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003327 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3328 (!RHSValue.Base && !RHSValue.Offset.isZero()))
3329 return false;
Richard Smith83c68212011-10-31 05:11:32 +00003330 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00003331 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00003332 // distinct. However, we do know that the address of a literal will be
3333 // non-null.
3334 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
3335 LHSValue.Base && RHSValue.Base)
Eli Friedman334046a2009-06-14 02:17:33 +00003336 return false;
Richard Smith83c68212011-10-31 05:11:32 +00003337 // We can't tell whether weak symbols will end up pointing to the same
3338 // object.
3339 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Eli Friedman334046a2009-06-14 02:17:33 +00003340 return false;
Richard Smith83c68212011-10-31 05:11:32 +00003341 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00003342 // (Note that clang defaults to -fmerge-all-constants, which can
3343 // lead to inconsistent results for comparisons involving the address
3344 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00003345 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00003346 }
Eli Friedman64004332009-03-23 04:38:34 +00003347
Richard Smithf3e9e432011-11-07 09:22:26 +00003348 // FIXME: Implement the C++11 restrictions:
3349 // - Pointer subtractions must be on elements of the same array.
3350 // - Pointer comparisons must be between members with the same access.
3351
John McCalle3027922010-08-25 11:45:40 +00003352 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00003353 QualType Type = E->getLHS()->getType();
3354 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003355
Richard Smithd62306a2011-11-10 06:34:14 +00003356 CharUnits ElementSize;
3357 if (!HandleSizeof(Info, ElementType, ElementSize))
3358 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003359
Richard Smithd62306a2011-11-10 06:34:14 +00003360 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00003361 RHSValue.getLValueOffset();
3362 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003363 }
Richard Smith8b3497e2011-10-31 01:37:14 +00003364
3365 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
3366 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
3367 switch (E->getOpcode()) {
3368 default: llvm_unreachable("missing comparison operator");
3369 case BO_LT: return Success(LHSOffset < RHSOffset, E);
3370 case BO_GT: return Success(LHSOffset > RHSOffset, E);
3371 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
3372 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
3373 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
3374 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003375 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003376 }
3377 }
Douglas Gregorb90df602010-06-16 00:17:44 +00003378 if (!LHSTy->isIntegralOrEnumerationType() ||
3379 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00003380 // We can't continue from here for non-integral types.
3381 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003382 }
3383
Anders Carlsson9c181652008-07-08 14:35:21 +00003384 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00003385 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00003386 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00003387 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00003388
Richard Smith11562c52011-10-28 17:51:58 +00003389 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003390 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003391 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00003392
3393 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00003394 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00003395 CharUnits AdditionalOffset = CharUnits::fromQuantity(
3396 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00003397 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00003398 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00003399 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00003400 LHSVal.getLValueOffset() -= AdditionalOffset;
3401 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00003402 return true;
3403 }
3404
3405 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00003406 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00003407 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003408 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
3409 LHSVal.getInt().getZExtValue());
3410 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00003411 return true;
3412 }
3413
3414 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00003415 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00003416 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00003417
Richard Smith11562c52011-10-28 17:51:58 +00003418 APSInt &LHS = LHSVal.getInt();
3419 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00003420
Anders Carlsson9c181652008-07-08 14:35:21 +00003421 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003422 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00003423 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00003424 case BO_Mul: return Success(LHS * RHS, E);
3425 case BO_Add: return Success(LHS + RHS, E);
3426 case BO_Sub: return Success(LHS - RHS, E);
3427 case BO_And: return Success(LHS & RHS, E);
3428 case BO_Xor: return Success(LHS ^ RHS, E);
3429 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003430 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00003431 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00003432 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00003433 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003434 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00003435 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00003436 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00003437 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003438 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00003439 // During constant-folding, a negative shift is an opposite shift.
3440 if (RHS.isSigned() && RHS.isNegative()) {
3441 RHS = -RHS;
3442 goto shift_right;
3443 }
3444
3445 shift_left:
3446 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00003447 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3448 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003449 }
John McCalle3027922010-08-25 11:45:40 +00003450 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00003451 // During constant-folding, a negative shift is an opposite shift.
3452 if (RHS.isSigned() && RHS.isNegative()) {
3453 RHS = -RHS;
3454 goto shift_left;
3455 }
3456
3457 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00003458 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00003459 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3460 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003461 }
Mike Stump11289f42009-09-09 15:08:12 +00003462
Richard Smith11562c52011-10-28 17:51:58 +00003463 case BO_LT: return Success(LHS < RHS, E);
3464 case BO_GT: return Success(LHS > RHS, E);
3465 case BO_LE: return Success(LHS <= RHS, E);
3466 case BO_GE: return Success(LHS >= RHS, E);
3467 case BO_EQ: return Success(LHS == RHS, E);
3468 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00003469 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003470}
3471
Ken Dyck160146e2010-01-27 17:10:57 +00003472CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003473 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3474 // the result is the size of the referenced type."
3475 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3476 // result shall be the alignment of the referenced type."
3477 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3478 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00003479
3480 // __alignof is defined to return the preferred alignment.
3481 return Info.Ctx.toCharUnitsFromBits(
3482 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00003483}
3484
Ken Dyck160146e2010-01-27 17:10:57 +00003485CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00003486 E = E->IgnoreParens();
3487
3488 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00003489 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00003490 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003491 return Info.Ctx.getDeclAlign(DRE->getDecl(),
3492 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00003493
Chris Lattner68061312009-01-24 21:53:27 +00003494 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003495 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
3496 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00003497
Chris Lattner24aeeab2009-01-24 21:09:06 +00003498 return GetAlignOfType(E->getType());
3499}
3500
3501
Peter Collingbournee190dee2011-03-11 19:24:49 +00003502/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
3503/// a result as the expression's type.
3504bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
3505 const UnaryExprOrTypeTraitExpr *E) {
3506 switch(E->getKind()) {
3507 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00003508 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00003509 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003510 else
Ken Dyckdbc01912011-03-11 02:13:43 +00003511 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003512 }
Eli Friedman64004332009-03-23 04:38:34 +00003513
Peter Collingbournee190dee2011-03-11 19:24:49 +00003514 case UETT_VecStep: {
3515 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00003516
Peter Collingbournee190dee2011-03-11 19:24:49 +00003517 if (Ty->isVectorType()) {
3518 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00003519
Peter Collingbournee190dee2011-03-11 19:24:49 +00003520 // The vec_step built-in functions that take a 3-component
3521 // vector return 4. (OpenCL 1.1 spec 6.11.12)
3522 if (n == 3)
3523 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00003524
Peter Collingbournee190dee2011-03-11 19:24:49 +00003525 return Success(n, E);
3526 } else
3527 return Success(1, E);
3528 }
3529
3530 case UETT_SizeOf: {
3531 QualType SrcTy = E->getTypeOfArgument();
3532 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3533 // the result is the size of the referenced type."
3534 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3535 // result shall be the alignment of the referenced type."
3536 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
3537 SrcTy = Ref->getPointeeType();
3538
Richard Smithd62306a2011-11-10 06:34:14 +00003539 CharUnits Sizeof;
3540 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00003541 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003542 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003543 }
3544 }
3545
3546 llvm_unreachable("unknown expr/type trait");
3547 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003548}
3549
Peter Collingbournee9200682011-05-13 03:29:01 +00003550bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00003551 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00003552 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00003553 if (n == 0)
3554 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00003555 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00003556 for (unsigned i = 0; i != n; ++i) {
3557 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
3558 switch (ON.getKind()) {
3559 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00003560 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00003561 APSInt IdxResult;
3562 if (!EvaluateInteger(Idx, IdxResult, Info))
3563 return false;
3564 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
3565 if (!AT)
3566 return false;
3567 CurrentType = AT->getElementType();
3568 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
3569 Result += IdxResult.getSExtValue() * ElementSize;
3570 break;
3571 }
3572
3573 case OffsetOfExpr::OffsetOfNode::Field: {
3574 FieldDecl *MemberDecl = ON.getField();
3575 const RecordType *RT = CurrentType->getAs<RecordType>();
3576 if (!RT)
3577 return false;
3578 RecordDecl *RD = RT->getDecl();
3579 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00003580 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00003581 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00003582 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00003583 CurrentType = MemberDecl->getType().getNonReferenceType();
3584 break;
3585 }
3586
3587 case OffsetOfExpr::OffsetOfNode::Identifier:
3588 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00003589 return false;
3590
3591 case OffsetOfExpr::OffsetOfNode::Base: {
3592 CXXBaseSpecifier *BaseSpec = ON.getBase();
3593 if (BaseSpec->isVirtual())
3594 return false;
3595
3596 // Find the layout of the class whose base we are looking into.
3597 const RecordType *RT = CurrentType->getAs<RecordType>();
3598 if (!RT)
3599 return false;
3600 RecordDecl *RD = RT->getDecl();
3601 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
3602
3603 // Find the base class itself.
3604 CurrentType = BaseSpec->getType();
3605 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
3606 if (!BaseRT)
3607 return false;
3608
3609 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00003610 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00003611 break;
3612 }
Douglas Gregor882211c2010-04-28 22:16:22 +00003613 }
3614 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003615 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003616}
3617
Chris Lattnere13042c2008-07-11 19:10:17 +00003618bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003619 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00003620 // LNot's operand isn't necessarily an integer, so we handle it specially.
3621 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00003622 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00003623 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003624 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003625 }
3626
Daniel Dunbar79e042a2009-02-21 18:14:20 +00003627 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00003628 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00003629 return false;
3630
Richard Smith11562c52011-10-28 17:51:58 +00003631 // Get the operand value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00003632 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00003633 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00003634 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00003635
Chris Lattnerf09ad162008-07-11 22:15:16 +00003636 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003637 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00003638 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
3639 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00003640 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00003641 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00003642 // FIXME: Should extension allow i-c-e extension expressions in its scope?
3643 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00003644 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00003645 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00003646 // The result is just the value.
3647 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00003648 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00003649 if (!Val.isInt()) return false;
3650 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00003651 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00003652 if (!Val.isInt()) return false;
3653 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00003654 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003655}
Mike Stump11289f42009-09-09 15:08:12 +00003656
Chris Lattner477c4be2008-07-12 01:15:53 +00003657/// HandleCast - This is used to evaluate implicit or explicit casts where the
3658/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00003659bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
3660 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00003661 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00003662 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00003663
Eli Friedmanc757de22011-03-25 00:43:55 +00003664 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00003665 case CK_BaseToDerived:
3666 case CK_DerivedToBase:
3667 case CK_UncheckedDerivedToBase:
3668 case CK_Dynamic:
3669 case CK_ToUnion:
3670 case CK_ArrayToPointerDecay:
3671 case CK_FunctionToPointerDecay:
3672 case CK_NullToPointer:
3673 case CK_NullToMemberPointer:
3674 case CK_BaseToDerivedMemberPointer:
3675 case CK_DerivedToBaseMemberPointer:
3676 case CK_ConstructorConversion:
3677 case CK_IntegralToPointer:
3678 case CK_ToVoid:
3679 case CK_VectorSplat:
3680 case CK_IntegralToFloating:
3681 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00003682 case CK_CPointerToObjCPointerCast:
3683 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00003684 case CK_AnyPointerToBlockPointerCast:
3685 case CK_ObjCObjectLValueCast:
3686 case CK_FloatingRealToComplex:
3687 case CK_FloatingComplexToReal:
3688 case CK_FloatingComplexCast:
3689 case CK_FloatingComplexToIntegralComplex:
3690 case CK_IntegralRealToComplex:
3691 case CK_IntegralComplexCast:
3692 case CK_IntegralComplexToFloatingComplex:
3693 llvm_unreachable("invalid cast kind for integral value");
3694
Eli Friedman9faf2f92011-03-25 19:07:11 +00003695 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00003696 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00003697 case CK_LValueBitCast:
3698 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00003699 case CK_ARCProduceObject:
3700 case CK_ARCConsumeObject:
3701 case CK_ARCReclaimReturnedObject:
3702 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00003703 return false;
3704
3705 case CK_LValueToRValue:
3706 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00003707 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003708
3709 case CK_MemberPointerToBoolean:
3710 case CK_PointerToBoolean:
3711 case CK_IntegralToBoolean:
3712 case CK_FloatingToBoolean:
3713 case CK_FloatingComplexToBoolean:
3714 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00003715 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00003716 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00003717 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003718 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003719 }
3720
Eli Friedmanc757de22011-03-25 00:43:55 +00003721 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00003722 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00003723 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00003724
Eli Friedman742421e2009-02-20 01:15:07 +00003725 if (!Result.isInt()) {
3726 // Only allow casts of lvalues if they are lossless.
3727 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
3728 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003729
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003730 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003731 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00003732 }
Mike Stump11289f42009-09-09 15:08:12 +00003733
Eli Friedmanc757de22011-03-25 00:43:55 +00003734 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00003735 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00003736 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00003737 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00003738
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003739 if (LV.getLValueBase()) {
3740 // Only allow based lvalue casts if they are lossless.
3741 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
3742 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00003743
Richard Smithcf74da72011-11-16 07:18:12 +00003744 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00003745 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003746 return true;
3747 }
3748
Ken Dyck02990832010-01-15 12:37:54 +00003749 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
3750 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003751 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003752 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003753
Eli Friedmanc757de22011-03-25 00:43:55 +00003754 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00003755 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00003756 if (!EvaluateComplex(SubExpr, C, Info))
3757 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00003758 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00003759 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00003760
Eli Friedmanc757de22011-03-25 00:43:55 +00003761 case CK_FloatingToIntegral: {
3762 APFloat F(0.0);
3763 if (!EvaluateFloat(SubExpr, F, Info))
3764 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00003765
Eli Friedmanc757de22011-03-25 00:43:55 +00003766 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
3767 }
3768 }
Mike Stump11289f42009-09-09 15:08:12 +00003769
Eli Friedmanc757de22011-03-25 00:43:55 +00003770 llvm_unreachable("unknown cast resulting in integral value");
3771 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00003772}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003773
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003774bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3775 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00003776 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003777 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
3778 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
3779 return Success(LV.getComplexIntReal(), E);
3780 }
3781
3782 return Visit(E->getSubExpr());
3783}
3784
Eli Friedman4e7a2412009-02-27 04:45:43 +00003785bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003786 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00003787 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003788 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
3789 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
3790 return Success(LV.getComplexIntImag(), E);
3791 }
3792
Richard Smith4a678122011-10-24 18:44:57 +00003793 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00003794 return Success(0, E);
3795}
3796
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003797bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
3798 return Success(E->getPackLength(), E);
3799}
3800
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003801bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
3802 return Success(E->getValue(), E);
3803}
3804
Chris Lattner05706e882008-07-11 18:11:29 +00003805//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00003806// Float Evaluation
3807//===----------------------------------------------------------------------===//
3808
3809namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003810class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003811 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00003812 APFloat &Result;
3813public:
3814 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003815 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00003816
Richard Smith0b0a0b62011-10-29 20:57:55 +00003817 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003818 Result = V.getFloat();
3819 return true;
3820 }
3821 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00003822 return false;
3823 }
3824
Richard Smith4ce706a2011-10-11 21:43:33 +00003825 bool ValueInitialization(const Expr *E) {
3826 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
3827 return true;
3828 }
3829
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003830 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00003831
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003832 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00003833 bool VisitBinaryOperator(const BinaryOperator *E);
3834 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003835 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00003836
John McCallb1fb0d32010-05-07 22:08:54 +00003837 bool VisitUnaryReal(const UnaryOperator *E);
3838 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00003839
John McCallb1fb0d32010-05-07 22:08:54 +00003840 // FIXME: Missing: array subscript of vector, member of vector,
3841 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00003842};
3843} // end anonymous namespace
3844
3845static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003846 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003847 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00003848}
3849
Jay Foad39c79802011-01-12 09:06:06 +00003850static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00003851 QualType ResultTy,
3852 const Expr *Arg,
3853 bool SNaN,
3854 llvm::APFloat &Result) {
3855 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
3856 if (!S) return false;
3857
3858 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
3859
3860 llvm::APInt fill;
3861
3862 // Treat empty strings as if they were zero.
3863 if (S->getString().empty())
3864 fill = llvm::APInt(32, 0);
3865 else if (S->getString().getAsInteger(0, fill))
3866 return false;
3867
3868 if (SNaN)
3869 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
3870 else
3871 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
3872 return true;
3873}
3874
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003875bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003876 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003877 default:
3878 return ExprEvaluatorBaseTy::VisitCallExpr(E);
3879
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003880 case Builtin::BI__builtin_huge_val:
3881 case Builtin::BI__builtin_huge_valf:
3882 case Builtin::BI__builtin_huge_vall:
3883 case Builtin::BI__builtin_inf:
3884 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00003885 case Builtin::BI__builtin_infl: {
3886 const llvm::fltSemantics &Sem =
3887 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00003888 Result = llvm::APFloat::getInf(Sem);
3889 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00003890 }
Mike Stump11289f42009-09-09 15:08:12 +00003891
John McCall16291492010-02-28 13:00:19 +00003892 case Builtin::BI__builtin_nans:
3893 case Builtin::BI__builtin_nansf:
3894 case Builtin::BI__builtin_nansl:
3895 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
3896 true, Result);
3897
Chris Lattner0b7282e2008-10-06 06:31:58 +00003898 case Builtin::BI__builtin_nan:
3899 case Builtin::BI__builtin_nanf:
3900 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00003901 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00003902 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00003903 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
3904 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003905
3906 case Builtin::BI__builtin_fabs:
3907 case Builtin::BI__builtin_fabsf:
3908 case Builtin::BI__builtin_fabsl:
3909 if (!EvaluateFloat(E->getArg(0), Result, Info))
3910 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003911
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003912 if (Result.isNegative())
3913 Result.changeSign();
3914 return true;
3915
Mike Stump11289f42009-09-09 15:08:12 +00003916 case Builtin::BI__builtin_copysign:
3917 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003918 case Builtin::BI__builtin_copysignl: {
3919 APFloat RHS(0.);
3920 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
3921 !EvaluateFloat(E->getArg(1), RHS, Info))
3922 return false;
3923 Result.copySign(RHS);
3924 return true;
3925 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003926 }
3927}
3928
John McCallb1fb0d32010-05-07 22:08:54 +00003929bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00003930 if (E->getSubExpr()->getType()->isAnyComplexType()) {
3931 ComplexValue CV;
3932 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
3933 return false;
3934 Result = CV.FloatReal;
3935 return true;
3936 }
3937
3938 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00003939}
3940
3941bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00003942 if (E->getSubExpr()->getType()->isAnyComplexType()) {
3943 ComplexValue CV;
3944 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
3945 return false;
3946 Result = CV.FloatImag;
3947 return true;
3948 }
3949
Richard Smith4a678122011-10-24 18:44:57 +00003950 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00003951 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
3952 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00003953 return true;
3954}
3955
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003956bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003957 switch (E->getOpcode()) {
3958 default: return false;
John McCalle3027922010-08-25 11:45:40 +00003959 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00003960 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00003961 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00003962 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
3963 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003964 Result.changeSign();
3965 return true;
3966 }
3967}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003968
Eli Friedman24c01542008-08-22 00:06:13 +00003969bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003970 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
3971 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00003972
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003973 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00003974 if (!EvaluateFloat(E->getLHS(), Result, Info))
3975 return false;
3976 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3977 return false;
3978
3979 switch (E->getOpcode()) {
3980 default: return false;
John McCalle3027922010-08-25 11:45:40 +00003981 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00003982 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
3983 return true;
John McCalle3027922010-08-25 11:45:40 +00003984 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00003985 Result.add(RHS, APFloat::rmNearestTiesToEven);
3986 return true;
John McCalle3027922010-08-25 11:45:40 +00003987 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00003988 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
3989 return true;
John McCalle3027922010-08-25 11:45:40 +00003990 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00003991 Result.divide(RHS, APFloat::rmNearestTiesToEven);
3992 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00003993 }
3994}
3995
3996bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
3997 Result = E->getValue();
3998 return true;
3999}
4000
Peter Collingbournee9200682011-05-13 03:29:01 +00004001bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4002 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004003
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004004 switch (E->getCastKind()) {
4005 default:
Richard Smith11562c52011-10-28 17:51:58 +00004006 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004007
4008 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004009 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004010 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004011 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004012 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004013 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00004014 return true;
4015 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004016
4017 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004018 if (!Visit(SubExpr))
4019 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004020 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
4021 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00004022 return true;
4023 }
John McCalld7646252010-11-14 08:17:51 +00004024
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004025 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004026 ComplexValue V;
4027 if (!EvaluateComplex(SubExpr, V, Info))
4028 return false;
4029 Result = V.getComplexFloatReal();
4030 return true;
4031 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004032 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004033
4034 return false;
4035}
4036
Eli Friedman24c01542008-08-22 00:06:13 +00004037//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004038// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004039//===----------------------------------------------------------------------===//
4040
4041namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004042class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004043 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004044 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004045
Anders Carlsson537969c2008-11-16 20:27:53 +00004046public:
John McCall93d91dc2010-05-07 17:22:02 +00004047 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004048 : ExprEvaluatorBaseTy(info), Result(Result) {}
4049
Richard Smith0b0a0b62011-10-29 20:57:55 +00004050 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004051 Result.setFrom(V);
4052 return true;
4053 }
4054 bool Error(const Expr *E) {
4055 return false;
4056 }
Mike Stump11289f42009-09-09 15:08:12 +00004057
Anders Carlsson537969c2008-11-16 20:27:53 +00004058 //===--------------------------------------------------------------------===//
4059 // Visitor Methods
4060 //===--------------------------------------------------------------------===//
4061
Peter Collingbournee9200682011-05-13 03:29:01 +00004062 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00004063
Peter Collingbournee9200682011-05-13 03:29:01 +00004064 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004065
John McCall93d91dc2010-05-07 17:22:02 +00004066 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004067 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004068 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00004069};
4070} // end anonymous namespace
4071
John McCall93d91dc2010-05-07 17:22:02 +00004072static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4073 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004074 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004075 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004076}
4077
Peter Collingbournee9200682011-05-13 03:29:01 +00004078bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4079 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004080
4081 if (SubExpr->getType()->isRealFloatingType()) {
4082 Result.makeComplexFloat();
4083 APFloat &Imag = Result.FloatImag;
4084 if (!EvaluateFloat(SubExpr, Imag, Info))
4085 return false;
4086
4087 Result.FloatReal = APFloat(Imag.getSemantics());
4088 return true;
4089 } else {
4090 assert(SubExpr->getType()->isIntegerType() &&
4091 "Unexpected imaginary literal.");
4092
4093 Result.makeComplexInt();
4094 APSInt &Imag = Result.IntImag;
4095 if (!EvaluateInteger(SubExpr, Imag, Info))
4096 return false;
4097
4098 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4099 return true;
4100 }
4101}
4102
Peter Collingbournee9200682011-05-13 03:29:01 +00004103bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004104
John McCallfcef3cf2010-12-14 17:51:41 +00004105 switch (E->getCastKind()) {
4106 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004107 case CK_BaseToDerived:
4108 case CK_DerivedToBase:
4109 case CK_UncheckedDerivedToBase:
4110 case CK_Dynamic:
4111 case CK_ToUnion:
4112 case CK_ArrayToPointerDecay:
4113 case CK_FunctionToPointerDecay:
4114 case CK_NullToPointer:
4115 case CK_NullToMemberPointer:
4116 case CK_BaseToDerivedMemberPointer:
4117 case CK_DerivedToBaseMemberPointer:
4118 case CK_MemberPointerToBoolean:
4119 case CK_ConstructorConversion:
4120 case CK_IntegralToPointer:
4121 case CK_PointerToIntegral:
4122 case CK_PointerToBoolean:
4123 case CK_ToVoid:
4124 case CK_VectorSplat:
4125 case CK_IntegralCast:
4126 case CK_IntegralToBoolean:
4127 case CK_IntegralToFloating:
4128 case CK_FloatingToIntegral:
4129 case CK_FloatingToBoolean:
4130 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004131 case CK_CPointerToObjCPointerCast:
4132 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004133 case CK_AnyPointerToBlockPointerCast:
4134 case CK_ObjCObjectLValueCast:
4135 case CK_FloatingComplexToReal:
4136 case CK_FloatingComplexToBoolean:
4137 case CK_IntegralComplexToReal:
4138 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004139 case CK_ARCProduceObject:
4140 case CK_ARCConsumeObject:
4141 case CK_ARCReclaimReturnedObject:
4142 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004143 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004144
John McCallfcef3cf2010-12-14 17:51:41 +00004145 case CK_LValueToRValue:
4146 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004147 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004148
4149 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004150 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004151 case CK_UserDefinedConversion:
4152 return false;
4153
4154 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004155 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004156 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004157 return false;
4158
John McCallfcef3cf2010-12-14 17:51:41 +00004159 Result.makeComplexFloat();
4160 Result.FloatImag = APFloat(Real.getSemantics());
4161 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004162 }
4163
John McCallfcef3cf2010-12-14 17:51:41 +00004164 case CK_FloatingComplexCast: {
4165 if (!Visit(E->getSubExpr()))
4166 return false;
4167
4168 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4169 QualType From
4170 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4171
4172 Result.FloatReal
4173 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
4174 Result.FloatImag
4175 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
4176 return true;
4177 }
4178
4179 case CK_FloatingComplexToIntegralComplex: {
4180 if (!Visit(E->getSubExpr()))
4181 return false;
4182
4183 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4184 QualType From
4185 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4186 Result.makeComplexInt();
4187 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
4188 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
4189 return true;
4190 }
4191
4192 case CK_IntegralRealToComplex: {
4193 APSInt &Real = Result.IntReal;
4194 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4195 return false;
4196
4197 Result.makeComplexInt();
4198 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4199 return true;
4200 }
4201
4202 case CK_IntegralComplexCast: {
4203 if (!Visit(E->getSubExpr()))
4204 return false;
4205
4206 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4207 QualType From
4208 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4209
4210 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4211 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4212 return true;
4213 }
4214
4215 case CK_IntegralComplexToFloatingComplex: {
4216 if (!Visit(E->getSubExpr()))
4217 return false;
4218
4219 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4220 QualType From
4221 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4222 Result.makeComplexFloat();
4223 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
4224 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
4225 return true;
4226 }
4227 }
4228
4229 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004230 return false;
4231}
4232
John McCall93d91dc2010-05-07 17:22:02 +00004233bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004234 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00004235 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4236
John McCall93d91dc2010-05-07 17:22:02 +00004237 if (!Visit(E->getLHS()))
4238 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004239
John McCall93d91dc2010-05-07 17:22:02 +00004240 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004241 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00004242 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004243
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004244 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4245 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004246 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00004247 default: return false;
John McCalle3027922010-08-25 11:45:40 +00004248 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004249 if (Result.isComplexFloat()) {
4250 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4251 APFloat::rmNearestTiesToEven);
4252 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4253 APFloat::rmNearestTiesToEven);
4254 } else {
4255 Result.getComplexIntReal() += RHS.getComplexIntReal();
4256 Result.getComplexIntImag() += RHS.getComplexIntImag();
4257 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004258 break;
John McCalle3027922010-08-25 11:45:40 +00004259 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004260 if (Result.isComplexFloat()) {
4261 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4262 APFloat::rmNearestTiesToEven);
4263 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4264 APFloat::rmNearestTiesToEven);
4265 } else {
4266 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4267 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4268 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004269 break;
John McCalle3027922010-08-25 11:45:40 +00004270 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004271 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00004272 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004273 APFloat &LHS_r = LHS.getComplexFloatReal();
4274 APFloat &LHS_i = LHS.getComplexFloatImag();
4275 APFloat &RHS_r = RHS.getComplexFloatReal();
4276 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00004277
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004278 APFloat Tmp = LHS_r;
4279 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4280 Result.getComplexFloatReal() = Tmp;
4281 Tmp = LHS_i;
4282 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4283 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4284
4285 Tmp = LHS_r;
4286 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4287 Result.getComplexFloatImag() = Tmp;
4288 Tmp = LHS_i;
4289 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4290 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4291 } else {
John McCall93d91dc2010-05-07 17:22:02 +00004292 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00004293 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004294 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4295 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00004296 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004297 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4298 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4299 }
4300 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004301 case BO_Div:
4302 if (Result.isComplexFloat()) {
4303 ComplexValue LHS = Result;
4304 APFloat &LHS_r = LHS.getComplexFloatReal();
4305 APFloat &LHS_i = LHS.getComplexFloatImag();
4306 APFloat &RHS_r = RHS.getComplexFloatReal();
4307 APFloat &RHS_i = RHS.getComplexFloatImag();
4308 APFloat &Res_r = Result.getComplexFloatReal();
4309 APFloat &Res_i = Result.getComplexFloatImag();
4310
4311 APFloat Den = RHS_r;
4312 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4313 APFloat Tmp = RHS_i;
4314 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4315 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4316
4317 Res_r = LHS_r;
4318 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4319 Tmp = LHS_i;
4320 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4321 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4322 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4323
4324 Res_i = LHS_i;
4325 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4326 Tmp = LHS_r;
4327 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4328 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4329 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4330 } else {
4331 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
4332 // FIXME: what about diagnostics?
4333 return false;
4334 }
4335 ComplexValue LHS = Result;
4336 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4337 RHS.getComplexIntImag() * RHS.getComplexIntImag();
4338 Result.getComplexIntReal() =
4339 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
4340 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
4341 Result.getComplexIntImag() =
4342 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
4343 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
4344 }
4345 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004346 }
4347
John McCall93d91dc2010-05-07 17:22:02 +00004348 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004349}
4350
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004351bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4352 // Get the operand value into 'Result'.
4353 if (!Visit(E->getSubExpr()))
4354 return false;
4355
4356 switch (E->getOpcode()) {
4357 default:
4358 // FIXME: what about diagnostics?
4359 return false;
4360 case UO_Extension:
4361 return true;
4362 case UO_Plus:
4363 // The result is always just the subexpr.
4364 return true;
4365 case UO_Minus:
4366 if (Result.isComplexFloat()) {
4367 Result.getComplexFloatReal().changeSign();
4368 Result.getComplexFloatImag().changeSign();
4369 }
4370 else {
4371 Result.getComplexIntReal() = -Result.getComplexIntReal();
4372 Result.getComplexIntImag() = -Result.getComplexIntImag();
4373 }
4374 return true;
4375 case UO_Not:
4376 if (Result.isComplexFloat())
4377 Result.getComplexFloatImag().changeSign();
4378 else
4379 Result.getComplexIntImag() = -Result.getComplexIntImag();
4380 return true;
4381 }
4382}
4383
Anders Carlsson537969c2008-11-16 20:27:53 +00004384//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00004385// Void expression evaluation, primarily for a cast to void on the LHS of a
4386// comma operator
4387//===----------------------------------------------------------------------===//
4388
4389namespace {
4390class VoidExprEvaluator
4391 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
4392public:
4393 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
4394
4395 bool Success(const CCValue &V, const Expr *e) { return true; }
4396 bool Error(const Expr *E) { return false; }
4397
4398 bool VisitCastExpr(const CastExpr *E) {
4399 switch (E->getCastKind()) {
4400 default:
4401 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4402 case CK_ToVoid:
4403 VisitIgnoredValue(E->getSubExpr());
4404 return true;
4405 }
4406 }
4407};
4408} // end anonymous namespace
4409
4410static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
4411 assert(E->isRValue() && E->getType()->isVoidType());
4412 return VoidExprEvaluator(Info).Visit(E);
4413}
4414
4415//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00004416// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00004417//===----------------------------------------------------------------------===//
4418
Richard Smith0b0a0b62011-10-29 20:57:55 +00004419static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004420 // In C, function designators are not lvalues, but we evaluate them as if they
4421 // are.
4422 if (E->isGLValue() || E->getType()->isFunctionType()) {
4423 LValue LV;
4424 if (!EvaluateLValue(E, LV, Info))
4425 return false;
4426 LV.moveInto(Result);
4427 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004428 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004429 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004430 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004431 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004432 return false;
John McCall45d55e42010-05-07 21:00:08 +00004433 } else if (E->getType()->hasPointerRepresentation()) {
4434 LValue LV;
4435 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004436 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004437 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00004438 } else if (E->getType()->isRealFloatingType()) {
4439 llvm::APFloat F(0.0);
4440 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004441 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004442 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00004443 } else if (E->getType()->isAnyComplexType()) {
4444 ComplexValue C;
4445 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004446 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004447 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00004448 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004449 MemberPtr P;
4450 if (!EvaluateMemberPointer(E, P, Info))
4451 return false;
4452 P.moveInto(Result);
4453 return true;
Richard Smithed5165f2011-11-04 05:33:44 +00004454 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004455 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004456 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004457 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00004458 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004459 Result = Info.CurrentCall->Temporaries[E];
Richard Smithed5165f2011-11-04 05:33:44 +00004460 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004461 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004462 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004463 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
4464 return false;
4465 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00004466 } else if (E->getType()->isVoidType()) {
4467 if (!EvaluateVoid(E, Info))
4468 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004469 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00004470 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004471
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00004472 return true;
4473}
4474
Richard Smithed5165f2011-11-04 05:33:44 +00004475/// EvaluateConstantExpression - Evaluate an expression as a constant expression
4476/// in-place in an APValue. In some cases, the in-place evaluation is essential,
4477/// since later initializers for an object can indirectly refer to subobjects
4478/// which were initialized earlier.
4479static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +00004480 const LValue &This, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004481 if (E->isRValue() && E->getType()->isLiteralType()) {
4482 // Evaluate arrays and record types in-place, so that later initializers can
4483 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00004484 if (E->getType()->isArrayType())
4485 return EvaluateArray(E, This, Result, Info);
4486 else if (E->getType()->isRecordType())
4487 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00004488 }
4489
4490 // For any other type, in-place evaluation is unimportant.
4491 CCValue CoreConstResult;
4492 return Evaluate(CoreConstResult, Info, E) &&
4493 CheckConstantExpression(CoreConstResult, Result);
4494}
4495
Richard Smith11562c52011-10-28 17:51:58 +00004496
Richard Smith7b553f12011-10-29 00:50:52 +00004497/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00004498/// any crazy technique (that has nothing to do with language standards) that
4499/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00004500/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
4501/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00004502bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith5686e752011-11-10 03:30:42 +00004503 // FIXME: Evaluating initializers for large arrays can cause performance
4504 // problems, and we don't use such values yet. Once we have a more efficient
4505 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00004506 // The same problem affects large records.
4507 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
4508 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00004509 return false;
4510
John McCallc07a0c72011-02-17 10:25:35 +00004511 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00004512
Richard Smithd62306a2011-11-10 06:34:14 +00004513 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smith0b0a0b62011-10-29 20:57:55 +00004514 CCValue Value;
4515 if (!::Evaluate(Value, Info, this))
Richard Smith11562c52011-10-28 17:51:58 +00004516 return false;
4517
4518 if (isGLValue()) {
4519 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004520 LV.setFrom(Value);
4521 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
4522 return false;
Richard Smith11562c52011-10-28 17:51:58 +00004523 }
4524
Richard Smith0b0a0b62011-10-29 20:57:55 +00004525 // Check this core constant expression is a constant expression, and if so,
Richard Smithed5165f2011-11-04 05:33:44 +00004526 // convert it to one.
4527 return CheckConstantExpression(Value, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00004528}
4529
Jay Foad39c79802011-01-12 09:06:06 +00004530bool Expr::EvaluateAsBooleanCondition(bool &Result,
4531 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00004532 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00004533 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00004534 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00004535 Result);
John McCall1be1c632010-01-05 23:42:56 +00004536}
4537
Richard Smithcaf33902011-10-10 18:28:20 +00004538bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00004539 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004540 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smith11562c52011-10-28 17:51:58 +00004541 !ExprResult.Val.isInt()) {
4542 return false;
4543 }
4544 Result = ExprResult.Val.getInt();
4545 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00004546}
4547
Jay Foad39c79802011-01-12 09:06:06 +00004548bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00004549 EvalInfo Info(Ctx, Result);
4550
John McCall45d55e42010-05-07 21:00:08 +00004551 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00004552 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
4553 CheckLValueConstantExpression(LV, Result.Val);
Eli Friedman7d45c482009-09-13 10:17:44 +00004554}
4555
Richard Smith7b553f12011-10-29 00:50:52 +00004556/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
4557/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00004558bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00004559 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00004560 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00004561}
Anders Carlsson59689ed2008-11-22 21:04:56 +00004562
Jay Foad39c79802011-01-12 09:06:06 +00004563bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00004564 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00004565}
4566
Richard Smithcaf33902011-10-10 18:28:20 +00004567APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004568 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004569 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00004570 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00004571 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004572 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00004573
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004574 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00004575}
John McCall864e3962010-05-07 05:32:02 +00004576
Abramo Bagnaraf8199452010-05-14 17:07:14 +00004577 bool Expr::EvalResult::isGlobalLValue() const {
4578 assert(Val.isLValue());
4579 return IsGlobalLValue(Val.getLValueBase());
4580 }
4581
4582
John McCall864e3962010-05-07 05:32:02 +00004583/// isIntegerConstantExpr - this recursive routine will test if an expression is
4584/// an integer constant expression.
4585
4586/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
4587/// comma, etc
4588///
4589/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
4590/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
4591/// cast+dereference.
4592
4593// CheckICE - This function does the fundamental ICE checking: the returned
4594// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
4595// Note that to reduce code duplication, this helper does no evaluation
4596// itself; the caller checks whether the expression is evaluatable, and
4597// in the rare cases where CheckICE actually cares about the evaluated
4598// value, it calls into Evalute.
4599//
4600// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00004601// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00004602// 1: This expression is not an ICE, but if it isn't evaluated, it's
4603// a legal subexpression for an ICE. This return value is used to handle
4604// the comma operator in C99 mode.
4605// 2: This expression is not an ICE, and is not a legal subexpression for one.
4606
Dan Gohman28ade552010-07-26 21:25:24 +00004607namespace {
4608
John McCall864e3962010-05-07 05:32:02 +00004609struct ICEDiag {
4610 unsigned Val;
4611 SourceLocation Loc;
4612
4613 public:
4614 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
4615 ICEDiag() : Val(0) {}
4616};
4617
Dan Gohman28ade552010-07-26 21:25:24 +00004618}
4619
4620static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00004621
4622static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
4623 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004624 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00004625 !EVResult.Val.isInt()) {
4626 return ICEDiag(2, E->getLocStart());
4627 }
4628 return NoDiag();
4629}
4630
4631static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
4632 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00004633 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00004634 return ICEDiag(2, E->getLocStart());
4635 }
4636
4637 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00004638#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00004639#define STMT(Node, Base) case Expr::Node##Class:
4640#define EXPR(Node, Base)
4641#include "clang/AST/StmtNodes.inc"
4642 case Expr::PredefinedExprClass:
4643 case Expr::FloatingLiteralClass:
4644 case Expr::ImaginaryLiteralClass:
4645 case Expr::StringLiteralClass:
4646 case Expr::ArraySubscriptExprClass:
4647 case Expr::MemberExprClass:
4648 case Expr::CompoundAssignOperatorClass:
4649 case Expr::CompoundLiteralExprClass:
4650 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00004651 case Expr::DesignatedInitExprClass:
4652 case Expr::ImplicitValueInitExprClass:
4653 case Expr::ParenListExprClass:
4654 case Expr::VAArgExprClass:
4655 case Expr::AddrLabelExprClass:
4656 case Expr::StmtExprClass:
4657 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00004658 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00004659 case Expr::CXXDynamicCastExprClass:
4660 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00004661 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00004662 case Expr::CXXNullPtrLiteralExprClass:
4663 case Expr::CXXThisExprClass:
4664 case Expr::CXXThrowExprClass:
4665 case Expr::CXXNewExprClass:
4666 case Expr::CXXDeleteExprClass:
4667 case Expr::CXXPseudoDestructorExprClass:
4668 case Expr::UnresolvedLookupExprClass:
4669 case Expr::DependentScopeDeclRefExprClass:
4670 case Expr::CXXConstructExprClass:
4671 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00004672 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00004673 case Expr::CXXTemporaryObjectExprClass:
4674 case Expr::CXXUnresolvedConstructExprClass:
4675 case Expr::CXXDependentScopeMemberExprClass:
4676 case Expr::UnresolvedMemberExprClass:
4677 case Expr::ObjCStringLiteralClass:
4678 case Expr::ObjCEncodeExprClass:
4679 case Expr::ObjCMessageExprClass:
4680 case Expr::ObjCSelectorExprClass:
4681 case Expr::ObjCProtocolExprClass:
4682 case Expr::ObjCIvarRefExprClass:
4683 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00004684 case Expr::ObjCIsaExprClass:
4685 case Expr::ShuffleVectorExprClass:
4686 case Expr::BlockExprClass:
4687 case Expr::BlockDeclRefExprClass:
4688 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00004689 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004690 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00004691 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00004692 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00004693 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00004694 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00004695 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004696 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00004697 return ICEDiag(2, E->getLocStart());
4698
Sebastian Redl12757ab2011-09-24 17:48:14 +00004699 case Expr::InitListExprClass:
4700 if (Ctx.getLangOptions().CPlusPlus0x) {
4701 const InitListExpr *ILE = cast<InitListExpr>(E);
4702 if (ILE->getNumInits() == 0)
4703 return NoDiag();
4704 if (ILE->getNumInits() == 1)
4705 return CheckICE(ILE->getInit(0), Ctx);
4706 // Fall through for more than 1 expression.
4707 }
4708 return ICEDiag(2, E->getLocStart());
4709
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004710 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00004711 case Expr::GNUNullExprClass:
4712 // GCC considers the GNU __null value to be an integral constant expression.
4713 return NoDiag();
4714
John McCall7c454bb2011-07-15 05:09:51 +00004715 case Expr::SubstNonTypeTemplateParmExprClass:
4716 return
4717 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
4718
John McCall864e3962010-05-07 05:32:02 +00004719 case Expr::ParenExprClass:
4720 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00004721 case Expr::GenericSelectionExprClass:
4722 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00004723 case Expr::IntegerLiteralClass:
4724 case Expr::CharacterLiteralClass:
4725 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00004726 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00004727 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004728 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00004729 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00004730 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00004731 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00004732 return NoDiag();
4733 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00004734 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00004735 // C99 6.6/3 allows function calls within unevaluated subexpressions of
4736 // constant expressions, but they can never be ICEs because an ICE cannot
4737 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00004738 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004739 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00004740 return CheckEvalInICE(E, Ctx);
4741 return ICEDiag(2, E->getLocStart());
4742 }
4743 case Expr::DeclRefExprClass:
4744 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
4745 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00004746 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00004747 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4748
4749 // Parameter variables are never constants. Without this check,
4750 // getAnyInitializer() can find a default argument, which leads
4751 // to chaos.
4752 if (isa<ParmVarDecl>(D))
4753 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4754
4755 // C++ 7.1.5.1p2
4756 // A variable of non-volatile const-qualified integral or enumeration
4757 // type initialized by an ICE can be used in ICEs.
4758 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00004759 if (!Dcl->getType()->isIntegralOrEnumerationType())
4760 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4761
John McCall864e3962010-05-07 05:32:02 +00004762 // Look for a declaration of this variable that has an initializer.
4763 const VarDecl *ID = 0;
4764 const Expr *Init = Dcl->getAnyInitializer(ID);
4765 if (Init) {
4766 if (ID->isInitKnownICE()) {
4767 // We have already checked whether this subexpression is an
4768 // integral constant expression.
4769 if (ID->isInitICE())
4770 return NoDiag();
4771 else
4772 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4773 }
4774
4775 // It's an ICE whether or not the definition we found is
4776 // out-of-line. See DR 721 and the discussion in Clang PR
4777 // 6206 for details.
4778
4779 if (Dcl->isCheckingICE()) {
4780 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4781 }
4782
4783 Dcl->setCheckingICE();
4784 ICEDiag Result = CheckICE(Init, Ctx);
4785 // Cache the result of the ICE test.
4786 Dcl->setInitKnownICE(Result.Val == 0);
4787 return Result;
4788 }
4789 }
4790 }
4791 return ICEDiag(2, E->getLocStart());
4792 case Expr::UnaryOperatorClass: {
4793 const UnaryOperator *Exp = cast<UnaryOperator>(E);
4794 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004795 case UO_PostInc:
4796 case UO_PostDec:
4797 case UO_PreInc:
4798 case UO_PreDec:
4799 case UO_AddrOf:
4800 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00004801 // C99 6.6/3 allows increment and decrement within unevaluated
4802 // subexpressions of constant expressions, but they can never be ICEs
4803 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00004804 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00004805 case UO_Extension:
4806 case UO_LNot:
4807 case UO_Plus:
4808 case UO_Minus:
4809 case UO_Not:
4810 case UO_Real:
4811 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00004812 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00004813 }
4814
4815 // OffsetOf falls through here.
4816 }
4817 case Expr::OffsetOfExprClass: {
4818 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00004819 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00004820 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00004821 // compliance: we should warn earlier for offsetof expressions with
4822 // array subscripts that aren't ICEs, and if the array subscripts
4823 // are ICEs, the value of the offsetof must be an integer constant.
4824 return CheckEvalInICE(E, Ctx);
4825 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00004826 case Expr::UnaryExprOrTypeTraitExprClass: {
4827 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
4828 if ((Exp->getKind() == UETT_SizeOf) &&
4829 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00004830 return ICEDiag(2, E->getLocStart());
4831 return NoDiag();
4832 }
4833 case Expr::BinaryOperatorClass: {
4834 const BinaryOperator *Exp = cast<BinaryOperator>(E);
4835 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004836 case BO_PtrMemD:
4837 case BO_PtrMemI:
4838 case BO_Assign:
4839 case BO_MulAssign:
4840 case BO_DivAssign:
4841 case BO_RemAssign:
4842 case BO_AddAssign:
4843 case BO_SubAssign:
4844 case BO_ShlAssign:
4845 case BO_ShrAssign:
4846 case BO_AndAssign:
4847 case BO_XorAssign:
4848 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00004849 // C99 6.6/3 allows assignments within unevaluated subexpressions of
4850 // constant expressions, but they can never be ICEs because an ICE cannot
4851 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00004852 return ICEDiag(2, E->getLocStart());
4853
John McCalle3027922010-08-25 11:45:40 +00004854 case BO_Mul:
4855 case BO_Div:
4856 case BO_Rem:
4857 case BO_Add:
4858 case BO_Sub:
4859 case BO_Shl:
4860 case BO_Shr:
4861 case BO_LT:
4862 case BO_GT:
4863 case BO_LE:
4864 case BO_GE:
4865 case BO_EQ:
4866 case BO_NE:
4867 case BO_And:
4868 case BO_Xor:
4869 case BO_Or:
4870 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00004871 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
4872 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00004873 if (Exp->getOpcode() == BO_Div ||
4874 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00004875 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00004876 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00004877 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00004878 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00004879 if (REval == 0)
4880 return ICEDiag(1, E->getLocStart());
4881 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00004882 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00004883 if (LEval.isMinSignedValue())
4884 return ICEDiag(1, E->getLocStart());
4885 }
4886 }
4887 }
John McCalle3027922010-08-25 11:45:40 +00004888 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00004889 if (Ctx.getLangOptions().C99) {
4890 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
4891 // if it isn't evaluated.
4892 if (LHSResult.Val == 0 && RHSResult.Val == 0)
4893 return ICEDiag(1, E->getLocStart());
4894 } else {
4895 // In both C89 and C++, commas in ICEs are illegal.
4896 return ICEDiag(2, E->getLocStart());
4897 }
4898 }
4899 if (LHSResult.Val >= RHSResult.Val)
4900 return LHSResult;
4901 return RHSResult;
4902 }
John McCalle3027922010-08-25 11:45:40 +00004903 case BO_LAnd:
4904 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00004905 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00004906
4907 // C++0x [expr.const]p2:
4908 // [...] subexpressions of logical AND (5.14), logical OR
4909 // (5.15), and condi- tional (5.16) operations that are not
4910 // evaluated are not considered.
4911 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
4912 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00004913 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00004914 return LHSResult;
4915
4916 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00004917 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00004918 return LHSResult;
4919 }
4920
John McCall864e3962010-05-07 05:32:02 +00004921 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
4922 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
4923 // Rare case where the RHS has a comma "side-effect"; we need
4924 // to actually check the condition to see whether the side
4925 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00004926 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00004927 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00004928 return RHSResult;
4929 return NoDiag();
4930 }
4931
4932 if (LHSResult.Val >= RHSResult.Val)
4933 return LHSResult;
4934 return RHSResult;
4935 }
4936 }
4937 }
4938 case Expr::ImplicitCastExprClass:
4939 case Expr::CStyleCastExprClass:
4940 case Expr::CXXFunctionalCastExprClass:
4941 case Expr::CXXStaticCastExprClass:
4942 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00004943 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004944 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00004945 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00004946 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00004947 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
4948 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00004949 switch (cast<CastExpr>(E)->getCastKind()) {
4950 case CK_LValueToRValue:
4951 case CK_NoOp:
4952 case CK_IntegralToBoolean:
4953 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00004954 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00004955 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00004956 return ICEDiag(2, E->getLocStart());
4957 }
John McCall864e3962010-05-07 05:32:02 +00004958 }
John McCallc07a0c72011-02-17 10:25:35 +00004959 case Expr::BinaryConditionalOperatorClass: {
4960 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
4961 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
4962 if (CommonResult.Val == 2) return CommonResult;
4963 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
4964 if (FalseResult.Val == 2) return FalseResult;
4965 if (CommonResult.Val == 1) return CommonResult;
4966 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00004967 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00004968 return FalseResult;
4969 }
John McCall864e3962010-05-07 05:32:02 +00004970 case Expr::ConditionalOperatorClass: {
4971 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
4972 // If the condition (ignoring parens) is a __builtin_constant_p call,
4973 // then only the true side is actually considered in an integer constant
4974 // expression, and it is fully evaluated. This is an important GNU
4975 // extension. See GCC PR38377 for discussion.
4976 if (const CallExpr *CallCE
4977 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smithd62306a2011-11-10 06:34:14 +00004978 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCall864e3962010-05-07 05:32:02 +00004979 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004980 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00004981 !EVResult.Val.isInt()) {
4982 return ICEDiag(2, E->getLocStart());
4983 }
4984 return NoDiag();
4985 }
4986 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00004987 if (CondResult.Val == 2)
4988 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00004989
4990 // C++0x [expr.const]p2:
4991 // subexpressions of [...] conditional (5.16) operations that
4992 // are not evaluated are not considered
4993 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00004994 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00004995 : false;
4996 ICEDiag TrueResult = NoDiag();
4997 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
4998 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
4999 ICEDiag FalseResult = NoDiag();
5000 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
5001 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5002
John McCall864e3962010-05-07 05:32:02 +00005003 if (TrueResult.Val == 2)
5004 return TrueResult;
5005 if (FalseResult.Val == 2)
5006 return FalseResult;
5007 if (CondResult.Val == 1)
5008 return CondResult;
5009 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5010 return NoDiag();
5011 // Rare case where the diagnostics depend on which side is evaluated
5012 // Note that if we get here, CondResult is 0, and at least one of
5013 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005014 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005015 return FalseResult;
5016 }
5017 return TrueResult;
5018 }
5019 case Expr::CXXDefaultArgExprClass:
5020 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5021 case Expr::ChooseExprClass: {
5022 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5023 }
5024 }
5025
5026 // Silence a GCC warning
5027 return ICEDiag(2, E->getLocStart());
5028}
5029
5030bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
5031 SourceLocation *Loc, bool isEvaluated) const {
5032 ICEDiag d = CheckICE(this, Ctx);
5033 if (d.Val != 0) {
5034 if (Loc) *Loc = d.Loc;
5035 return false;
5036 }
Richard Smith11562c52011-10-28 17:51:58 +00005037 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005038 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005039 return true;
5040}