blob: f2e3d36d751b675f30349a367cbcbf63269f7a8e [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Richard Smith254a73d2011-10-28 22:34:42 +000046 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000047 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000048
Richard Smith80815602011-11-07 05:07:52 +000049 /// Determine whether the described subobject is an array element.
50 static bool SubobjectIsArrayElement(QualType Base,
51 ArrayRef<APValue::LValuePathEntry> Path) {
52 bool IsArrayElement = false;
53 const Type *T = Base.getTypePtr();
54 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
55 IsArrayElement = T && T->isArrayType();
56 if (IsArrayElement)
57 T = T->getBaseElementTypeUnsafe();
58 else if (const FieldDecl *FD = dyn_cast<FieldDecl>(Path[I].BaseOrMember))
59 T = FD->getType().getTypePtr();
60 else
61 // Path[I] describes a base class.
62 T = 0;
63 }
64 return IsArrayElement;
65 }
66
Richard Smith96e0c102011-11-04 02:25:55 +000067 /// A path from a glvalue to a subobject of that glvalue.
68 struct SubobjectDesignator {
69 /// True if the subobject was named in a manner not supported by C++11. Such
70 /// lvalues can still be folded, but they are not core constant expressions
71 /// and we cannot perform lvalue-to-rvalue conversions on them.
72 bool Invalid : 1;
73
74 /// Whether this designates an array element.
75 bool ArrayElement : 1;
76
77 /// Whether this designates 'one past the end' of the current subobject.
78 bool OnePastTheEnd : 1;
79
Richard Smith80815602011-11-07 05:07:52 +000080 typedef APValue::LValuePathEntry PathEntry;
81
Richard Smith96e0c102011-11-04 02:25:55 +000082 /// The entries on the path from the glvalue to the designated subobject.
83 SmallVector<PathEntry, 8> Entries;
84
85 SubobjectDesignator() :
86 Invalid(false), ArrayElement(false), OnePastTheEnd(false) {}
87
Richard Smith80815602011-11-07 05:07:52 +000088 SubobjectDesignator(const APValue &V) :
89 Invalid(!V.isLValue() || !V.hasLValuePath()), ArrayElement(false),
90 OnePastTheEnd(false) {
91 if (!Invalid) {
92 ArrayRef<PathEntry> VEntries = V.getLValuePath();
93 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
94 if (V.getLValueBase())
95 ArrayElement = SubobjectIsArrayElement(V.getLValueBase()->getType(),
96 V.getLValuePath());
97 else
98 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
99 }
100 }
101
Richard Smith96e0c102011-11-04 02:25:55 +0000102 void setInvalid() {
103 Invalid = true;
104 Entries.clear();
105 }
106 /// Update this designator to refer to the given element within this array.
107 void addIndex(uint64_t N) {
108 if (Invalid) return;
109 if (OnePastTheEnd) {
110 setInvalid();
111 return;
112 }
113 PathEntry Entry;
Richard Smith80815602011-11-07 05:07:52 +0000114 Entry.ArrayIndex = N;
Richard Smith96e0c102011-11-04 02:25:55 +0000115 Entries.push_back(Entry);
116 ArrayElement = true;
117 }
118 /// Update this designator to refer to the given base or member of this
119 /// object.
120 void addDecl(const Decl *D) {
121 if (Invalid) return;
122 if (OnePastTheEnd) {
123 setInvalid();
124 return;
125 }
126 PathEntry Entry;
127 Entry.BaseOrMember = D;
128 Entries.push_back(Entry);
129 ArrayElement = false;
130 }
131 /// Add N to the address of this subobject.
132 void adjustIndex(uint64_t N) {
133 if (Invalid) return;
134 if (ArrayElement) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000135 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith80815602011-11-07 05:07:52 +0000136 Entries.back().ArrayIndex += N;
Richard Smith96e0c102011-11-04 02:25:55 +0000137 return;
138 }
139 if (OnePastTheEnd && N == (uint64_t)-1)
140 OnePastTheEnd = false;
141 else if (!OnePastTheEnd && N == 1)
142 OnePastTheEnd = true;
143 else if (N != 0)
144 setInvalid();
145 }
146 };
147
Richard Smith0b0a0b62011-10-29 20:57:55 +0000148 /// A core constant value. This can be the value of any constant expression,
149 /// or a pointer or reference to a non-static object or function parameter.
150 class CCValue : public APValue {
151 typedef llvm::APSInt APSInt;
152 typedef llvm::APFloat APFloat;
Richard Smithfec09922011-11-01 16:57:24 +0000153 /// If the value is a reference or pointer into a parameter or temporary,
154 /// this is the corresponding call stack frame.
155 CallStackFrame *CallFrame;
Richard Smith96e0c102011-11-04 02:25:55 +0000156 /// If the value is a reference or pointer, this is a description of how the
157 /// subobject was specified.
158 SubobjectDesignator Designator;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000159 public:
Richard Smithfec09922011-11-01 16:57:24 +0000160 struct GlobalValue {};
161
Richard Smith0b0a0b62011-10-29 20:57:55 +0000162 CCValue() {}
163 explicit CCValue(const APSInt &I) : APValue(I) {}
164 explicit CCValue(const APFloat &F) : APValue(F) {}
165 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
166 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
167 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smithfec09922011-11-01 16:57:24 +0000168 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000169 CCValue(const Expr *B, const CharUnits &O, CallStackFrame *F,
170 const SubobjectDesignator &D) :
Richard Smith80815602011-11-07 05:07:52 +0000171 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithfec09922011-11-01 16:57:24 +0000172 CCValue(const APValue &V, GlobalValue) :
Richard Smith80815602011-11-07 05:07:52 +0000173 APValue(V), CallFrame(0), Designator(V) {}
Richard Smith0b0a0b62011-10-29 20:57:55 +0000174
Richard Smithfec09922011-11-01 16:57:24 +0000175 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000176 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +0000177 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000178 }
Richard Smith96e0c102011-11-04 02:25:55 +0000179 SubobjectDesignator &getLValueDesignator() {
180 assert(getKind() == LValue);
181 return Designator;
182 }
183 const SubobjectDesignator &getLValueDesignator() const {
184 return const_cast<CCValue*>(this)->getLValueDesignator();
185 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000186 };
187
Richard Smith254a73d2011-10-28 22:34:42 +0000188 /// A stack frame in the constexpr call stack.
189 struct CallStackFrame {
190 EvalInfo &Info;
191
192 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000193 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000194
195 /// ParmBindings - Parameter bindings for this function call, indexed by
196 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000197 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000198
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000199 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
200 typedef MapTy::const_iterator temp_iterator;
201 /// Temporaries - Temporary lvalues materialized within this stack frame.
202 MapTy Temporaries;
203
204 CallStackFrame(EvalInfo &Info, const CCValue *Arguments);
205 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000206 };
207
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000208 struct EvalInfo {
209 const ASTContext &Ctx;
210
211 /// EvalStatus - Contains information about the evaluation.
212 Expr::EvalStatus &EvalStatus;
213
214 /// CurrentCall - The top of the constexpr call stack.
215 CallStackFrame *CurrentCall;
216
217 /// NumCalls - The number of calls we've evaluated so far.
218 unsigned NumCalls;
219
220 /// CallStackDepth - The number of calls in the call stack right now.
221 unsigned CallStackDepth;
222
223 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
224 /// OpaqueValues - Values used as the common expression in a
225 /// BinaryConditionalOperator.
226 MapTy OpaqueValues;
227
228 /// BottomFrame - The frame in which evaluation started. This must be
229 /// initialized last.
230 CallStackFrame BottomFrame;
231
232
233 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
234 : Ctx(C), EvalStatus(S), CurrentCall(0), NumCalls(0), CallStackDepth(0),
235 BottomFrame(*this, 0) {}
236
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000237 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
238 MapTy::const_iterator i = OpaqueValues.find(e);
239 if (i == OpaqueValues.end()) return 0;
240 return &i->second;
241 }
242
243 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
244 };
245
246 CallStackFrame::CallStackFrame(EvalInfo &Info, const CCValue *Arguments)
Richard Smithfec09922011-11-01 16:57:24 +0000247 : Info(Info), Caller(Info.CurrentCall), Arguments(Arguments) {
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000248 Info.CurrentCall = this;
249 ++Info.CallStackDepth;
250 }
251
252 CallStackFrame::~CallStackFrame() {
253 assert(Info.CurrentCall == this && "calls retired out of order");
254 --Info.CallStackDepth;
255 Info.CurrentCall = Caller;
256 }
257
John McCall93d91dc2010-05-07 17:22:02 +0000258 struct ComplexValue {
259 private:
260 bool IsInt;
261
262 public:
263 APSInt IntReal, IntImag;
264 APFloat FloatReal, FloatImag;
265
266 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
267
268 void makeComplexFloat() { IsInt = false; }
269 bool isComplexFloat() const { return !IsInt; }
270 APFloat &getComplexFloatReal() { return FloatReal; }
271 APFloat &getComplexFloatImag() { return FloatImag; }
272
273 void makeComplexInt() { IsInt = true; }
274 bool isComplexInt() const { return IsInt; }
275 APSInt &getComplexIntReal() { return IntReal; }
276 APSInt &getComplexIntImag() { return IntImag; }
277
Richard Smith0b0a0b62011-10-29 20:57:55 +0000278 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000279 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000280 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000281 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000282 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000283 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000284 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000285 assert(v.isComplexFloat() || v.isComplexInt());
286 if (v.isComplexFloat()) {
287 makeComplexFloat();
288 FloatReal = v.getComplexFloatReal();
289 FloatImag = v.getComplexFloatImag();
290 } else {
291 makeComplexInt();
292 IntReal = v.getComplexIntReal();
293 IntImag = v.getComplexIntImag();
294 }
295 }
John McCall93d91dc2010-05-07 17:22:02 +0000296 };
John McCall45d55e42010-05-07 21:00:08 +0000297
298 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000299 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000300 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000301 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000302 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000303
Richard Smith8b3497e2011-10-31 01:37:14 +0000304 const Expr *getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000305 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000306 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000307 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000308 SubobjectDesignator &getLValueDesignator() { return Designator; }
309 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000310
Richard Smith0b0a0b62011-10-29 20:57:55 +0000311 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000312 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000313 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000314 void setFrom(const CCValue &V) {
315 assert(V.isLValue());
316 Base = V.getLValueBase();
317 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000318 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000319 Designator = V.getLValueDesignator();
320 }
321
322 void setExpr(const Expr *E, CallStackFrame *F = 0) {
323 Base = E;
324 Offset = CharUnits::Zero();
325 Frame = F;
326 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000327 }
John McCall45d55e42010-05-07 21:00:08 +0000328 };
John McCall93d91dc2010-05-07 17:22:02 +0000329}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000330
Richard Smith0b0a0b62011-10-29 20:57:55 +0000331static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000332static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
333 const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000334static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
335static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000336static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000337static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000338 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000339static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000340static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000341
342//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000343// Misc utilities
344//===----------------------------------------------------------------------===//
345
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000346static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000347 if (!E) return true;
348
349 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
350 if (isa<FunctionDecl>(DRE->getDecl()))
351 return true;
352 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
353 return VD->hasGlobalStorage();
354 return false;
355 }
356
357 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
358 return CLE->isFileScope();
359
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000360 if (isa<MemberExpr>(E) || isa<MaterializeTemporaryExpr>(E))
Richard Smith11562c52011-10-28 17:51:58 +0000361 return false;
362
John McCall95007602010-05-10 23:27:23 +0000363 return true;
364}
365
Richard Smith80815602011-11-07 05:07:52 +0000366/// Check that this reference or pointer core constant expression is a valid
367/// value for a constant expression. Type T should be either LValue or CCValue.
368template<typename T>
369static bool CheckLValueConstantExpression(const T &LVal, APValue &Value) {
370 if (!IsGlobalLValue(LVal.getLValueBase()))
371 return false;
372
373 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
374 // A constant expression must refer to an object or be a null pointer.
375 if (Designator.Invalid || Designator.OnePastTheEnd ||
376 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
377 // FIXME: Check for out-of-bounds array indices.
378 // FIXME: This is not a constant expression.
379 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
380 APValue::NoLValuePath());
381 return true;
382 }
383
384 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
385 Designator.Entries);
386 return true;
387}
388
Richard Smith0b0a0b62011-10-29 20:57:55 +0000389/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000390/// constant expression, and if it is, produce the corresponding constant value.
391static bool CheckConstantExpression(const CCValue &CCValue, APValue &Value) {
Richard Smith80815602011-11-07 05:07:52 +0000392 if (!CCValue.isLValue()) {
393 Value = CCValue;
394 return true;
395 }
396 return CheckLValueConstantExpression(CCValue, Value);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000397}
398
Richard Smith83c68212011-10-31 05:11:32 +0000399const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
400 if (!LVal.Base)
401 return 0;
402
403 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVal.Base))
404 return DRE->getDecl();
405
406 // FIXME: Static data members accessed via a MemberExpr are represented as
407 // that MemberExpr. We should use the Decl directly instead.
408 if (const MemberExpr *ME = dyn_cast<MemberExpr>(LVal.Base)) {
409 assert(!isa<FieldDecl>(ME->getMemberDecl()) && "shouldn't see fields here");
410 return ME->getMemberDecl();
411 }
412
413 return 0;
414}
415
416static bool IsLiteralLValue(const LValue &Value) {
417 return Value.Base &&
418 !isa<DeclRefExpr>(Value.Base) &&
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000419 !isa<MemberExpr>(Value.Base) &&
420 !isa<MaterializeTemporaryExpr>(Value.Base);
Richard Smith83c68212011-10-31 05:11:32 +0000421}
422
Richard Smithcecf1842011-11-01 21:06:14 +0000423static bool IsWeakDecl(const ValueDecl *Decl) {
Richard Smith83c68212011-10-31 05:11:32 +0000424 return Decl->hasAttr<WeakAttr>() ||
425 Decl->hasAttr<WeakRefAttr>() ||
426 Decl->isWeakImported();
427}
428
Richard Smithcecf1842011-11-01 21:06:14 +0000429static bool IsWeakLValue(const LValue &Value) {
430 const ValueDecl *Decl = GetLValueBaseDecl(Value);
431 return Decl && IsWeakDecl(Decl);
432}
433
Richard Smith11562c52011-10-28 17:51:58 +0000434static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCall45d55e42010-05-07 21:00:08 +0000435 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000436
John McCalleb3e4f32010-05-07 21:34:32 +0000437 // A null base expression indicates a null pointer. These are always
438 // evaluatable, and they are false unless the offset is zero.
439 if (!Base) {
440 Result = !Value.Offset.isZero();
441 return true;
442 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000443
John McCall95007602010-05-10 23:27:23 +0000444 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000445 // FIXME: C++11 requires such conversions. Remove this check.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000446 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000447
John McCalleb3e4f32010-05-07 21:34:32 +0000448 // We have a non-null base expression. These are generally known to
449 // be true, but if it'a decl-ref to a weak symbol it can be null at
450 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000451 Result = true;
Richard Smith83c68212011-10-31 05:11:32 +0000452 return !IsWeakLValue(Value);
Eli Friedman334046a2009-06-14 02:17:33 +0000453}
454
Richard Smith0b0a0b62011-10-29 20:57:55 +0000455static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000456 switch (Val.getKind()) {
457 case APValue::Uninitialized:
458 return false;
459 case APValue::Int:
460 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000461 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000462 case APValue::Float:
463 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000464 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000465 case APValue::ComplexInt:
466 Result = Val.getComplexIntReal().getBoolValue() ||
467 Val.getComplexIntImag().getBoolValue();
468 return true;
469 case APValue::ComplexFloat:
470 Result = !Val.getComplexFloatReal().isZero() ||
471 !Val.getComplexFloatImag().isZero();
472 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000473 case APValue::LValue: {
474 LValue PointerResult;
475 PointerResult.setFrom(Val);
476 return EvalPointerValueAsBool(PointerResult, Result);
477 }
Richard Smith11562c52011-10-28 17:51:58 +0000478 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000479 case APValue::Array:
Richard Smith11562c52011-10-28 17:51:58 +0000480 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000481 }
482
Richard Smith11562c52011-10-28 17:51:58 +0000483 llvm_unreachable("unknown APValue kind");
484}
485
486static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
487 EvalInfo &Info) {
488 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000489 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000490 if (!Evaluate(Val, Info, E))
491 return false;
492 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000493}
494
Mike Stump11289f42009-09-09 15:08:12 +0000495static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000496 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000497 unsigned DestWidth = Ctx.getIntWidth(DestType);
498 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000499 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000500
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000501 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000502 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000503 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000504 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
505 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000506}
507
Mike Stump11289f42009-09-09 15:08:12 +0000508static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000509 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000510 bool ignored;
511 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000512 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000513 APFloat::rmNearestTiesToEven, &ignored);
514 return Result;
515}
516
Mike Stump11289f42009-09-09 15:08:12 +0000517static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000518 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000519 unsigned DestWidth = Ctx.getIntWidth(DestType);
520 APSInt Result = Value;
521 // Figure out if this is a truncate, extend or noop cast.
522 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000523 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000524 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000525 return Result;
526}
527
Mike Stump11289f42009-09-09 15:08:12 +0000528static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000529 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000530
531 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
532 Result.convertFromAPInt(Value, Value.isSigned(),
533 APFloat::rmNearestTiesToEven);
534 return Result;
535}
536
Richard Smith27908702011-10-24 17:54:18 +0000537/// Try to evaluate the initializer for a variable declaration.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000538static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +0000539 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000540 // If this is a parameter to an active constexpr function call, perform
541 // argument substitution.
542 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithfec09922011-11-01 16:57:24 +0000543 if (!Frame || !Frame->Arguments)
544 return false;
545 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
546 return true;
Richard Smith254a73d2011-10-28 22:34:42 +0000547 }
Richard Smith27908702011-10-24 17:54:18 +0000548
Richard Smithcecf1842011-11-01 21:06:14 +0000549 // Never evaluate the initializer of a weak variable. We can't be sure that
550 // this is the definition which will be used.
551 if (IsWeakDecl(VD))
552 return false;
553
Richard Smith27908702011-10-24 17:54:18 +0000554 const Expr *Init = VD->getAnyInitializer();
Richard Smithec8dcd22011-11-08 01:31:09 +0000555 if (!Init || Init->isValueDependent())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000556 return false;
Richard Smith27908702011-10-24 17:54:18 +0000557
Richard Smith0b0a0b62011-10-29 20:57:55 +0000558 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smithfec09922011-11-01 16:57:24 +0000559 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000560 return !Result.isUninit();
561 }
Richard Smith27908702011-10-24 17:54:18 +0000562
563 if (VD->isEvaluatingValue())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000564 return false;
Richard Smith27908702011-10-24 17:54:18 +0000565
566 VD->setEvaluatingValue();
567
Richard Smith0b0a0b62011-10-29 20:57:55 +0000568 Expr::EvalStatus EStatus;
569 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith11562c52011-10-28 17:51:58 +0000570 // FIXME: The caller will need to know whether the value was a constant
571 // expression. If not, we should propagate up a diagnostic.
Richard Smithed5165f2011-11-04 05:33:44 +0000572 APValue EvalResult;
573 if (!EvaluateConstantExpression(EvalResult, InitInfo, Init)) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000574 // FIXME: If the evaluation failure was not permanent (for instance, if we
575 // hit a variable with no declaration yet, or a constexpr function with no
576 // definition yet), the standard is unclear as to how we should behave.
577 //
578 // Either the initializer should be evaluated when the variable is defined,
579 // or a failed evaluation of the initializer should be reattempted each time
580 // it is used.
Richard Smith27908702011-10-24 17:54:18 +0000581 VD->setEvaluatedValue(APValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000582 return false;
583 }
Richard Smith27908702011-10-24 17:54:18 +0000584
Richard Smithed5165f2011-11-04 05:33:44 +0000585 VD->setEvaluatedValue(EvalResult);
586 Result = CCValue(EvalResult, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000587 return true;
Richard Smith27908702011-10-24 17:54:18 +0000588}
589
Richard Smith11562c52011-10-28 17:51:58 +0000590static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000591 Qualifiers Quals = T.getQualifiers();
592 return Quals.hasConst() && !Quals.hasVolatile();
593}
594
Richard Smithf3e9e432011-11-07 09:22:26 +0000595/// Extract the designated sub-object of an rvalue.
596static bool ExtractSubobject(EvalInfo &Info, CCValue &Obj, QualType ObjType,
597 const SubobjectDesignator &Sub, QualType SubType) {
598 if (Sub.Invalid || Sub.OnePastTheEnd)
599 return false;
600 if (Sub.Entries.empty()) {
601 assert(Info.Ctx.hasSameUnqualifiedType(ObjType, SubType) &&
602 "Unexpected subobject type");
603 return true;
604 }
605
606 assert(!Obj.isLValue() && "extracting subobject of lvalue");
607 const APValue *O = &Obj;
608 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
609 if (O->isUninit())
610 return false;
611 if (ObjType->isArrayType()) {
612 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
613 if (!CAT)
614 return false;
615 uint64_t Index = Sub.Entries[I].ArrayIndex;
616 if (CAT->getSize().ule(Index))
617 return false;
618 if (O->getArrayInitializedElts() > Index)
619 O = &O->getArrayInitializedElt(Index);
620 else
621 O = &O->getArrayFiller();
622 ObjType = CAT->getElementType();
623 } else {
624 // FIXME: Support handling of subobjects of structs and unions. Also
625 // for vector elements, if we want to support those?
626 }
627 }
628
629 assert(Info.Ctx.hasSameUnqualifiedType(ObjType, SubType) &&
630 "Unexpected subobject type");
631 Obj = CCValue(*O, CCValue::GlobalValue());
632 return true;
633}
634
635static bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
636 const LValue &LVal, CCValue &RVal) {
Richard Smith11562c52011-10-28 17:51:58 +0000637 const Expr *Base = LVal.Base;
Richard Smithfec09922011-11-01 16:57:24 +0000638 CallStackFrame *Frame = LVal.Frame;
Richard Smith11562c52011-10-28 17:51:58 +0000639
640 // FIXME: Indirection through a null pointer deserves a diagnostic.
641 if (!Base)
642 return false;
643
Richard Smith8b3497e2011-10-31 01:37:14 +0000644 if (const ValueDecl *D = GetLValueBaseDecl(LVal)) {
Richard Smith11562c52011-10-28 17:51:58 +0000645 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
646 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +0000647 // expressions are constant expressions too. Inside constexpr functions,
648 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +0000649 // In C, such things can also be folded, although they are not ICEs.
650 //
Richard Smith254a73d2011-10-28 22:34:42 +0000651 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
652 // interpretation of C++11 suggests that volatile parameters are OK if
653 // they're never read (there's no prohibition against constructing volatile
654 // objects in constant expressions), but lvalue-to-rvalue conversions on
655 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +0000656 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith96e0c102011-11-04 02:25:55 +0000657 QualType VT = VD->getType();
Richard Smitha08acd82011-11-07 03:22:51 +0000658 if (!VD || VD->isInvalidDecl())
Richard Smith96e0c102011-11-04 02:25:55 +0000659 return false;
660 if (!isa<ParmVarDecl>(VD)) {
661 if (!IsConstNonVolatile(VT))
662 return false;
Richard Smitha08acd82011-11-07 03:22:51 +0000663 // FIXME: Allow folding of values of any literal type in all languages.
664 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
665 !VD->isConstexpr())
Richard Smith96e0c102011-11-04 02:25:55 +0000666 return false;
667 }
668 if (!EvaluateVarDeclInit(Info, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +0000669 return false;
670
Richard Smith0b0a0b62011-10-29 20:57:55 +0000671 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf3e9e432011-11-07 09:22:26 +0000672 return ExtractSubobject(Info, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +0000673
674 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
675 // conversion. This happens when the declaration and the lvalue should be
676 // considered synonymous, for instance when initializing an array of char
677 // from a string literal. Continue as if the initializer lvalue was the
678 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +0000679 assert(RVal.getLValueOffset().isZero() &&
680 "offset for lvalue init of non-reference");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000681 Base = RVal.getLValueBase();
Richard Smithfec09922011-11-01 16:57:24 +0000682 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +0000683 }
684
Richard Smith96e0c102011-11-04 02:25:55 +0000685 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
686 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
687 const SubobjectDesignator &Designator = LVal.Designator;
688 if (Designator.Invalid || Designator.Entries.size() != 1)
689 return false;
690
691 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +0000692 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000693 if (Index > S->getLength())
694 return false;
695 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
696 Type->isUnsignedIntegerType());
697 if (Index < S->getLength())
698 Value = S->getCodeUnit(Index);
699 RVal = CCValue(Value);
700 return true;
701 }
702
Richard Smithf3e9e432011-11-07 09:22:26 +0000703 if (Frame) {
704 // If this is a temporary expression with a nontrivial initializer, grab the
705 // value from the relevant stack frame.
706 RVal = Frame->Temporaries[Base];
707 } else if (const CompoundLiteralExpr *CLE
708 = dyn_cast<CompoundLiteralExpr>(Base)) {
709 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
710 // initializer until now for such expressions. Such an expression can't be
711 // an ICE in C, so this only matters for fold.
712 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
713 if (!Evaluate(RVal, Info, CLE->getInitializer()))
714 return false;
715 } else
Richard Smith96e0c102011-11-04 02:25:55 +0000716 return false;
717
Richard Smithf3e9e432011-11-07 09:22:26 +0000718 return ExtractSubobject(Info, RVal, Base->getType(), LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +0000719}
720
Mike Stump876387b2009-10-27 22:09:17 +0000721namespace {
Richard Smith254a73d2011-10-28 22:34:42 +0000722enum EvalStmtResult {
723 /// Evaluation failed.
724 ESR_Failed,
725 /// Hit a 'return' statement.
726 ESR_Returned,
727 /// Evaluation succeeded.
728 ESR_Succeeded
729};
730}
731
732// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000733static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +0000734 const Stmt *S) {
735 switch (S->getStmtClass()) {
736 default:
737 return ESR_Failed;
738
739 case Stmt::NullStmtClass:
740 case Stmt::DeclStmtClass:
741 return ESR_Succeeded;
742
743 case Stmt::ReturnStmtClass:
744 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
745 return ESR_Returned;
746 return ESR_Failed;
747
748 case Stmt::CompoundStmtClass: {
749 const CompoundStmt *CS = cast<CompoundStmt>(S);
750 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
751 BE = CS->body_end(); BI != BE; ++BI) {
752 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
753 if (ESR != ESR_Succeeded)
754 return ESR;
755 }
756 return ESR_Succeeded;
757 }
758 }
759}
760
761/// Evaluate a function call.
762static bool HandleFunctionCall(ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000763 EvalInfo &Info, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000764 // FIXME: Implement a proper call limit, along with a command-line flag.
765 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
766 return false;
767
Richard Smith0b0a0b62011-10-29 20:57:55 +0000768 SmallVector<CCValue, 16> ArgValues(Args.size());
Richard Smith254a73d2011-10-28 22:34:42 +0000769 // FIXME: Deal with default arguments and 'this'.
770 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
771 I != E; ++I)
772 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
773 return false;
774
775 CallStackFrame Frame(Info, ArgValues.data());
776 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
777}
778
779namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000780class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000781 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000782 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000783public:
784
Richard Smith725810a2011-10-16 21:26:27 +0000785 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000786
787 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000788 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000789 return true;
790 }
791
Peter Collingbournee9200682011-05-13 03:29:01 +0000792 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
793 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000794 return Visit(E->getResultExpr());
795 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000796 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000797 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000798 return true;
799 return false;
800 }
John McCall31168b02011-06-15 23:02:42 +0000801 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000802 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000803 return true;
804 return false;
805 }
806 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000807 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000808 return true;
809 return false;
810 }
811
Mike Stump876387b2009-10-27 22:09:17 +0000812 // We don't want to evaluate BlockExprs multiple times, as they generate
813 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000814 bool VisitBlockExpr(const BlockExpr *E) { return true; }
815 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
816 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000817 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000818 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
819 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
820 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
821 bool VisitStringLiteral(const StringLiteral *E) { return false; }
822 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
823 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000824 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000825 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000826 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000827 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000828 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000829 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
830 bool VisitBinAssign(const BinaryOperator *E) { return true; }
831 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
832 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000833 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000834 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
835 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
836 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
837 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
838 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000839 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000840 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000841 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000842 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000843 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000844
845 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000846 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000847 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
848 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000849 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000850 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000851 return false;
852 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000853
Peter Collingbournee9200682011-05-13 03:29:01 +0000854 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000855};
856
John McCallc07a0c72011-02-17 10:25:35 +0000857class OpaqueValueEvaluation {
858 EvalInfo &info;
859 OpaqueValueExpr *opaqueValue;
860
861public:
862 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
863 Expr *value)
864 : info(info), opaqueValue(opaqueValue) {
865
866 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000867 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000868 this->opaqueValue = 0;
869 return;
870 }
John McCallc07a0c72011-02-17 10:25:35 +0000871 }
872
873 bool hasError() const { return opaqueValue == 0; }
874
875 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000876 // FIXME: This will not work for recursive constexpr functions using opaque
877 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000878 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
879 }
880};
881
Mike Stump876387b2009-10-27 22:09:17 +0000882} // end anonymous namespace
883
Eli Friedman9a156e52008-11-12 09:44:48 +0000884//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000885// Generic Evaluation
886//===----------------------------------------------------------------------===//
887namespace {
888
889template <class Derived, typename RetTy=void>
890class ExprEvaluatorBase
891 : public ConstStmtVisitor<Derived, RetTy> {
892private:
Richard Smith0b0a0b62011-10-29 20:57:55 +0000893 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000894 return static_cast<Derived*>(this)->Success(V, E);
895 }
896 RetTy DerivedError(const Expr *E) {
897 return static_cast<Derived*>(this)->Error(E);
898 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000899 RetTy DerivedValueInitialization(const Expr *E) {
900 return static_cast<Derived*>(this)->ValueInitialization(E);
901 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000902
903protected:
904 EvalInfo &Info;
905 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
906 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
907
Richard Smith4ce706a2011-10-11 21:43:33 +0000908 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
909
Richard Smithfec09922011-11-01 16:57:24 +0000910 bool MakeTemporary(const Expr *Key, const Expr *Value, LValue &Result) {
911 if (!Evaluate(Info.CurrentCall->Temporaries[Key], Info, Value))
912 return false;
Richard Smith96e0c102011-11-04 02:25:55 +0000913 Result.setExpr(Key, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +0000914 return true;
915 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000916public:
917 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
918
919 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000920 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000921 }
922 RetTy VisitExpr(const Expr *E) {
923 return DerivedError(E);
924 }
925
926 RetTy VisitParenExpr(const ParenExpr *E)
927 { return StmtVisitorTy::Visit(E->getSubExpr()); }
928 RetTy VisitUnaryExtension(const UnaryOperator *E)
929 { return StmtVisitorTy::Visit(E->getSubExpr()); }
930 RetTy VisitUnaryPlus(const UnaryOperator *E)
931 { return StmtVisitorTy::Visit(E->getSubExpr()); }
932 RetTy VisitChooseExpr(const ChooseExpr *E)
933 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
934 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
935 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000936 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
937 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +0000938 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
939 { return StmtVisitorTy::Visit(E->getExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000940
941 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
942 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
943 if (opaque.hasError())
944 return DerivedError(E);
945
946 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +0000947 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000948 return DerivedError(E);
949
950 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
951 }
952
953 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
954 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +0000955 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000956 return DerivedError(E);
957
Richard Smith11562c52011-10-28 17:51:58 +0000958 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +0000959 return StmtVisitorTy::Visit(EvalExpr);
960 }
961
962 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000963 const CCValue *Value = Info.getOpaqueValue(E);
964 if (!Value)
Peter Collingbournee9200682011-05-13 03:29:01 +0000965 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
966 : DerivedError(E));
Richard Smith0b0a0b62011-10-29 20:57:55 +0000967 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000968 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000969
Richard Smith254a73d2011-10-28 22:34:42 +0000970 RetTy VisitCallExpr(const CallExpr *E) {
971 const Expr *Callee = E->getCallee();
972 QualType CalleeType = Callee->getType();
973
974 // FIXME: Handle the case where Callee is a (parenthesized) MemberExpr for a
975 // non-static member function.
976 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember))
977 return DerivedError(E);
978
979 if (!CalleeType->isFunctionType() && !CalleeType->isFunctionPointerType())
980 return DerivedError(E);
981
Richard Smith0b0a0b62011-10-29 20:57:55 +0000982 CCValue Call;
Richard Smith254a73d2011-10-28 22:34:42 +0000983 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
984 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
985 return DerivedError(Callee);
986
987 const FunctionDecl *FD = 0;
988 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Call.getLValueBase()))
989 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
990 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Call.getLValueBase()))
991 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
992 if (!FD)
993 return DerivedError(Callee);
994
995 // Don't call function pointers which have been cast to some other type.
996 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
997 return DerivedError(E);
998
999 const FunctionDecl *Definition;
1000 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00001001 CCValue CCResult;
1002 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00001003 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
1004
1005 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
Richard Smithed5165f2011-11-04 05:33:44 +00001006 HandleFunctionCall(Args, Body, Info, CCResult) &&
1007 CheckConstantExpression(CCResult, Result))
1008 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00001009
1010 return DerivedError(E);
1011 }
1012
Richard Smith11562c52011-10-28 17:51:58 +00001013 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1014 return StmtVisitorTy::Visit(E->getInitializer());
1015 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001016 RetTy VisitInitListExpr(const InitListExpr *E) {
1017 if (Info.getLangOpts().CPlusPlus0x) {
1018 if (E->getNumInits() == 0)
1019 return DerivedValueInitialization(E);
1020 if (E->getNumInits() == 1)
1021 return StmtVisitorTy::Visit(E->getInit(0));
1022 }
1023 return DerivedError(E);
1024 }
1025 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1026 return DerivedValueInitialization(E);
1027 }
1028 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1029 return DerivedValueInitialization(E);
1030 }
1031
Richard Smith11562c52011-10-28 17:51:58 +00001032 RetTy VisitCastExpr(const CastExpr *E) {
1033 switch (E->getCastKind()) {
1034 default:
1035 break;
1036
1037 case CK_NoOp:
1038 return StmtVisitorTy::Visit(E->getSubExpr());
1039
1040 case CK_LValueToRValue: {
1041 LValue LVal;
1042 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001043 CCValue RVal;
Richard Smith11562c52011-10-28 17:51:58 +00001044 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
1045 return DerivedSuccess(RVal, E);
1046 }
1047 break;
1048 }
1049 }
1050
1051 return DerivedError(E);
1052 }
1053
Richard Smith4a678122011-10-24 18:44:57 +00001054 /// Visit a value which is evaluated, but whose value is ignored.
1055 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001056 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00001057 if (!Evaluate(Scratch, Info, E))
1058 Info.EvalStatus.HasSideEffects = true;
1059 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001060};
1061
1062}
1063
1064//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001065// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001066//
1067// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
1068// function designators (in C), decl references to void objects (in C), and
1069// temporaries (if building with -Wno-address-of-temporary).
1070//
1071// LValue evaluation produces values comprising a base expression of one of the
1072// following types:
1073// * DeclRefExpr
1074// * MemberExpr for a static member
1075// * CompoundLiteralExpr in C
1076// * StringLiteral
1077// * PredefinedExpr
1078// * ObjCEncodeExpr
1079// * AddrLabelExpr
1080// * BlockExpr
1081// * CallExpr for a MakeStringConstant builtin
Richard Smithfec09922011-11-01 16:57:24 +00001082// plus an offset in bytes. It can also produce lvalues referring to locals. In
1083// that case, the Frame will point to a stack frame, and the Expr is used as a
1084// key to find the relevant temporary's value.
Eli Friedman9a156e52008-11-12 09:44:48 +00001085//===----------------------------------------------------------------------===//
1086namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001087class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001088 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001089 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +00001090 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +00001091
Peter Collingbournee9200682011-05-13 03:29:01 +00001092 bool Success(const Expr *E) {
Richard Smith96e0c102011-11-04 02:25:55 +00001093 Result.setExpr(E);
John McCall45d55e42010-05-07 21:00:08 +00001094 return true;
1095 }
Eli Friedman9a156e52008-11-12 09:44:48 +00001096public:
Mike Stump11289f42009-09-09 15:08:12 +00001097
John McCall45d55e42010-05-07 21:00:08 +00001098 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +00001099 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +00001100
Richard Smith0b0a0b62011-10-29 20:57:55 +00001101 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001102 Result.setFrom(V);
1103 return true;
1104 }
1105 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00001106 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001107 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001108
Richard Smith11562c52011-10-28 17:51:58 +00001109 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
1110
Peter Collingbournee9200682011-05-13 03:29:01 +00001111 bool VisitDeclRefExpr(const DeclRefExpr *E);
1112 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001113 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001114 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1115 bool VisitMemberExpr(const MemberExpr *E);
1116 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
1117 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
1118 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
1119 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001120
Peter Collingbournee9200682011-05-13 03:29:01 +00001121 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00001122 switch (E->getCastKind()) {
1123 default:
Richard Smith11562c52011-10-28 17:51:58 +00001124 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001125
Eli Friedmance3e02a2011-10-11 00:13:24 +00001126 case CK_LValueBitCast:
Richard Smith96e0c102011-11-04 02:25:55 +00001127 if (!Visit(E->getSubExpr()))
1128 return false;
1129 Result.Designator.setInvalid();
1130 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00001131
Richard Smith11562c52011-10-28 17:51:58 +00001132 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
1133 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlssonde55f642009-10-03 16:30:22 +00001134 }
1135 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00001136
Eli Friedman449fe542009-03-23 04:56:01 +00001137 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00001138
Eli Friedman9a156e52008-11-12 09:44:48 +00001139};
1140} // end anonymous namespace
1141
Richard Smith11562c52011-10-28 17:51:58 +00001142/// Evaluate an expression as an lvalue. This can be legitimately called on
1143/// expressions which are not glvalues, in a few cases:
1144/// * function designators in C,
1145/// * "extern void" objects,
1146/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00001147static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001148 assert((E->isGLValue() || E->getType()->isFunctionType() ||
1149 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
1150 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00001151 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001152}
1153
Peter Collingbournee9200682011-05-13 03:29:01 +00001154bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001155 if (isa<FunctionDecl>(E->getDecl()))
John McCall45d55e42010-05-07 21:00:08 +00001156 return Success(E);
Richard Smith11562c52011-10-28 17:51:58 +00001157 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
1158 return VisitVarDecl(E, VD);
1159 return Error(E);
1160}
Richard Smith733237d2011-10-24 23:14:33 +00001161
Richard Smith11562c52011-10-28 17:51:58 +00001162bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00001163 if (!VD->getType()->isReferenceType()) {
1164 if (isa<ParmVarDecl>(VD)) {
Richard Smith96e0c102011-11-04 02:25:55 +00001165 Result.setExpr(E, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00001166 return true;
1167 }
Richard Smith11562c52011-10-28 17:51:58 +00001168 return Success(E);
Richard Smithfec09922011-11-01 16:57:24 +00001169 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00001170
Richard Smith0b0a0b62011-10-29 20:57:55 +00001171 CCValue V;
Richard Smithfec09922011-11-01 16:57:24 +00001172 if (EvaluateVarDeclInit(Info, VD, Info.CurrentCall, V))
Richard Smith0b0a0b62011-10-29 20:57:55 +00001173 return Success(V, E);
Richard Smith11562c52011-10-28 17:51:58 +00001174
1175 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +00001176}
1177
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001178bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
1179 const MaterializeTemporaryExpr *E) {
Richard Smithfec09922011-11-01 16:57:24 +00001180 return MakeTemporary(E, E->GetTemporaryExpr(), Result);
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001181}
1182
Peter Collingbournee9200682011-05-13 03:29:01 +00001183bool
1184LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001185 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1186 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
1187 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00001188 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001189}
1190
Peter Collingbournee9200682011-05-13 03:29:01 +00001191bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001192 // Handle static data members.
1193 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
1194 VisitIgnoredValue(E->getBase());
1195 return VisitVarDecl(E, VD);
1196 }
1197
Richard Smith254a73d2011-10-28 22:34:42 +00001198 // Handle static member functions.
1199 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
1200 if (MD->isStatic()) {
1201 VisitIgnoredValue(E->getBase());
1202 return Success(E);
1203 }
1204 }
1205
Eli Friedman9a156e52008-11-12 09:44:48 +00001206 QualType Ty;
1207 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +00001208 if (!EvaluatePointer(E->getBase(), Result, Info))
1209 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001210 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +00001211 } else {
John McCall45d55e42010-05-07 21:00:08 +00001212 if (!Visit(E->getBase()))
1213 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001214 Ty = E->getBase()->getType();
1215 }
1216
Peter Collingbournee9200682011-05-13 03:29:01 +00001217 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +00001218 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001219
Peter Collingbournee9200682011-05-13 03:29:01 +00001220 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001221 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +00001222 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001223
1224 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +00001225 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001226
Eli Friedmana3c122d2011-07-07 01:54:01 +00001227 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001228 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Richard Smith96e0c102011-11-04 02:25:55 +00001229 Result.Designator.addDecl(FD);
John McCall45d55e42010-05-07 21:00:08 +00001230 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +00001231}
1232
Peter Collingbournee9200682011-05-13 03:29:01 +00001233bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001234 // FIXME: Deal with vectors as array subscript bases.
1235 if (E->getBase()->getType()->isVectorType())
1236 return false;
1237
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001238 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00001239 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001240
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001241 APSInt Index;
1242 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00001243 return false;
Richard Smith96e0c102011-11-04 02:25:55 +00001244 uint64_t IndexValue
1245 = Index.isSigned() ? static_cast<uint64_t>(Index.getSExtValue())
1246 : Index.getZExtValue();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001247
Ken Dyck40775002010-01-11 17:06:35 +00001248 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
Richard Smith96e0c102011-11-04 02:25:55 +00001249 Result.Offset += IndexValue * ElementSize;
1250 Result.Designator.adjustIndex(IndexValue);
John McCall45d55e42010-05-07 21:00:08 +00001251 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001252}
Eli Friedman9a156e52008-11-12 09:44:48 +00001253
Peter Collingbournee9200682011-05-13 03:29:01 +00001254bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00001255 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00001256}
1257
Eli Friedman9a156e52008-11-12 09:44:48 +00001258//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001259// Pointer Evaluation
1260//===----------------------------------------------------------------------===//
1261
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001262namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001263class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001264 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001265 LValue &Result;
1266
Peter Collingbournee9200682011-05-13 03:29:01 +00001267 bool Success(const Expr *E) {
Richard Smith96e0c102011-11-04 02:25:55 +00001268 Result.setExpr(E);
John McCall45d55e42010-05-07 21:00:08 +00001269 return true;
1270 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001271public:
Mike Stump11289f42009-09-09 15:08:12 +00001272
John McCall45d55e42010-05-07 21:00:08 +00001273 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001274 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001275
Richard Smith0b0a0b62011-10-29 20:57:55 +00001276 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001277 Result.setFrom(V);
1278 return true;
1279 }
1280 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +00001281 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001282 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001283 bool ValueInitialization(const Expr *E) {
1284 return Success((Expr*)0);
1285 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001286
John McCall45d55e42010-05-07 21:00:08 +00001287 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001288 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00001289 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001290 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00001291 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001292 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00001293 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001294 bool VisitCallExpr(const CallExpr *E);
1295 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00001296 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00001297 return Success(E);
1298 return false;
Mike Stumpa6703322009-02-19 22:01:56 +00001299 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001300 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +00001301 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +00001302
Eli Friedman449fe542009-03-23 04:56:01 +00001303 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001304};
Chris Lattner05706e882008-07-11 18:11:29 +00001305} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001306
John McCall45d55e42010-05-07 21:00:08 +00001307static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001308 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00001309 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00001310}
1311
John McCall45d55e42010-05-07 21:00:08 +00001312bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001313 if (E->getOpcode() != BO_Add &&
1314 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +00001315 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001316
Chris Lattner05706e882008-07-11 18:11:29 +00001317 const Expr *PExp = E->getLHS();
1318 const Expr *IExp = E->getRHS();
1319 if (IExp->getType()->isPointerType())
1320 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00001321
John McCall45d55e42010-05-07 21:00:08 +00001322 if (!EvaluatePointer(PExp, Result, Info))
1323 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001324
John McCall45d55e42010-05-07 21:00:08 +00001325 llvm::APSInt Offset;
1326 if (!EvaluateInteger(IExp, Offset, Info))
1327 return false;
1328 int64_t AdditionalOffset
1329 = Offset.isSigned() ? Offset.getSExtValue()
1330 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00001331 if (E->getOpcode() == BO_Sub)
1332 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00001333
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001334 // Compute the new offset in the appropriate width.
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001335 QualType PointeeType =
1336 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +00001337 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +00001338
Anders Carlssonef56fba2009-02-19 04:55:58 +00001339 // Explicitly handle GNU void* and function pointer arithmetic extensions.
1340 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +00001341 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +00001342 else
John McCall45d55e42010-05-07 21:00:08 +00001343 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +00001344
Richard Smith96e0c102011-11-04 02:25:55 +00001345 Result.Offset += AdditionalOffset * SizeOfPointee;
1346 Result.Designator.adjustIndex(AdditionalOffset);
John McCall45d55e42010-05-07 21:00:08 +00001347 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001348}
Eli Friedman9a156e52008-11-12 09:44:48 +00001349
John McCall45d55e42010-05-07 21:00:08 +00001350bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1351 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001352}
Mike Stump11289f42009-09-09 15:08:12 +00001353
Chris Lattner05706e882008-07-11 18:11:29 +00001354
Peter Collingbournee9200682011-05-13 03:29:01 +00001355bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1356 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00001357
Eli Friedman847a2bc2009-12-27 05:43:15 +00001358 switch (E->getCastKind()) {
1359 default:
1360 break;
1361
John McCalle3027922010-08-25 11:45:40 +00001362 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00001363 case CK_CPointerToObjCPointerCast:
1364 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001365 case CK_AnyPointerToBlockPointerCast:
Richard Smith96e0c102011-11-04 02:25:55 +00001366 if (!Visit(SubExpr))
1367 return false;
1368 Result.Designator.setInvalid();
1369 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00001370
Anders Carlsson18275092010-10-31 20:41:46 +00001371 case CK_DerivedToBase:
1372 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001373 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00001374 return false;
1375
1376 // Now figure out the necessary offset to add to the baseLV to get from
1377 // the derived class to the base class.
Anders Carlsson18275092010-10-31 20:41:46 +00001378 QualType Ty = E->getSubExpr()->getType();
1379 const CXXRecordDecl *DerivedDecl =
1380 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
1381
1382 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1383 PathE = E->path_end(); PathI != PathE; ++PathI) {
1384 const CXXBaseSpecifier *Base = *PathI;
1385
1386 // FIXME: If the base is virtual, we'd need to determine the type of the
1387 // most derived class and we don't support that right now.
1388 if (Base->isVirtual())
1389 return false;
1390
1391 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1392 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1393
Richard Smith0b0a0b62011-10-29 20:57:55 +00001394 Result.getLValueOffset() += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +00001395 DerivedDecl = BaseDecl;
1396 }
1397
Richard Smith96e0c102011-11-04 02:25:55 +00001398 // FIXME
1399 Result.Designator.setInvalid();
1400
Anders Carlsson18275092010-10-31 20:41:46 +00001401 return true;
1402 }
1403
Richard Smith0b0a0b62011-10-29 20:57:55 +00001404 case CK_NullToPointer:
1405 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00001406
John McCalle3027922010-08-25 11:45:40 +00001407 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001408 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00001409 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00001410 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00001411
John McCall45d55e42010-05-07 21:00:08 +00001412 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001413 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1414 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
John McCall45d55e42010-05-07 21:00:08 +00001415 Result.Base = 0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001416 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00001417 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00001418 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00001419 return true;
1420 } else {
1421 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001422 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00001423 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001424 }
1425 }
John McCalle3027922010-08-25 11:45:40 +00001426 case CK_ArrayToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00001427 // FIXME: Support array-to-pointer decay on array rvalues.
1428 if (!SubExpr->isGLValue())
1429 return Error(E);
Richard Smith96e0c102011-11-04 02:25:55 +00001430 if (!EvaluateLValue(SubExpr, Result, Info))
1431 return false;
1432 // The result is a pointer to the first element of the array.
1433 Result.Designator.addIndex(0);
1434 return true;
Richard Smithdd785442011-10-31 20:57:44 +00001435
John McCalle3027922010-08-25 11:45:40 +00001436 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00001437 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001438 }
1439
Richard Smith11562c52011-10-28 17:51:58 +00001440 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00001441}
Chris Lattner05706e882008-07-11 18:11:29 +00001442
Peter Collingbournee9200682011-05-13 03:29:01 +00001443bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +00001444 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +00001445 Builtin::BI__builtin___CFStringMakeConstantString ||
1446 E->isBuiltinCall(Info.Ctx) ==
1447 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +00001448 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00001449
Peter Collingbournee9200682011-05-13 03:29:01 +00001450 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001451}
Chris Lattner05706e882008-07-11 18:11:29 +00001452
1453//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001454// Vector Evaluation
1455//===----------------------------------------------------------------------===//
1456
1457namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001458 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00001459 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1460 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001461 public:
Mike Stump11289f42009-09-09 15:08:12 +00001462
Richard Smith2d406342011-10-22 21:10:00 +00001463 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1464 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001465
Richard Smith2d406342011-10-22 21:10:00 +00001466 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1467 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1468 // FIXME: remove this APValue copy.
1469 Result = APValue(V.data(), V.size());
1470 return true;
1471 }
Richard Smithed5165f2011-11-04 05:33:44 +00001472 bool Success(const CCValue &V, const Expr *E) {
1473 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00001474 Result = V;
1475 return true;
1476 }
1477 bool Error(const Expr *E) { return false; }
1478 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00001479
Richard Smith2d406342011-10-22 21:10:00 +00001480 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00001481 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00001482 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00001483 bool VisitInitListExpr(const InitListExpr *E);
1484 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001485 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001486 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00001487 // shufflevector, ExtVectorElementExpr
1488 // (Note that these require implementing conversions
1489 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001490 };
1491} // end anonymous namespace
1492
1493static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001494 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00001495 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001496}
1497
Richard Smith2d406342011-10-22 21:10:00 +00001498bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1499 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001500 QualType EltTy = VTy->getElementType();
1501 unsigned NElts = VTy->getNumElements();
1502 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +00001503
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001504 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00001505 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001506
Eli Friedmanc757de22011-03-25 00:43:55 +00001507 switch (E->getCastKind()) {
1508 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00001509 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00001510 if (SETy->isIntegerType()) {
1511 APSInt IntResult;
1512 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001513 return Error(E);
1514 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00001515 } else if (SETy->isRealFloatingType()) {
1516 APFloat F(0.0);
1517 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001518 return Error(E);
1519 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00001520 } else {
Richard Smith2d406342011-10-22 21:10:00 +00001521 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001522 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001523
1524 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00001525 SmallVector<APValue, 4> Elts(NElts, Val);
1526 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00001527 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001528 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +00001529 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +00001530 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +00001531 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001532
Eli Friedmanc757de22011-03-25 00:43:55 +00001533 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +00001534 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +00001535
Eli Friedmanc757de22011-03-25 00:43:55 +00001536 APSInt Init;
1537 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001538 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001539
Eli Friedmanc757de22011-03-25 00:43:55 +00001540 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1541 "Vectors must be composed of ints or floats");
1542
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001543 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +00001544 for (unsigned i = 0; i != NElts; ++i) {
1545 APSInt Tmp = Init.extOrTrunc(EltWidth);
1546
1547 if (EltTy->isIntegerType())
1548 Elts.push_back(APValue(Tmp));
1549 else
1550 Elts.push_back(APValue(APFloat(Tmp)));
1551
1552 Init >>= EltWidth;
1553 }
Richard Smith2d406342011-10-22 21:10:00 +00001554 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001555 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001556 default:
Richard Smith11562c52011-10-28 17:51:58 +00001557 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001558 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001559}
1560
Richard Smith2d406342011-10-22 21:10:00 +00001561bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001562VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00001563 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001564 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00001565 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00001566
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001567 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001568 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001569
John McCall875679e2010-06-11 17:54:15 +00001570 // If a vector is initialized with a single element, that value
1571 // becomes every element of the vector, not just the first.
1572 // This is the behavior described in the IBM AltiVec documentation.
1573 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00001574
1575 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00001576 // vector (OpenCL 6.1.6).
1577 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00001578 return Visit(E->getInit(0));
1579
John McCall875679e2010-06-11 17:54:15 +00001580 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001581 if (EltTy->isIntegerType()) {
1582 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00001583 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001584 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001585 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001586 } else {
1587 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00001588 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001589 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001590 InitValue = APValue(f);
1591 }
1592 for (unsigned i = 0; i < NumElements; i++) {
1593 Elements.push_back(InitValue);
1594 }
1595 } else {
1596 for (unsigned i = 0; i < NumElements; i++) {
1597 if (EltTy->isIntegerType()) {
1598 llvm::APSInt sInt(32);
1599 if (i < NumInits) {
1600 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001601 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001602 } else {
1603 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1604 }
1605 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00001606 } else {
John McCall875679e2010-06-11 17:54:15 +00001607 llvm::APFloat f(0.0);
1608 if (i < NumInits) {
1609 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001610 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001611 } else {
1612 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1613 }
1614 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00001615 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001616 }
1617 }
Richard Smith2d406342011-10-22 21:10:00 +00001618 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001619}
1620
Richard Smith2d406342011-10-22 21:10:00 +00001621bool
1622VectorExprEvaluator::ValueInitialization(const Expr *E) {
1623 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00001624 QualType EltTy = VT->getElementType();
1625 APValue ZeroElement;
1626 if (EltTy->isIntegerType())
1627 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1628 else
1629 ZeroElement =
1630 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1631
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001632 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00001633 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001634}
1635
Richard Smith2d406342011-10-22 21:10:00 +00001636bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00001637 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00001638 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001639}
1640
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001641//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00001642// Array Evaluation
1643//===----------------------------------------------------------------------===//
1644
1645namespace {
1646 class ArrayExprEvaluator
1647 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
1648 APValue &Result;
1649 public:
1650
1651 ArrayExprEvaluator(EvalInfo &Info, APValue &Result)
1652 : ExprEvaluatorBaseTy(Info), Result(Result) {}
1653
1654 bool Success(const APValue &V, const Expr *E) {
1655 assert(V.isArray() && "Expected array type");
1656 Result = V;
1657 return true;
1658 }
1659 bool Error(const Expr *E) { return false; }
1660
1661 bool VisitInitListExpr(const InitListExpr *E);
1662 };
1663} // end anonymous namespace
1664
1665static bool EvaluateArray(const Expr* E, APValue& Result, EvalInfo &Info) {
1666 assert(E->isRValue() && E->getType()->isArrayType() &&
1667 E->getType()->isLiteralType() && "not a literal array rvalue");
1668 return ArrayExprEvaluator(Info, Result).Visit(E);
1669}
1670
1671bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
1672 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
1673 if (!CAT)
1674 return false;
1675
1676 Result = APValue(APValue::UninitArray(), E->getNumInits(),
1677 CAT->getSize().getZExtValue());
1678 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
1679 I != End; ++I)
1680 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(I-E->begin()),
1681 Info, cast<Expr>(*I)))
1682 return false;
1683
1684 if (!Result.hasArrayFiller()) return true;
1685 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
1686 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
1687 E->getArrayFiller());
1688}
1689
1690//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001691// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001692//
1693// As a GNU extension, we support casting pointers to sufficiently-wide integer
1694// types and back in constant folding. Integer values are thus represented
1695// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00001696//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001697
1698namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001699class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001700 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001701 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001702public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001703 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001704 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001705
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001706 bool Success(const llvm::APSInt &SI, const Expr *E) {
1707 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001708 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001709 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001710 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001711 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001712 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001713 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001714 return true;
1715 }
1716
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001717 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001718 assert(E->getType()->isIntegralOrEnumerationType() &&
1719 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001720 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001721 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001722 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001723 Result.getInt().setIsUnsigned(
1724 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001725 return true;
1726 }
1727
1728 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001729 assert(E->getType()->isIntegralOrEnumerationType() &&
1730 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001731 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001732 return true;
1733 }
1734
Ken Dyckdbc01912011-03-11 02:13:43 +00001735 bool Success(CharUnits Size, const Expr *E) {
1736 return Success(Size.getQuantity(), E);
1737 }
1738
1739
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001740 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001741 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001742 if (Info.EvalStatus.Diag == 0) {
1743 Info.EvalStatus.DiagLoc = L;
1744 Info.EvalStatus.Diag = D;
1745 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001746 }
Chris Lattner99415702008-07-12 00:14:42 +00001747 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001748 }
Mike Stump11289f42009-09-09 15:08:12 +00001749
Richard Smith0b0a0b62011-10-29 20:57:55 +00001750 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00001751 if (V.isLValue()) {
1752 Result = V;
1753 return true;
1754 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001755 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001756 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001757 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001758 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001759 }
Mike Stump11289f42009-09-09 15:08:12 +00001760
Richard Smith4ce706a2011-10-11 21:43:33 +00001761 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1762
Peter Collingbournee9200682011-05-13 03:29:01 +00001763 //===--------------------------------------------------------------------===//
1764 // Visitor Methods
1765 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001766
Chris Lattner7174bf32008-07-12 00:38:25 +00001767 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001768 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001769 }
1770 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001771 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001772 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001773
1774 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1775 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001776 if (CheckReferencedDecl(E, E->getDecl()))
1777 return true;
1778
1779 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001780 }
1781 bool VisitMemberExpr(const MemberExpr *E) {
1782 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00001783 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001784 return true;
1785 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001786
1787 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001788 }
1789
Peter Collingbournee9200682011-05-13 03:29:01 +00001790 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001791 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001792 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001793 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001794
Peter Collingbournee9200682011-05-13 03:29:01 +00001795 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001796 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001797
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001798 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001799 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001800 }
Mike Stump11289f42009-09-09 15:08:12 +00001801
Richard Smith4ce706a2011-10-11 21:43:33 +00001802 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001803 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001804 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001805 }
1806
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001807 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001808 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001809 }
1810
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001811 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1812 return Success(E->getValue(), E);
1813 }
1814
John Wiegley6242b6a2011-04-28 00:16:57 +00001815 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1816 return Success(E->getValue(), E);
1817 }
1818
John Wiegleyf9f65842011-04-25 06:54:41 +00001819 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1820 return Success(E->getValue(), E);
1821 }
1822
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001823 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001824 bool VisitUnaryImag(const UnaryOperator *E);
1825
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001826 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001827 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001828
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001829private:
Ken Dyck160146e2010-01-27 17:10:57 +00001830 CharUnits GetAlignOfExpr(const Expr *E);
1831 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001832 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001833 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001834 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001835};
Chris Lattner05706e882008-07-11 18:11:29 +00001836} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001837
Richard Smith11562c52011-10-28 17:51:58 +00001838/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1839/// produce either the integer value or a pointer.
1840///
1841/// GCC has a heinous extension which folds casts between pointer types and
1842/// pointer-sized integral types. We support this by allowing the evaluation of
1843/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1844/// Some simple arithmetic on such values is supported (they are treated much
1845/// like char*).
Richard Smith0b0a0b62011-10-29 20:57:55 +00001846static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
1847 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001848 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001849 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001850}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001851
Daniel Dunbarce399542009-02-20 18:22:23 +00001852static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001853 CCValue Val;
Daniel Dunbarce399542009-02-20 18:22:23 +00001854 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1855 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001856 Result = Val.getInt();
1857 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001858}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001859
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001860bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001861 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001862 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001863 // Check for signedness/width mismatches between E type and ECD value.
1864 bool SameSign = (ECD->getInitVal().isSigned()
1865 == E->getType()->isSignedIntegerOrEnumerationType());
1866 bool SameWidth = (ECD->getInitVal().getBitWidth()
1867 == Info.Ctx.getIntWidth(E->getType()));
1868 if (SameSign && SameWidth)
1869 return Success(ECD->getInitVal(), E);
1870 else {
1871 // Get rid of mismatch (otherwise Success assertions will fail)
1872 // by computing a new value matching the type of E.
1873 llvm::APSInt Val = ECD->getInitVal();
1874 if (!SameSign)
1875 Val.setIsSigned(!ECD->getInitVal().isSigned());
1876 if (!SameWidth)
1877 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1878 return Success(Val, E);
1879 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001880 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001881 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001882}
1883
Chris Lattner86ee2862008-10-06 06:40:35 +00001884/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1885/// as GCC.
1886static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1887 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001888 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001889 enum gcc_type_class {
1890 no_type_class = -1,
1891 void_type_class, integer_type_class, char_type_class,
1892 enumeral_type_class, boolean_type_class,
1893 pointer_type_class, reference_type_class, offset_type_class,
1894 real_type_class, complex_type_class,
1895 function_type_class, method_type_class,
1896 record_type_class, union_type_class,
1897 array_type_class, string_type_class,
1898 lang_type_class
1899 };
Mike Stump11289f42009-09-09 15:08:12 +00001900
1901 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001902 // ideal, however it is what gcc does.
1903 if (E->getNumArgs() == 0)
1904 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001905
Chris Lattner86ee2862008-10-06 06:40:35 +00001906 QualType ArgTy = E->getArg(0)->getType();
1907 if (ArgTy->isVoidType())
1908 return void_type_class;
1909 else if (ArgTy->isEnumeralType())
1910 return enumeral_type_class;
1911 else if (ArgTy->isBooleanType())
1912 return boolean_type_class;
1913 else if (ArgTy->isCharType())
1914 return string_type_class; // gcc doesn't appear to use char_type_class
1915 else if (ArgTy->isIntegerType())
1916 return integer_type_class;
1917 else if (ArgTy->isPointerType())
1918 return pointer_type_class;
1919 else if (ArgTy->isReferenceType())
1920 return reference_type_class;
1921 else if (ArgTy->isRealType())
1922 return real_type_class;
1923 else if (ArgTy->isComplexType())
1924 return complex_type_class;
1925 else if (ArgTy->isFunctionType())
1926 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001927 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001928 return record_type_class;
1929 else if (ArgTy->isUnionType())
1930 return union_type_class;
1931 else if (ArgTy->isArrayType())
1932 return array_type_class;
1933 else if (ArgTy->isUnionType())
1934 return union_type_class;
1935 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001936 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001937 return -1;
1938}
1939
John McCall95007602010-05-10 23:27:23 +00001940/// Retrieves the "underlying object type" of the given expression,
1941/// as used by __builtin_object_size.
1942QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1943 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1944 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1945 return VD->getType();
1946 } else if (isa<CompoundLiteralExpr>(E)) {
1947 return E->getType();
1948 }
1949
1950 return QualType();
1951}
1952
Peter Collingbournee9200682011-05-13 03:29:01 +00001953bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001954 // TODO: Perhaps we should let LLVM lower this?
1955 LValue Base;
1956 if (!EvaluatePointer(E->getArg(0), Base, Info))
1957 return false;
1958
1959 // If we can prove the base is null, lower to zero now.
1960 const Expr *LVBase = Base.getLValueBase();
1961 if (!LVBase) return Success(0, E);
1962
1963 QualType T = GetObjectType(LVBase);
1964 if (T.isNull() ||
1965 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001966 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001967 T->isVariablyModifiedType() ||
1968 T->isDependentType())
1969 return false;
1970
1971 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1972 CharUnits Offset = Base.getLValueOffset();
1973
1974 if (!Offset.isNegative() && Offset <= Size)
1975 Size -= Offset;
1976 else
1977 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001978 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001979}
1980
Peter Collingbournee9200682011-05-13 03:29:01 +00001981bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001982 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001983 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001984 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001985
1986 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001987 if (TryEvaluateBuiltinObjectSize(E))
1988 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001989
Eric Christopher99469702010-01-19 22:58:35 +00001990 // If evaluating the argument has side-effects we can't determine
1991 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001992 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001993 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001994 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001995 return Success(0, E);
1996 }
Mike Stump876387b2009-10-27 22:09:17 +00001997
Mike Stump722cedf2009-10-26 18:35:08 +00001998 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1999 }
2000
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002001 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002002 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00002003
Anders Carlsson4c76e932008-11-24 04:21:33 +00002004 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002005 // __builtin_constant_p always has one operand: it returns true if that
2006 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002007 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00002008
2009 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00002010 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00002011 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00002012 return Success(Operand, E);
2013 }
Eli Friedmand5c93992010-02-13 00:10:10 +00002014
2015 case Builtin::BI__builtin_expect:
2016 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00002017
2018 case Builtin::BIstrlen:
2019 case Builtin::BI__builtin_strlen:
2020 // As an extension, we support strlen() and __builtin_strlen() as constant
2021 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00002022 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00002023 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
2024 // The string literal may have embedded null characters. Find the first
2025 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002026 StringRef Str = S->getString();
2027 StringRef::size_type Pos = Str.find(0);
2028 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00002029 Str = Str.substr(0, Pos);
2030
2031 return Success(Str.size(), E);
2032 }
2033
2034 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00002035
2036 case Builtin::BI__atomic_is_lock_free: {
2037 APSInt SizeVal;
2038 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
2039 return false;
2040
2041 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
2042 // of two less than the maximum inline atomic width, we know it is
2043 // lock-free. If the size isn't a power of two, or greater than the
2044 // maximum alignment where we promote atomics, we know it is not lock-free
2045 // (at least not in the sense of atomic_is_lock_free). Otherwise,
2046 // the answer can only be determined at runtime; for example, 16-byte
2047 // atomics have lock-free implementations on some, but not all,
2048 // x86-64 processors.
2049
2050 // Check power-of-two.
2051 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
2052 if (!Size.isPowerOfTwo())
2053#if 0
2054 // FIXME: Suppress this folding until the ABI for the promotion width
2055 // settles.
2056 return Success(0, E);
2057#else
2058 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2059#endif
2060
2061#if 0
2062 // Check against promotion width.
2063 // FIXME: Suppress this folding until the ABI for the promotion width
2064 // settles.
2065 unsigned PromoteWidthBits =
2066 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
2067 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
2068 return Success(0, E);
2069#endif
2070
2071 // Check against inlining width.
2072 unsigned InlineWidthBits =
2073 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
2074 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
2075 return Success(1, E);
2076
2077 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2078 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002079 }
Chris Lattner7174bf32008-07-12 00:38:25 +00002080}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002081
Richard Smith8b3497e2011-10-31 01:37:14 +00002082static bool HasSameBase(const LValue &A, const LValue &B) {
2083 if (!A.getLValueBase())
2084 return !B.getLValueBase();
2085 if (!B.getLValueBase())
2086 return false;
2087
2088 if (A.getLValueBase() != B.getLValueBase()) {
2089 const Decl *ADecl = GetLValueBaseDecl(A);
2090 if (!ADecl)
2091 return false;
2092 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00002093 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00002094 return false;
2095 }
2096
2097 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00002098 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00002099}
2100
Chris Lattnere13042c2008-07-11 19:10:17 +00002101bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002102 if (E->isAssignmentOp())
2103 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
2104
John McCalle3027922010-08-25 11:45:40 +00002105 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002106 VisitIgnoredValue(E->getLHS());
2107 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00002108 }
2109
2110 if (E->isLogicalOp()) {
2111 // These need to be handled specially because the operands aren't
2112 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00002113 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00002114
Richard Smith11562c52011-10-28 17:51:58 +00002115 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00002116 // We were able to evaluate the LHS, see if we can get away with not
2117 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00002118 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002119 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00002120
Richard Smith11562c52011-10-28 17:51:58 +00002121 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00002122 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002123 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00002124 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002125 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00002126 }
2127 } else {
Richard Smith11562c52011-10-28 17:51:58 +00002128 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00002129 // We can't evaluate the LHS; however, sometimes the result
2130 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00002131 if (rhsResult == (E->getOpcode() == BO_LOr) ||
2132 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002133 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00002134 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00002135 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002136
2137 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00002138 }
2139 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00002140 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00002141
Eli Friedman5a332ea2008-11-13 06:09:17 +00002142 return false;
2143 }
2144
Anders Carlssonacc79812008-11-16 07:17:21 +00002145 QualType LHSTy = E->getLHS()->getType();
2146 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002147
2148 if (LHSTy->isAnyComplexType()) {
2149 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00002150 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002151
2152 if (!EvaluateComplex(E->getLHS(), LHS, Info))
2153 return false;
2154
2155 if (!EvaluateComplex(E->getRHS(), RHS, Info))
2156 return false;
2157
2158 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00002159 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002160 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00002161 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002162 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
2163
John McCalle3027922010-08-25 11:45:40 +00002164 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002165 return Success((CR_r == APFloat::cmpEqual &&
2166 CR_i == APFloat::cmpEqual), E);
2167 else {
John McCalle3027922010-08-25 11:45:40 +00002168 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002169 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00002170 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00002171 CR_r == APFloat::cmpLessThan ||
2172 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00002173 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00002174 CR_i == APFloat::cmpLessThan ||
2175 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002176 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002177 } else {
John McCalle3027922010-08-25 11:45:40 +00002178 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002179 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
2180 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
2181 else {
John McCalle3027922010-08-25 11:45:40 +00002182 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002183 "Invalid compex comparison.");
2184 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
2185 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
2186 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002187 }
2188 }
Mike Stump11289f42009-09-09 15:08:12 +00002189
Anders Carlssonacc79812008-11-16 07:17:21 +00002190 if (LHSTy->isRealFloatingType() &&
2191 RHSTy->isRealFloatingType()) {
2192 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00002193
Anders Carlssonacc79812008-11-16 07:17:21 +00002194 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2195 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002196
Anders Carlssonacc79812008-11-16 07:17:21 +00002197 if (!EvaluateFloat(E->getLHS(), LHS, Info))
2198 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002199
Anders Carlssonacc79812008-11-16 07:17:21 +00002200 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00002201
Anders Carlssonacc79812008-11-16 07:17:21 +00002202 switch (E->getOpcode()) {
2203 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002204 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00002205 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002206 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00002207 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002208 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00002209 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002210 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00002211 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00002212 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002213 E);
John McCalle3027922010-08-25 11:45:40 +00002214 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002215 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00002216 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00002217 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00002218 || CR == APFloat::cmpLessThan
2219 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00002220 }
Anders Carlssonacc79812008-11-16 07:17:21 +00002221 }
Mike Stump11289f42009-09-09 15:08:12 +00002222
Eli Friedmana38da572009-04-28 19:17:36 +00002223 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00002224 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00002225 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002226 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
2227 return false;
Eli Friedman64004332009-03-23 04:38:34 +00002228
John McCall45d55e42010-05-07 21:00:08 +00002229 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002230 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
2231 return false;
Eli Friedman64004332009-03-23 04:38:34 +00002232
Richard Smith8b3497e2011-10-31 01:37:14 +00002233 // Reject differing bases from the normal codepath; we special-case
2234 // comparisons to null.
2235 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00002236 // Inequalities and subtractions between unrelated pointers have
2237 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00002238 if (!E->isEqualityOp())
2239 return false;
Eli Friedmanc6be94b2011-10-31 22:28:05 +00002240 // A constant address may compare equal to the address of a symbol.
2241 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00002242 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00002243 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
2244 (!RHSValue.Base && !RHSValue.Offset.isZero()))
2245 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002246 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00002247 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00002248 // distinct. However, we do know that the address of a literal will be
2249 // non-null.
2250 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
2251 LHSValue.Base && RHSValue.Base)
Eli Friedman334046a2009-06-14 02:17:33 +00002252 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002253 // We can't tell whether weak symbols will end up pointing to the same
2254 // object.
2255 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Eli Friedman334046a2009-06-14 02:17:33 +00002256 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002257 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00002258 // (Note that clang defaults to -fmerge-all-constants, which can
2259 // lead to inconsistent results for comparisons involving the address
2260 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00002261 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00002262 }
Eli Friedman64004332009-03-23 04:38:34 +00002263
Richard Smithf3e9e432011-11-07 09:22:26 +00002264 // FIXME: Implement the C++11 restrictions:
2265 // - Pointer subtractions must be on elements of the same array.
2266 // - Pointer comparisons must be between members with the same access.
2267
John McCalle3027922010-08-25 11:45:40 +00002268 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00002269 QualType Type = E->getLHS()->getType();
2270 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002271
Ken Dyck02990832010-01-15 12:37:54 +00002272 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00002273 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00002274 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00002275
Ken Dyck02990832010-01-15 12:37:54 +00002276 CharUnits Diff = LHSValue.getLValueOffset() -
2277 RHSValue.getLValueOffset();
2278 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002279 }
Richard Smith8b3497e2011-10-31 01:37:14 +00002280
2281 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
2282 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
2283 switch (E->getOpcode()) {
2284 default: llvm_unreachable("missing comparison operator");
2285 case BO_LT: return Success(LHSOffset < RHSOffset, E);
2286 case BO_GT: return Success(LHSOffset > RHSOffset, E);
2287 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
2288 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
2289 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
2290 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002291 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002292 }
2293 }
Douglas Gregorb90df602010-06-16 00:17:44 +00002294 if (!LHSTy->isIntegralOrEnumerationType() ||
2295 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002296 // We can't continue from here for non-integral types, and they
2297 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00002298 return false;
2299 }
2300
Anders Carlsson9c181652008-07-08 14:35:21 +00002301 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002302 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00002303 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00002304 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00002305
Richard Smith11562c52011-10-28 17:51:58 +00002306 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002307 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002308 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00002309
2310 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00002311 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00002312 CharUnits AdditionalOffset = CharUnits::fromQuantity(
2313 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00002314 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00002315 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00002316 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00002317 LHSVal.getLValueOffset() -= AdditionalOffset;
2318 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00002319 return true;
2320 }
2321
2322 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00002323 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00002324 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002325 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
2326 LHSVal.getInt().getZExtValue());
2327 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00002328 return true;
2329 }
2330
2331 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00002332 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00002333 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00002334
Richard Smith11562c52011-10-28 17:51:58 +00002335 APSInt &LHS = LHSVal.getInt();
2336 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00002337
Anders Carlsson9c181652008-07-08 14:35:21 +00002338 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002339 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002340 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00002341 case BO_Mul: return Success(LHS * RHS, E);
2342 case BO_Add: return Success(LHS + RHS, E);
2343 case BO_Sub: return Success(LHS - RHS, E);
2344 case BO_And: return Success(LHS & RHS, E);
2345 case BO_Xor: return Success(LHS ^ RHS, E);
2346 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002347 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00002348 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002349 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002350 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002351 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00002352 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002353 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002354 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002355 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00002356 // During constant-folding, a negative shift is an opposite shift.
2357 if (RHS.isSigned() && RHS.isNegative()) {
2358 RHS = -RHS;
2359 goto shift_right;
2360 }
2361
2362 shift_left:
2363 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00002364 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2365 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002366 }
John McCalle3027922010-08-25 11:45:40 +00002367 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00002368 // During constant-folding, a negative shift is an opposite shift.
2369 if (RHS.isSigned() && RHS.isNegative()) {
2370 RHS = -RHS;
2371 goto shift_left;
2372 }
2373
2374 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00002375 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00002376 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2377 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002378 }
Mike Stump11289f42009-09-09 15:08:12 +00002379
Richard Smith11562c52011-10-28 17:51:58 +00002380 case BO_LT: return Success(LHS < RHS, E);
2381 case BO_GT: return Success(LHS > RHS, E);
2382 case BO_LE: return Success(LHS <= RHS, E);
2383 case BO_GE: return Success(LHS >= RHS, E);
2384 case BO_EQ: return Success(LHS == RHS, E);
2385 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00002386 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002387}
2388
Ken Dyck160146e2010-01-27 17:10:57 +00002389CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002390 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2391 // the result is the size of the referenced type."
2392 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2393 // result shall be the alignment of the referenced type."
2394 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2395 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00002396
2397 // __alignof is defined to return the preferred alignment.
2398 return Info.Ctx.toCharUnitsFromBits(
2399 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00002400}
2401
Ken Dyck160146e2010-01-27 17:10:57 +00002402CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00002403 E = E->IgnoreParens();
2404
2405 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00002406 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00002407 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002408 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2409 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00002410
Chris Lattner68061312009-01-24 21:53:27 +00002411 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002412 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2413 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00002414
Chris Lattner24aeeab2009-01-24 21:09:06 +00002415 return GetAlignOfType(E->getType());
2416}
2417
2418
Peter Collingbournee190dee2011-03-11 19:24:49 +00002419/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2420/// a result as the expression's type.
2421bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2422 const UnaryExprOrTypeTraitExpr *E) {
2423 switch(E->getKind()) {
2424 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00002425 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00002426 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002427 else
Ken Dyckdbc01912011-03-11 02:13:43 +00002428 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002429 }
Eli Friedman64004332009-03-23 04:38:34 +00002430
Peter Collingbournee190dee2011-03-11 19:24:49 +00002431 case UETT_VecStep: {
2432 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00002433
Peter Collingbournee190dee2011-03-11 19:24:49 +00002434 if (Ty->isVectorType()) {
2435 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00002436
Peter Collingbournee190dee2011-03-11 19:24:49 +00002437 // The vec_step built-in functions that take a 3-component
2438 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2439 if (n == 3)
2440 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002441
Peter Collingbournee190dee2011-03-11 19:24:49 +00002442 return Success(n, E);
2443 } else
2444 return Success(1, E);
2445 }
2446
2447 case UETT_SizeOf: {
2448 QualType SrcTy = E->getTypeOfArgument();
2449 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2450 // the result is the size of the referenced type."
2451 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2452 // result shall be the alignment of the referenced type."
2453 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2454 SrcTy = Ref->getPointeeType();
2455
2456 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2457 // extension.
2458 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
2459 return Success(1, E);
2460
2461 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2462 if (!SrcTy->isConstantSizeType())
2463 return false;
2464
2465 // Get information about the size.
2466 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
2467 }
2468 }
2469
2470 llvm_unreachable("unknown expr/type trait");
2471 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002472}
2473
Peter Collingbournee9200682011-05-13 03:29:01 +00002474bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00002475 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00002476 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00002477 if (n == 0)
2478 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002479 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00002480 for (unsigned i = 0; i != n; ++i) {
2481 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
2482 switch (ON.getKind()) {
2483 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00002484 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00002485 APSInt IdxResult;
2486 if (!EvaluateInteger(Idx, IdxResult, Info))
2487 return false;
2488 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
2489 if (!AT)
2490 return false;
2491 CurrentType = AT->getElementType();
2492 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
2493 Result += IdxResult.getSExtValue() * ElementSize;
2494 break;
2495 }
2496
2497 case OffsetOfExpr::OffsetOfNode::Field: {
2498 FieldDecl *MemberDecl = ON.getField();
2499 const RecordType *RT = CurrentType->getAs<RecordType>();
2500 if (!RT)
2501 return false;
2502 RecordDecl *RD = RT->getDecl();
2503 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00002504 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00002505 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002506 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00002507 CurrentType = MemberDecl->getType().getNonReferenceType();
2508 break;
2509 }
2510
2511 case OffsetOfExpr::OffsetOfNode::Identifier:
2512 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00002513 return false;
2514
2515 case OffsetOfExpr::OffsetOfNode::Base: {
2516 CXXBaseSpecifier *BaseSpec = ON.getBase();
2517 if (BaseSpec->isVirtual())
2518 return false;
2519
2520 // Find the layout of the class whose base we are looking into.
2521 const RecordType *RT = CurrentType->getAs<RecordType>();
2522 if (!RT)
2523 return false;
2524 RecordDecl *RD = RT->getDecl();
2525 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
2526
2527 // Find the base class itself.
2528 CurrentType = BaseSpec->getType();
2529 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2530 if (!BaseRT)
2531 return false;
2532
2533 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00002534 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00002535 break;
2536 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002537 }
2538 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002539 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00002540}
2541
Chris Lattnere13042c2008-07-11 19:10:17 +00002542bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002543 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002544 // LNot's operand isn't necessarily an integer, so we handle it specially.
2545 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00002546 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00002547 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002548 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00002549 }
2550
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002551 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00002552 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002553 return false;
2554
Richard Smith11562c52011-10-28 17:51:58 +00002555 // Get the operand value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002556 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00002557 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00002558 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002559
Chris Lattnerf09ad162008-07-11 22:15:16 +00002560 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002561 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00002562 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2563 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002564 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00002565 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00002566 // FIXME: Should extension allow i-c-e extension expressions in its scope?
2567 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00002568 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002569 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00002570 // The result is just the value.
2571 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002572 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00002573 if (!Val.isInt()) return false;
2574 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00002575 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00002576 if (!Val.isInt()) return false;
2577 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00002578 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002579}
Mike Stump11289f42009-09-09 15:08:12 +00002580
Chris Lattner477c4be2008-07-12 01:15:53 +00002581/// HandleCast - This is used to evaluate implicit or explicit casts where the
2582/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00002583bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
2584 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002585 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00002586 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002587
Eli Friedmanc757de22011-03-25 00:43:55 +00002588 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00002589 case CK_BaseToDerived:
2590 case CK_DerivedToBase:
2591 case CK_UncheckedDerivedToBase:
2592 case CK_Dynamic:
2593 case CK_ToUnion:
2594 case CK_ArrayToPointerDecay:
2595 case CK_FunctionToPointerDecay:
2596 case CK_NullToPointer:
2597 case CK_NullToMemberPointer:
2598 case CK_BaseToDerivedMemberPointer:
2599 case CK_DerivedToBaseMemberPointer:
2600 case CK_ConstructorConversion:
2601 case CK_IntegralToPointer:
2602 case CK_ToVoid:
2603 case CK_VectorSplat:
2604 case CK_IntegralToFloating:
2605 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002606 case CK_CPointerToObjCPointerCast:
2607 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002608 case CK_AnyPointerToBlockPointerCast:
2609 case CK_ObjCObjectLValueCast:
2610 case CK_FloatingRealToComplex:
2611 case CK_FloatingComplexToReal:
2612 case CK_FloatingComplexCast:
2613 case CK_FloatingComplexToIntegralComplex:
2614 case CK_IntegralRealToComplex:
2615 case CK_IntegralComplexCast:
2616 case CK_IntegralComplexToFloatingComplex:
2617 llvm_unreachable("invalid cast kind for integral value");
2618
Eli Friedman9faf2f92011-03-25 19:07:11 +00002619 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002620 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00002621 case CK_LValueBitCast:
2622 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00002623 case CK_ARCProduceObject:
2624 case CK_ARCConsumeObject:
2625 case CK_ARCReclaimReturnedObject:
2626 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00002627 return false;
2628
2629 case CK_LValueToRValue:
2630 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002631 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002632
2633 case CK_MemberPointerToBoolean:
2634 case CK_PointerToBoolean:
2635 case CK_IntegralToBoolean:
2636 case CK_FloatingToBoolean:
2637 case CK_FloatingComplexToBoolean:
2638 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002639 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002640 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002641 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002642 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002643 }
2644
Eli Friedmanc757de22011-03-25 00:43:55 +00002645 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00002646 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00002647 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002648
Eli Friedman742421e2009-02-20 01:15:07 +00002649 if (!Result.isInt()) {
2650 // Only allow casts of lvalues if they are lossless.
2651 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2652 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002653
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002654 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002655 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00002656 }
Mike Stump11289f42009-09-09 15:08:12 +00002657
Eli Friedmanc757de22011-03-25 00:43:55 +00002658 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00002659 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00002660 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00002661 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002662
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002663 if (LV.getLValueBase()) {
2664 // Only allow based lvalue casts if they are lossless.
2665 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2666 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002667
John McCall45d55e42010-05-07 21:00:08 +00002668 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002669 return true;
2670 }
2671
Ken Dyck02990832010-01-15 12:37:54 +00002672 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2673 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002674 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002675 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002676
Eli Friedmanc757de22011-03-25 00:43:55 +00002677 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00002678 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002679 if (!EvaluateComplex(SubExpr, C, Info))
2680 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00002681 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002682 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00002683
Eli Friedmanc757de22011-03-25 00:43:55 +00002684 case CK_FloatingToIntegral: {
2685 APFloat F(0.0);
2686 if (!EvaluateFloat(SubExpr, F, Info))
2687 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00002688
Eli Friedmanc757de22011-03-25 00:43:55 +00002689 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2690 }
2691 }
Mike Stump11289f42009-09-09 15:08:12 +00002692
Eli Friedmanc757de22011-03-25 00:43:55 +00002693 llvm_unreachable("unknown cast resulting in integral value");
2694 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002695}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002696
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002697bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2698 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002699 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002700 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2701 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2702 return Success(LV.getComplexIntReal(), E);
2703 }
2704
2705 return Visit(E->getSubExpr());
2706}
2707
Eli Friedman4e7a2412009-02-27 04:45:43 +00002708bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002709 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002710 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002711 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2712 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2713 return Success(LV.getComplexIntImag(), E);
2714 }
2715
Richard Smith4a678122011-10-24 18:44:57 +00002716 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00002717 return Success(0, E);
2718}
2719
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002720bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2721 return Success(E->getPackLength(), E);
2722}
2723
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002724bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2725 return Success(E->getValue(), E);
2726}
2727
Chris Lattner05706e882008-07-11 18:11:29 +00002728//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002729// Float Evaluation
2730//===----------------------------------------------------------------------===//
2731
2732namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002733class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002734 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002735 APFloat &Result;
2736public:
2737 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002738 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002739
Richard Smith0b0a0b62011-10-29 20:57:55 +00002740 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002741 Result = V.getFloat();
2742 return true;
2743 }
2744 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002745 return false;
2746 }
2747
Richard Smith4ce706a2011-10-11 21:43:33 +00002748 bool ValueInitialization(const Expr *E) {
2749 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2750 return true;
2751 }
2752
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002753 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002754
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002755 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002756 bool VisitBinaryOperator(const BinaryOperator *E);
2757 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002758 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002759
John McCallb1fb0d32010-05-07 22:08:54 +00002760 bool VisitUnaryReal(const UnaryOperator *E);
2761 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002762
John McCallb1fb0d32010-05-07 22:08:54 +00002763 // FIXME: Missing: array subscript of vector, member of vector,
2764 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002765};
2766} // end anonymous namespace
2767
2768static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002769 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002770 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002771}
2772
Jay Foad39c79802011-01-12 09:06:06 +00002773static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002774 QualType ResultTy,
2775 const Expr *Arg,
2776 bool SNaN,
2777 llvm::APFloat &Result) {
2778 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2779 if (!S) return false;
2780
2781 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2782
2783 llvm::APInt fill;
2784
2785 // Treat empty strings as if they were zero.
2786 if (S->getString().empty())
2787 fill = llvm::APInt(32, 0);
2788 else if (S->getString().getAsInteger(0, fill))
2789 return false;
2790
2791 if (SNaN)
2792 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2793 else
2794 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2795 return true;
2796}
2797
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002798bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002799 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002800 default:
2801 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2802
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002803 case Builtin::BI__builtin_huge_val:
2804 case Builtin::BI__builtin_huge_valf:
2805 case Builtin::BI__builtin_huge_vall:
2806 case Builtin::BI__builtin_inf:
2807 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002808 case Builtin::BI__builtin_infl: {
2809 const llvm::fltSemantics &Sem =
2810 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002811 Result = llvm::APFloat::getInf(Sem);
2812 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002813 }
Mike Stump11289f42009-09-09 15:08:12 +00002814
John McCall16291492010-02-28 13:00:19 +00002815 case Builtin::BI__builtin_nans:
2816 case Builtin::BI__builtin_nansf:
2817 case Builtin::BI__builtin_nansl:
2818 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2819 true, Result);
2820
Chris Lattner0b7282e2008-10-06 06:31:58 +00002821 case Builtin::BI__builtin_nan:
2822 case Builtin::BI__builtin_nanf:
2823 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002824 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002825 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002826 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2827 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002828
2829 case Builtin::BI__builtin_fabs:
2830 case Builtin::BI__builtin_fabsf:
2831 case Builtin::BI__builtin_fabsl:
2832 if (!EvaluateFloat(E->getArg(0), Result, Info))
2833 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002834
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002835 if (Result.isNegative())
2836 Result.changeSign();
2837 return true;
2838
Mike Stump11289f42009-09-09 15:08:12 +00002839 case Builtin::BI__builtin_copysign:
2840 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002841 case Builtin::BI__builtin_copysignl: {
2842 APFloat RHS(0.);
2843 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2844 !EvaluateFloat(E->getArg(1), RHS, Info))
2845 return false;
2846 Result.copySign(RHS);
2847 return true;
2848 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002849 }
2850}
2851
John McCallb1fb0d32010-05-07 22:08:54 +00002852bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002853 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2854 ComplexValue CV;
2855 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2856 return false;
2857 Result = CV.FloatReal;
2858 return true;
2859 }
2860
2861 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002862}
2863
2864bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002865 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2866 ComplexValue CV;
2867 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2868 return false;
2869 Result = CV.FloatImag;
2870 return true;
2871 }
2872
Richard Smith4a678122011-10-24 18:44:57 +00002873 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00002874 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2875 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002876 return true;
2877}
2878
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002879bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002880 switch (E->getOpcode()) {
2881 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002882 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00002883 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00002884 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00002885 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2886 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002887 Result.changeSign();
2888 return true;
2889 }
2890}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002891
Eli Friedman24c01542008-08-22 00:06:13 +00002892bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002893 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002894 VisitIgnoredValue(E->getLHS());
2895 return Visit(E->getRHS());
Eli Friedman141fbf32009-11-16 04:25:37 +00002896 }
2897
Richard Smith472d4952011-10-28 23:26:52 +00002898 // We can't evaluate pointer-to-member operations or assignments.
2899 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlssona5df61a2010-10-31 01:21:47 +00002900 return false;
2901
Eli Friedman24c01542008-08-22 00:06:13 +00002902 // FIXME: Diagnostics? I really don't understand how the warnings
2903 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002904 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002905 if (!EvaluateFloat(E->getLHS(), Result, Info))
2906 return false;
2907 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2908 return false;
2909
2910 switch (E->getOpcode()) {
2911 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002912 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002913 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2914 return true;
John McCalle3027922010-08-25 11:45:40 +00002915 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002916 Result.add(RHS, APFloat::rmNearestTiesToEven);
2917 return true;
John McCalle3027922010-08-25 11:45:40 +00002918 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002919 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2920 return true;
John McCalle3027922010-08-25 11:45:40 +00002921 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002922 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2923 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002924 }
2925}
2926
2927bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2928 Result = E->getValue();
2929 return true;
2930}
2931
Peter Collingbournee9200682011-05-13 03:29:01 +00002932bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2933 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002934
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002935 switch (E->getCastKind()) {
2936 default:
Richard Smith11562c52011-10-28 17:51:58 +00002937 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002938
2939 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002940 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002941 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002942 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002943 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002944 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002945 return true;
2946 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002947
2948 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002949 if (!Visit(SubExpr))
2950 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002951 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2952 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002953 return true;
2954 }
John McCalld7646252010-11-14 08:17:51 +00002955
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002956 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002957 ComplexValue V;
2958 if (!EvaluateComplex(SubExpr, V, Info))
2959 return false;
2960 Result = V.getComplexFloatReal();
2961 return true;
2962 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002963 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002964
2965 return false;
2966}
2967
Eli Friedman24c01542008-08-22 00:06:13 +00002968//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002969// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002970//===----------------------------------------------------------------------===//
2971
2972namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002973class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002974 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002975 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002976
Anders Carlsson537969c2008-11-16 20:27:53 +00002977public:
John McCall93d91dc2010-05-07 17:22:02 +00002978 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002979 : ExprEvaluatorBaseTy(info), Result(Result) {}
2980
Richard Smith0b0a0b62011-10-29 20:57:55 +00002981 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002982 Result.setFrom(V);
2983 return true;
2984 }
2985 bool Error(const Expr *E) {
2986 return false;
2987 }
Mike Stump11289f42009-09-09 15:08:12 +00002988
Anders Carlsson537969c2008-11-16 20:27:53 +00002989 //===--------------------------------------------------------------------===//
2990 // Visitor Methods
2991 //===--------------------------------------------------------------------===//
2992
Peter Collingbournee9200682011-05-13 03:29:01 +00002993 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002994
Peter Collingbournee9200682011-05-13 03:29:01 +00002995 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002996
John McCall93d91dc2010-05-07 17:22:02 +00002997 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002998 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002999 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00003000};
3001} // end anonymous namespace
3002
John McCall93d91dc2010-05-07 17:22:02 +00003003static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
3004 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003005 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003006 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00003007}
3008
Peter Collingbournee9200682011-05-13 03:29:01 +00003009bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
3010 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003011
3012 if (SubExpr->getType()->isRealFloatingType()) {
3013 Result.makeComplexFloat();
3014 APFloat &Imag = Result.FloatImag;
3015 if (!EvaluateFloat(SubExpr, Imag, Info))
3016 return false;
3017
3018 Result.FloatReal = APFloat(Imag.getSemantics());
3019 return true;
3020 } else {
3021 assert(SubExpr->getType()->isIntegerType() &&
3022 "Unexpected imaginary literal.");
3023
3024 Result.makeComplexInt();
3025 APSInt &Imag = Result.IntImag;
3026 if (!EvaluateInteger(SubExpr, Imag, Info))
3027 return false;
3028
3029 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
3030 return true;
3031 }
3032}
3033
Peter Collingbournee9200682011-05-13 03:29:01 +00003034bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003035
John McCallfcef3cf2010-12-14 17:51:41 +00003036 switch (E->getCastKind()) {
3037 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00003038 case CK_BaseToDerived:
3039 case CK_DerivedToBase:
3040 case CK_UncheckedDerivedToBase:
3041 case CK_Dynamic:
3042 case CK_ToUnion:
3043 case CK_ArrayToPointerDecay:
3044 case CK_FunctionToPointerDecay:
3045 case CK_NullToPointer:
3046 case CK_NullToMemberPointer:
3047 case CK_BaseToDerivedMemberPointer:
3048 case CK_DerivedToBaseMemberPointer:
3049 case CK_MemberPointerToBoolean:
3050 case CK_ConstructorConversion:
3051 case CK_IntegralToPointer:
3052 case CK_PointerToIntegral:
3053 case CK_PointerToBoolean:
3054 case CK_ToVoid:
3055 case CK_VectorSplat:
3056 case CK_IntegralCast:
3057 case CK_IntegralToBoolean:
3058 case CK_IntegralToFloating:
3059 case CK_FloatingToIntegral:
3060 case CK_FloatingToBoolean:
3061 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00003062 case CK_CPointerToObjCPointerCast:
3063 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00003064 case CK_AnyPointerToBlockPointerCast:
3065 case CK_ObjCObjectLValueCast:
3066 case CK_FloatingComplexToReal:
3067 case CK_FloatingComplexToBoolean:
3068 case CK_IntegralComplexToReal:
3069 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00003070 case CK_ARCProduceObject:
3071 case CK_ARCConsumeObject:
3072 case CK_ARCReclaimReturnedObject:
3073 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00003074 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00003075
John McCallfcef3cf2010-12-14 17:51:41 +00003076 case CK_LValueToRValue:
3077 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00003078 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00003079
3080 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00003081 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00003082 case CK_UserDefinedConversion:
3083 return false;
3084
3085 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003086 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00003087 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003088 return false;
3089
John McCallfcef3cf2010-12-14 17:51:41 +00003090 Result.makeComplexFloat();
3091 Result.FloatImag = APFloat(Real.getSemantics());
3092 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003093 }
3094
John McCallfcef3cf2010-12-14 17:51:41 +00003095 case CK_FloatingComplexCast: {
3096 if (!Visit(E->getSubExpr()))
3097 return false;
3098
3099 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3100 QualType From
3101 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3102
3103 Result.FloatReal
3104 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
3105 Result.FloatImag
3106 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
3107 return true;
3108 }
3109
3110 case CK_FloatingComplexToIntegralComplex: {
3111 if (!Visit(E->getSubExpr()))
3112 return false;
3113
3114 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3115 QualType From
3116 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3117 Result.makeComplexInt();
3118 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
3119 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
3120 return true;
3121 }
3122
3123 case CK_IntegralRealToComplex: {
3124 APSInt &Real = Result.IntReal;
3125 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
3126 return false;
3127
3128 Result.makeComplexInt();
3129 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
3130 return true;
3131 }
3132
3133 case CK_IntegralComplexCast: {
3134 if (!Visit(E->getSubExpr()))
3135 return false;
3136
3137 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3138 QualType From
3139 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3140
3141 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
3142 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
3143 return true;
3144 }
3145
3146 case CK_IntegralComplexToFloatingComplex: {
3147 if (!Visit(E->getSubExpr()))
3148 return false;
3149
3150 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3151 QualType From
3152 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3153 Result.makeComplexFloat();
3154 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
3155 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
3156 return true;
3157 }
3158 }
3159
3160 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003161 return false;
3162}
3163
John McCall93d91dc2010-05-07 17:22:02 +00003164bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003165 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003166 VisitIgnoredValue(E->getLHS());
3167 return Visit(E->getRHS());
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003168 }
John McCall93d91dc2010-05-07 17:22:02 +00003169 if (!Visit(E->getLHS()))
3170 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003171
John McCall93d91dc2010-05-07 17:22:02 +00003172 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003173 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00003174 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003175
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003176 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
3177 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003178 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00003179 default: return false;
John McCalle3027922010-08-25 11:45:40 +00003180 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003181 if (Result.isComplexFloat()) {
3182 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
3183 APFloat::rmNearestTiesToEven);
3184 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
3185 APFloat::rmNearestTiesToEven);
3186 } else {
3187 Result.getComplexIntReal() += RHS.getComplexIntReal();
3188 Result.getComplexIntImag() += RHS.getComplexIntImag();
3189 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003190 break;
John McCalle3027922010-08-25 11:45:40 +00003191 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003192 if (Result.isComplexFloat()) {
3193 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
3194 APFloat::rmNearestTiesToEven);
3195 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
3196 APFloat::rmNearestTiesToEven);
3197 } else {
3198 Result.getComplexIntReal() -= RHS.getComplexIntReal();
3199 Result.getComplexIntImag() -= RHS.getComplexIntImag();
3200 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003201 break;
John McCalle3027922010-08-25 11:45:40 +00003202 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003203 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00003204 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003205 APFloat &LHS_r = LHS.getComplexFloatReal();
3206 APFloat &LHS_i = LHS.getComplexFloatImag();
3207 APFloat &RHS_r = RHS.getComplexFloatReal();
3208 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00003209
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003210 APFloat Tmp = LHS_r;
3211 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3212 Result.getComplexFloatReal() = Tmp;
3213 Tmp = LHS_i;
3214 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3215 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
3216
3217 Tmp = LHS_r;
3218 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3219 Result.getComplexFloatImag() = Tmp;
3220 Tmp = LHS_i;
3221 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3222 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
3223 } else {
John McCall93d91dc2010-05-07 17:22:02 +00003224 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00003225 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003226 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
3227 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00003228 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003229 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
3230 LHS.getComplexIntImag() * RHS.getComplexIntReal());
3231 }
3232 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003233 case BO_Div:
3234 if (Result.isComplexFloat()) {
3235 ComplexValue LHS = Result;
3236 APFloat &LHS_r = LHS.getComplexFloatReal();
3237 APFloat &LHS_i = LHS.getComplexFloatImag();
3238 APFloat &RHS_r = RHS.getComplexFloatReal();
3239 APFloat &RHS_i = RHS.getComplexFloatImag();
3240 APFloat &Res_r = Result.getComplexFloatReal();
3241 APFloat &Res_i = Result.getComplexFloatImag();
3242
3243 APFloat Den = RHS_r;
3244 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3245 APFloat Tmp = RHS_i;
3246 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3247 Den.add(Tmp, APFloat::rmNearestTiesToEven);
3248
3249 Res_r = LHS_r;
3250 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3251 Tmp = LHS_i;
3252 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3253 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
3254 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
3255
3256 Res_i = LHS_i;
3257 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3258 Tmp = LHS_r;
3259 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3260 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
3261 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
3262 } else {
3263 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
3264 // FIXME: what about diagnostics?
3265 return false;
3266 }
3267 ComplexValue LHS = Result;
3268 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
3269 RHS.getComplexIntImag() * RHS.getComplexIntImag();
3270 Result.getComplexIntReal() =
3271 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
3272 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
3273 Result.getComplexIntImag() =
3274 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
3275 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
3276 }
3277 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003278 }
3279
John McCall93d91dc2010-05-07 17:22:02 +00003280 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003281}
3282
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003283bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
3284 // Get the operand value into 'Result'.
3285 if (!Visit(E->getSubExpr()))
3286 return false;
3287
3288 switch (E->getOpcode()) {
3289 default:
3290 // FIXME: what about diagnostics?
3291 return false;
3292 case UO_Extension:
3293 return true;
3294 case UO_Plus:
3295 // The result is always just the subexpr.
3296 return true;
3297 case UO_Minus:
3298 if (Result.isComplexFloat()) {
3299 Result.getComplexFloatReal().changeSign();
3300 Result.getComplexFloatImag().changeSign();
3301 }
3302 else {
3303 Result.getComplexIntReal() = -Result.getComplexIntReal();
3304 Result.getComplexIntImag() = -Result.getComplexIntImag();
3305 }
3306 return true;
3307 case UO_Not:
3308 if (Result.isComplexFloat())
3309 Result.getComplexFloatImag().changeSign();
3310 else
3311 Result.getComplexIntImag() = -Result.getComplexIntImag();
3312 return true;
3313 }
3314}
3315
Anders Carlsson537969c2008-11-16 20:27:53 +00003316//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00003317// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00003318//===----------------------------------------------------------------------===//
3319
Richard Smith0b0a0b62011-10-29 20:57:55 +00003320static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003321 // In C, function designators are not lvalues, but we evaluate them as if they
3322 // are.
3323 if (E->isGLValue() || E->getType()->isFunctionType()) {
3324 LValue LV;
3325 if (!EvaluateLValue(E, LV, Info))
3326 return false;
3327 LV.moveInto(Result);
3328 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003329 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003330 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003331 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003332 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003333 return false;
John McCall45d55e42010-05-07 21:00:08 +00003334 } else if (E->getType()->hasPointerRepresentation()) {
3335 LValue LV;
3336 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003337 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003338 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00003339 } else if (E->getType()->isRealFloatingType()) {
3340 llvm::APFloat F(0.0);
3341 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003342 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003343 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00003344 } else if (E->getType()->isAnyComplexType()) {
3345 ComplexValue C;
3346 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003347 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003348 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00003349 } else if (E->getType()->isMemberPointerType()) {
3350 // FIXME: Implement evaluation of pointer-to-member types.
3351 return false;
3352 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smithf3e9e432011-11-07 09:22:26 +00003353 if (!EvaluateArray(E, Result, Info))
3354 return false;
Richard Smithed5165f2011-11-04 05:33:44 +00003355 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
3356 // FIXME: Implement evaluation of record rvalues.
3357 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003358 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00003359 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003360
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00003361 return true;
3362}
3363
Richard Smithed5165f2011-11-04 05:33:44 +00003364/// EvaluateConstantExpression - Evaluate an expression as a constant expression
3365/// in-place in an APValue. In some cases, the in-place evaluation is essential,
3366/// since later initializers for an object can indirectly refer to subobjects
3367/// which were initialized earlier.
3368static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
3369 const Expr *E) {
3370 if (E->isRValue() && E->getType()->isLiteralType()) {
3371 // Evaluate arrays and record types in-place, so that later initializers can
3372 // refer to earlier-initialized members of the object.
Richard Smithf3e9e432011-11-07 09:22:26 +00003373 if (E->getType()->isArrayType()) {
3374 if (!EvaluateArray(E, Result, Info))
3375 return false;
3376 } else if (E->getType()->isRecordType())
Richard Smithed5165f2011-11-04 05:33:44 +00003377 // FIXME: Implement evaluation of record rvalues.
3378 return false;
3379 }
3380
3381 // For any other type, in-place evaluation is unimportant.
3382 CCValue CoreConstResult;
3383 return Evaluate(CoreConstResult, Info, E) &&
3384 CheckConstantExpression(CoreConstResult, Result);
3385}
3386
Richard Smith11562c52011-10-28 17:51:58 +00003387
Richard Smith7b553f12011-10-29 00:50:52 +00003388/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00003389/// any crazy technique (that has nothing to do with language standards) that
3390/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00003391/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3392/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00003393bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith5686e752011-11-10 03:30:42 +00003394 // FIXME: Evaluating initializers for large arrays can cause performance
3395 // problems, and we don't use such values yet. Once we have a more efficient
3396 // array representation, this should be reinstated, and used by CodeGen.
3397 if (isRValue() && getType()->isArrayType())
3398 return false;
3399
John McCallc07a0c72011-02-17 10:25:35 +00003400 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00003401
Richard Smith0b0a0b62011-10-29 20:57:55 +00003402 CCValue Value;
3403 if (!::Evaluate(Value, Info, this))
Richard Smith11562c52011-10-28 17:51:58 +00003404 return false;
3405
3406 if (isGLValue()) {
3407 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003408 LV.setFrom(Value);
3409 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3410 return false;
Richard Smith11562c52011-10-28 17:51:58 +00003411 }
3412
Richard Smithf3e9e432011-11-07 09:22:26 +00003413 // Don't produce array constants until CodeGen is taught to handle them.
3414 if (Value.isArray())
3415 return false;
3416
Richard Smith0b0a0b62011-10-29 20:57:55 +00003417 // Check this core constant expression is a constant expression, and if so,
Richard Smithed5165f2011-11-04 05:33:44 +00003418 // convert it to one.
3419 return CheckConstantExpression(Value, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00003420}
3421
Jay Foad39c79802011-01-12 09:06:06 +00003422bool Expr::EvaluateAsBooleanCondition(bool &Result,
3423 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003424 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00003425 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00003426 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00003427 Result);
John McCall1be1c632010-01-05 23:42:56 +00003428}
3429
Richard Smithcaf33902011-10-10 18:28:20 +00003430bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003431 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003432 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smith11562c52011-10-28 17:51:58 +00003433 !ExprResult.Val.isInt()) {
3434 return false;
3435 }
3436 Result = ExprResult.Val.getInt();
3437 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00003438}
3439
Jay Foad39c79802011-01-12 09:06:06 +00003440bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00003441 EvalInfo Info(Ctx, Result);
3442
John McCall45d55e42010-05-07 21:00:08 +00003443 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00003444 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
3445 CheckLValueConstantExpression(LV, Result.Val);
Eli Friedman7d45c482009-09-13 10:17:44 +00003446}
3447
Richard Smith7b553f12011-10-29 00:50:52 +00003448/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3449/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00003450bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00003451 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00003452 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00003453}
Anders Carlsson59689ed2008-11-22 21:04:56 +00003454
Jay Foad39c79802011-01-12 09:06:06 +00003455bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00003456 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003457}
3458
Richard Smithcaf33902011-10-10 18:28:20 +00003459APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003460 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003461 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00003462 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00003463 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003464 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00003465
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003466 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00003467}
John McCall864e3962010-05-07 05:32:02 +00003468
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003469 bool Expr::EvalResult::isGlobalLValue() const {
3470 assert(Val.isLValue());
3471 return IsGlobalLValue(Val.getLValueBase());
3472 }
3473
3474
John McCall864e3962010-05-07 05:32:02 +00003475/// isIntegerConstantExpr - this recursive routine will test if an expression is
3476/// an integer constant expression.
3477
3478/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
3479/// comma, etc
3480///
3481/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
3482/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
3483/// cast+dereference.
3484
3485// CheckICE - This function does the fundamental ICE checking: the returned
3486// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
3487// Note that to reduce code duplication, this helper does no evaluation
3488// itself; the caller checks whether the expression is evaluatable, and
3489// in the rare cases where CheckICE actually cares about the evaluated
3490// value, it calls into Evalute.
3491//
3492// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00003493// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00003494// 1: This expression is not an ICE, but if it isn't evaluated, it's
3495// a legal subexpression for an ICE. This return value is used to handle
3496// the comma operator in C99 mode.
3497// 2: This expression is not an ICE, and is not a legal subexpression for one.
3498
Dan Gohman28ade552010-07-26 21:25:24 +00003499namespace {
3500
John McCall864e3962010-05-07 05:32:02 +00003501struct ICEDiag {
3502 unsigned Val;
3503 SourceLocation Loc;
3504
3505 public:
3506 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
3507 ICEDiag() : Val(0) {}
3508};
3509
Dan Gohman28ade552010-07-26 21:25:24 +00003510}
3511
3512static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00003513
3514static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
3515 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003516 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003517 !EVResult.Val.isInt()) {
3518 return ICEDiag(2, E->getLocStart());
3519 }
3520 return NoDiag();
3521}
3522
3523static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
3524 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00003525 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00003526 return ICEDiag(2, E->getLocStart());
3527 }
3528
3529 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00003530#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00003531#define STMT(Node, Base) case Expr::Node##Class:
3532#define EXPR(Node, Base)
3533#include "clang/AST/StmtNodes.inc"
3534 case Expr::PredefinedExprClass:
3535 case Expr::FloatingLiteralClass:
3536 case Expr::ImaginaryLiteralClass:
3537 case Expr::StringLiteralClass:
3538 case Expr::ArraySubscriptExprClass:
3539 case Expr::MemberExprClass:
3540 case Expr::CompoundAssignOperatorClass:
3541 case Expr::CompoundLiteralExprClass:
3542 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00003543 case Expr::DesignatedInitExprClass:
3544 case Expr::ImplicitValueInitExprClass:
3545 case Expr::ParenListExprClass:
3546 case Expr::VAArgExprClass:
3547 case Expr::AddrLabelExprClass:
3548 case Expr::StmtExprClass:
3549 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00003550 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00003551 case Expr::CXXDynamicCastExprClass:
3552 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00003553 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00003554 case Expr::CXXNullPtrLiteralExprClass:
3555 case Expr::CXXThisExprClass:
3556 case Expr::CXXThrowExprClass:
3557 case Expr::CXXNewExprClass:
3558 case Expr::CXXDeleteExprClass:
3559 case Expr::CXXPseudoDestructorExprClass:
3560 case Expr::UnresolvedLookupExprClass:
3561 case Expr::DependentScopeDeclRefExprClass:
3562 case Expr::CXXConstructExprClass:
3563 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00003564 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00003565 case Expr::CXXTemporaryObjectExprClass:
3566 case Expr::CXXUnresolvedConstructExprClass:
3567 case Expr::CXXDependentScopeMemberExprClass:
3568 case Expr::UnresolvedMemberExprClass:
3569 case Expr::ObjCStringLiteralClass:
3570 case Expr::ObjCEncodeExprClass:
3571 case Expr::ObjCMessageExprClass:
3572 case Expr::ObjCSelectorExprClass:
3573 case Expr::ObjCProtocolExprClass:
3574 case Expr::ObjCIvarRefExprClass:
3575 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00003576 case Expr::ObjCIsaExprClass:
3577 case Expr::ShuffleVectorExprClass:
3578 case Expr::BlockExprClass:
3579 case Expr::BlockDeclRefExprClass:
3580 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00003581 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00003582 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00003583 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00003584 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00003585 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00003586 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00003587 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003588 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00003589 return ICEDiag(2, E->getLocStart());
3590
Sebastian Redl12757ab2011-09-24 17:48:14 +00003591 case Expr::InitListExprClass:
3592 if (Ctx.getLangOptions().CPlusPlus0x) {
3593 const InitListExpr *ILE = cast<InitListExpr>(E);
3594 if (ILE->getNumInits() == 0)
3595 return NoDiag();
3596 if (ILE->getNumInits() == 1)
3597 return CheckICE(ILE->getInit(0), Ctx);
3598 // Fall through for more than 1 expression.
3599 }
3600 return ICEDiag(2, E->getLocStart());
3601
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003602 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00003603 case Expr::GNUNullExprClass:
3604 // GCC considers the GNU __null value to be an integral constant expression.
3605 return NoDiag();
3606
John McCall7c454bb2011-07-15 05:09:51 +00003607 case Expr::SubstNonTypeTemplateParmExprClass:
3608 return
3609 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
3610
John McCall864e3962010-05-07 05:32:02 +00003611 case Expr::ParenExprClass:
3612 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00003613 case Expr::GenericSelectionExprClass:
3614 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003615 case Expr::IntegerLiteralClass:
3616 case Expr::CharacterLiteralClass:
3617 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00003618 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00003619 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003620 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00003621 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00003622 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003623 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00003624 return NoDiag();
3625 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00003626 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00003627 // C99 6.6/3 allows function calls within unevaluated subexpressions of
3628 // constant expressions, but they can never be ICEs because an ICE cannot
3629 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00003630 const CallExpr *CE = cast<CallExpr>(E);
3631 if (CE->isBuiltinCall(Ctx))
3632 return CheckEvalInICE(E, Ctx);
3633 return ICEDiag(2, E->getLocStart());
3634 }
3635 case Expr::DeclRefExprClass:
3636 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
3637 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00003638 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00003639 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3640
3641 // Parameter variables are never constants. Without this check,
3642 // getAnyInitializer() can find a default argument, which leads
3643 // to chaos.
3644 if (isa<ParmVarDecl>(D))
3645 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3646
3647 // C++ 7.1.5.1p2
3648 // A variable of non-volatile const-qualified integral or enumeration
3649 // type initialized by an ICE can be used in ICEs.
3650 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00003651 if (!Dcl->getType()->isIntegralOrEnumerationType())
3652 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3653
John McCall864e3962010-05-07 05:32:02 +00003654 // Look for a declaration of this variable that has an initializer.
3655 const VarDecl *ID = 0;
3656 const Expr *Init = Dcl->getAnyInitializer(ID);
3657 if (Init) {
3658 if (ID->isInitKnownICE()) {
3659 // We have already checked whether this subexpression is an
3660 // integral constant expression.
3661 if (ID->isInitICE())
3662 return NoDiag();
3663 else
3664 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3665 }
3666
3667 // It's an ICE whether or not the definition we found is
3668 // out-of-line. See DR 721 and the discussion in Clang PR
3669 // 6206 for details.
3670
3671 if (Dcl->isCheckingICE()) {
3672 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3673 }
3674
3675 Dcl->setCheckingICE();
3676 ICEDiag Result = CheckICE(Init, Ctx);
3677 // Cache the result of the ICE test.
3678 Dcl->setInitKnownICE(Result.Val == 0);
3679 return Result;
3680 }
3681 }
3682 }
3683 return ICEDiag(2, E->getLocStart());
3684 case Expr::UnaryOperatorClass: {
3685 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3686 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003687 case UO_PostInc:
3688 case UO_PostDec:
3689 case UO_PreInc:
3690 case UO_PreDec:
3691 case UO_AddrOf:
3692 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00003693 // C99 6.6/3 allows increment and decrement within unevaluated
3694 // subexpressions of constant expressions, but they can never be ICEs
3695 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003696 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00003697 case UO_Extension:
3698 case UO_LNot:
3699 case UO_Plus:
3700 case UO_Minus:
3701 case UO_Not:
3702 case UO_Real:
3703 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003704 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003705 }
3706
3707 // OffsetOf falls through here.
3708 }
3709 case Expr::OffsetOfExprClass: {
3710 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00003711 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00003712 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00003713 // compliance: we should warn earlier for offsetof expressions with
3714 // array subscripts that aren't ICEs, and if the array subscripts
3715 // are ICEs, the value of the offsetof must be an integer constant.
3716 return CheckEvalInICE(E, Ctx);
3717 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003718 case Expr::UnaryExprOrTypeTraitExprClass: {
3719 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3720 if ((Exp->getKind() == UETT_SizeOf) &&
3721 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003722 return ICEDiag(2, E->getLocStart());
3723 return NoDiag();
3724 }
3725 case Expr::BinaryOperatorClass: {
3726 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3727 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003728 case BO_PtrMemD:
3729 case BO_PtrMemI:
3730 case BO_Assign:
3731 case BO_MulAssign:
3732 case BO_DivAssign:
3733 case BO_RemAssign:
3734 case BO_AddAssign:
3735 case BO_SubAssign:
3736 case BO_ShlAssign:
3737 case BO_ShrAssign:
3738 case BO_AndAssign:
3739 case BO_XorAssign:
3740 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00003741 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3742 // constant expressions, but they can never be ICEs because an ICE cannot
3743 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003744 return ICEDiag(2, E->getLocStart());
3745
John McCalle3027922010-08-25 11:45:40 +00003746 case BO_Mul:
3747 case BO_Div:
3748 case BO_Rem:
3749 case BO_Add:
3750 case BO_Sub:
3751 case BO_Shl:
3752 case BO_Shr:
3753 case BO_LT:
3754 case BO_GT:
3755 case BO_LE:
3756 case BO_GE:
3757 case BO_EQ:
3758 case BO_NE:
3759 case BO_And:
3760 case BO_Xor:
3761 case BO_Or:
3762 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003763 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3764 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003765 if (Exp->getOpcode() == BO_Div ||
3766 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00003767 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00003768 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003769 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003770 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003771 if (REval == 0)
3772 return ICEDiag(1, E->getLocStart());
3773 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003774 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003775 if (LEval.isMinSignedValue())
3776 return ICEDiag(1, E->getLocStart());
3777 }
3778 }
3779 }
John McCalle3027922010-08-25 11:45:40 +00003780 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003781 if (Ctx.getLangOptions().C99) {
3782 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3783 // if it isn't evaluated.
3784 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3785 return ICEDiag(1, E->getLocStart());
3786 } else {
3787 // In both C89 and C++, commas in ICEs are illegal.
3788 return ICEDiag(2, E->getLocStart());
3789 }
3790 }
3791 if (LHSResult.Val >= RHSResult.Val)
3792 return LHSResult;
3793 return RHSResult;
3794 }
John McCalle3027922010-08-25 11:45:40 +00003795 case BO_LAnd:
3796 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003797 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003798
3799 // C++0x [expr.const]p2:
3800 // [...] subexpressions of logical AND (5.14), logical OR
3801 // (5.15), and condi- tional (5.16) operations that are not
3802 // evaluated are not considered.
3803 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3804 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003805 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003806 return LHSResult;
3807
3808 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003809 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003810 return LHSResult;
3811 }
3812
John McCall864e3962010-05-07 05:32:02 +00003813 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3814 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3815 // Rare case where the RHS has a comma "side-effect"; we need
3816 // to actually check the condition to see whether the side
3817 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003818 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003819 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003820 return RHSResult;
3821 return NoDiag();
3822 }
3823
3824 if (LHSResult.Val >= RHSResult.Val)
3825 return LHSResult;
3826 return RHSResult;
3827 }
3828 }
3829 }
3830 case Expr::ImplicitCastExprClass:
3831 case Expr::CStyleCastExprClass:
3832 case Expr::CXXFunctionalCastExprClass:
3833 case Expr::CXXStaticCastExprClass:
3834 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00003835 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003836 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003837 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00003838 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00003839 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3840 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00003841 switch (cast<CastExpr>(E)->getCastKind()) {
3842 case CK_LValueToRValue:
3843 case CK_NoOp:
3844 case CK_IntegralToBoolean:
3845 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003846 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003847 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00003848 return ICEDiag(2, E->getLocStart());
3849 }
John McCall864e3962010-05-07 05:32:02 +00003850 }
John McCallc07a0c72011-02-17 10:25:35 +00003851 case Expr::BinaryConditionalOperatorClass: {
3852 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3853 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3854 if (CommonResult.Val == 2) return CommonResult;
3855 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3856 if (FalseResult.Val == 2) return FalseResult;
3857 if (CommonResult.Val == 1) return CommonResult;
3858 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003859 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003860 return FalseResult;
3861 }
John McCall864e3962010-05-07 05:32:02 +00003862 case Expr::ConditionalOperatorClass: {
3863 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3864 // If the condition (ignoring parens) is a __builtin_constant_p call,
3865 // then only the true side is actually considered in an integer constant
3866 // expression, and it is fully evaluated. This is an important GNU
3867 // extension. See GCC PR38377 for discussion.
3868 if (const CallExpr *CallCE
3869 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3870 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3871 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003872 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003873 !EVResult.Val.isInt()) {
3874 return ICEDiag(2, E->getLocStart());
3875 }
3876 return NoDiag();
3877 }
3878 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003879 if (CondResult.Val == 2)
3880 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003881
3882 // C++0x [expr.const]p2:
3883 // subexpressions of [...] conditional (5.16) operations that
3884 // are not evaluated are not considered
3885 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003886 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003887 : false;
3888 ICEDiag TrueResult = NoDiag();
3889 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3890 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3891 ICEDiag FalseResult = NoDiag();
3892 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3893 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3894
John McCall864e3962010-05-07 05:32:02 +00003895 if (TrueResult.Val == 2)
3896 return TrueResult;
3897 if (FalseResult.Val == 2)
3898 return FalseResult;
3899 if (CondResult.Val == 1)
3900 return CondResult;
3901 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3902 return NoDiag();
3903 // Rare case where the diagnostics depend on which side is evaluated
3904 // Note that if we get here, CondResult is 0, and at least one of
3905 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003906 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003907 return FalseResult;
3908 }
3909 return TrueResult;
3910 }
3911 case Expr::CXXDefaultArgExprClass:
3912 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3913 case Expr::ChooseExprClass: {
3914 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3915 }
3916 }
3917
3918 // Silence a GCC warning
3919 return ICEDiag(2, E->getLocStart());
3920}
3921
3922bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3923 SourceLocation *Loc, bool isEvaluated) const {
3924 ICEDiag d = CheckICE(this, Ctx);
3925 if (d.Val != 0) {
3926 if (Loc) *Loc = d.Loc;
3927 return false;
3928 }
Richard Smith11562c52011-10-28 17:51:58 +00003929 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00003930 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00003931 return true;
3932}