blob: a9408f6384c379a5f83e33fa3578ebf8446c5c5b [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 Smith80815602011-11-07 05:07:52 +0000135 Entries.back().ArrayIndex += N;
Richard Smith96e0c102011-11-04 02:25:55 +0000136 return;
137 }
138 if (OnePastTheEnd && N == (uint64_t)-1)
139 OnePastTheEnd = false;
140 else if (!OnePastTheEnd && N == 1)
141 OnePastTheEnd = true;
142 else if (N != 0)
143 setInvalid();
144 }
145 };
146
Richard Smith0b0a0b62011-10-29 20:57:55 +0000147 /// A core constant value. This can be the value of any constant expression,
148 /// or a pointer or reference to a non-static object or function parameter.
149 class CCValue : public APValue {
150 typedef llvm::APSInt APSInt;
151 typedef llvm::APFloat APFloat;
Richard Smithfec09922011-11-01 16:57:24 +0000152 /// If the value is a reference or pointer into a parameter or temporary,
153 /// this is the corresponding call stack frame.
154 CallStackFrame *CallFrame;
Richard Smith96e0c102011-11-04 02:25:55 +0000155 /// If the value is a reference or pointer, this is a description of how the
156 /// subobject was specified.
157 SubobjectDesignator Designator;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000158 public:
Richard Smithfec09922011-11-01 16:57:24 +0000159 struct GlobalValue {};
160
Richard Smith0b0a0b62011-10-29 20:57:55 +0000161 CCValue() {}
162 explicit CCValue(const APSInt &I) : APValue(I) {}
163 explicit CCValue(const APFloat &F) : APValue(F) {}
164 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
165 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
166 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smithfec09922011-11-01 16:57:24 +0000167 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000168 CCValue(const Expr *B, const CharUnits &O, CallStackFrame *F,
169 const SubobjectDesignator &D) :
Richard Smith80815602011-11-07 05:07:52 +0000170 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithfec09922011-11-01 16:57:24 +0000171 CCValue(const APValue &V, GlobalValue) :
Richard Smith80815602011-11-07 05:07:52 +0000172 APValue(V), CallFrame(0), Designator(V) {}
Richard Smith0b0a0b62011-10-29 20:57:55 +0000173
Richard Smithfec09922011-11-01 16:57:24 +0000174 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000175 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +0000176 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000177 }
Richard Smith96e0c102011-11-04 02:25:55 +0000178 SubobjectDesignator &getLValueDesignator() {
179 assert(getKind() == LValue);
180 return Designator;
181 }
182 const SubobjectDesignator &getLValueDesignator() const {
183 return const_cast<CCValue*>(this)->getLValueDesignator();
184 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000185 };
186
Richard Smith254a73d2011-10-28 22:34:42 +0000187 /// A stack frame in the constexpr call stack.
188 struct CallStackFrame {
189 EvalInfo &Info;
190
191 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000192 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000193
194 /// ParmBindings - Parameter bindings for this function call, indexed by
195 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000196 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000197
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000198 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
199 typedef MapTy::const_iterator temp_iterator;
200 /// Temporaries - Temporary lvalues materialized within this stack frame.
201 MapTy Temporaries;
202
203 CallStackFrame(EvalInfo &Info, const CCValue *Arguments);
204 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000205 };
206
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000207 struct EvalInfo {
208 const ASTContext &Ctx;
209
210 /// EvalStatus - Contains information about the evaluation.
211 Expr::EvalStatus &EvalStatus;
212
213 /// CurrentCall - The top of the constexpr call stack.
214 CallStackFrame *CurrentCall;
215
216 /// NumCalls - The number of calls we've evaluated so far.
217 unsigned NumCalls;
218
219 /// CallStackDepth - The number of calls in the call stack right now.
220 unsigned CallStackDepth;
221
222 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
223 /// OpaqueValues - Values used as the common expression in a
224 /// BinaryConditionalOperator.
225 MapTy OpaqueValues;
226
227 /// BottomFrame - The frame in which evaluation started. This must be
228 /// initialized last.
229 CallStackFrame BottomFrame;
230
231
232 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
233 : Ctx(C), EvalStatus(S), CurrentCall(0), NumCalls(0), CallStackDepth(0),
234 BottomFrame(*this, 0) {}
235
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000236 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
237 MapTy::const_iterator i = OpaqueValues.find(e);
238 if (i == OpaqueValues.end()) return 0;
239 return &i->second;
240 }
241
242 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
243 };
244
245 CallStackFrame::CallStackFrame(EvalInfo &Info, const CCValue *Arguments)
Richard Smithfec09922011-11-01 16:57:24 +0000246 : Info(Info), Caller(Info.CurrentCall), Arguments(Arguments) {
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000247 Info.CurrentCall = this;
248 ++Info.CallStackDepth;
249 }
250
251 CallStackFrame::~CallStackFrame() {
252 assert(Info.CurrentCall == this && "calls retired out of order");
253 --Info.CallStackDepth;
254 Info.CurrentCall = Caller;
255 }
256
John McCall93d91dc2010-05-07 17:22:02 +0000257 struct ComplexValue {
258 private:
259 bool IsInt;
260
261 public:
262 APSInt IntReal, IntImag;
263 APFloat FloatReal, FloatImag;
264
265 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
266
267 void makeComplexFloat() { IsInt = false; }
268 bool isComplexFloat() const { return !IsInt; }
269 APFloat &getComplexFloatReal() { return FloatReal; }
270 APFloat &getComplexFloatImag() { return FloatImag; }
271
272 void makeComplexInt() { IsInt = true; }
273 bool isComplexInt() const { return IsInt; }
274 APSInt &getComplexIntReal() { return IntReal; }
275 APSInt &getComplexIntImag() { return IntImag; }
276
Richard Smith0b0a0b62011-10-29 20:57:55 +0000277 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000278 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000279 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000280 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000281 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000282 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000283 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000284 assert(v.isComplexFloat() || v.isComplexInt());
285 if (v.isComplexFloat()) {
286 makeComplexFloat();
287 FloatReal = v.getComplexFloatReal();
288 FloatImag = v.getComplexFloatImag();
289 } else {
290 makeComplexInt();
291 IntReal = v.getComplexIntReal();
292 IntImag = v.getComplexIntImag();
293 }
294 }
John McCall93d91dc2010-05-07 17:22:02 +0000295 };
John McCall45d55e42010-05-07 21:00:08 +0000296
297 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000298 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000299 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000300 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000301 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000302
Richard Smith8b3497e2011-10-31 01:37:14 +0000303 const Expr *getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000304 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000305 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000306 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000307 SubobjectDesignator &getLValueDesignator() { return Designator; }
308 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000309
Richard Smith0b0a0b62011-10-29 20:57:55 +0000310 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000311 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000312 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000313 void setFrom(const CCValue &V) {
314 assert(V.isLValue());
315 Base = V.getLValueBase();
316 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000317 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000318 Designator = V.getLValueDesignator();
319 }
320
321 void setExpr(const Expr *E, CallStackFrame *F = 0) {
322 Base = E;
323 Offset = CharUnits::Zero();
324 Frame = F;
325 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000326 }
John McCall45d55e42010-05-07 21:00:08 +0000327 };
John McCall93d91dc2010-05-07 17:22:02 +0000328}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000329
Richard Smith0b0a0b62011-10-29 20:57:55 +0000330static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000331static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
332 const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000333static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
334static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000335static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000336static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000337 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000338static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000339static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000340
341//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000342// Misc utilities
343//===----------------------------------------------------------------------===//
344
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000345static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000346 if (!E) return true;
347
348 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
349 if (isa<FunctionDecl>(DRE->getDecl()))
350 return true;
351 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
352 return VD->hasGlobalStorage();
353 return false;
354 }
355
356 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
357 return CLE->isFileScope();
358
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000359 if (isa<MemberExpr>(E) || isa<MaterializeTemporaryExpr>(E))
Richard Smith11562c52011-10-28 17:51:58 +0000360 return false;
361
John McCall95007602010-05-10 23:27:23 +0000362 return true;
363}
364
Richard Smith80815602011-11-07 05:07:52 +0000365/// Check that this reference or pointer core constant expression is a valid
366/// value for a constant expression. Type T should be either LValue or CCValue.
367template<typename T>
368static bool CheckLValueConstantExpression(const T &LVal, APValue &Value) {
369 if (!IsGlobalLValue(LVal.getLValueBase()))
370 return false;
371
372 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
373 // A constant expression must refer to an object or be a null pointer.
374 if (Designator.Invalid || Designator.OnePastTheEnd ||
375 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
376 // FIXME: Check for out-of-bounds array indices.
377 // FIXME: This is not a constant expression.
378 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
379 APValue::NoLValuePath());
380 return true;
381 }
382
383 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
384 Designator.Entries);
385 return true;
386}
387
Richard Smith0b0a0b62011-10-29 20:57:55 +0000388/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000389/// constant expression, and if it is, produce the corresponding constant value.
390static bool CheckConstantExpression(const CCValue &CCValue, APValue &Value) {
Richard Smith80815602011-11-07 05:07:52 +0000391 if (!CCValue.isLValue()) {
392 Value = CCValue;
393 return true;
394 }
395 return CheckLValueConstantExpression(CCValue, Value);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000396}
397
Richard Smith83c68212011-10-31 05:11:32 +0000398const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
399 if (!LVal.Base)
400 return 0;
401
402 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVal.Base))
403 return DRE->getDecl();
404
405 // FIXME: Static data members accessed via a MemberExpr are represented as
406 // that MemberExpr. We should use the Decl directly instead.
407 if (const MemberExpr *ME = dyn_cast<MemberExpr>(LVal.Base)) {
408 assert(!isa<FieldDecl>(ME->getMemberDecl()) && "shouldn't see fields here");
409 return ME->getMemberDecl();
410 }
411
412 return 0;
413}
414
415static bool IsLiteralLValue(const LValue &Value) {
416 return Value.Base &&
417 !isa<DeclRefExpr>(Value.Base) &&
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000418 !isa<MemberExpr>(Value.Base) &&
419 !isa<MaterializeTemporaryExpr>(Value.Base);
Richard Smith83c68212011-10-31 05:11:32 +0000420}
421
Richard Smithcecf1842011-11-01 21:06:14 +0000422static bool IsWeakDecl(const ValueDecl *Decl) {
Richard Smith83c68212011-10-31 05:11:32 +0000423 return Decl->hasAttr<WeakAttr>() ||
424 Decl->hasAttr<WeakRefAttr>() ||
425 Decl->isWeakImported();
426}
427
Richard Smithcecf1842011-11-01 21:06:14 +0000428static bool IsWeakLValue(const LValue &Value) {
429 const ValueDecl *Decl = GetLValueBaseDecl(Value);
430 return Decl && IsWeakDecl(Decl);
431}
432
Richard Smith11562c52011-10-28 17:51:58 +0000433static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCall45d55e42010-05-07 21:00:08 +0000434 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000435
John McCalleb3e4f32010-05-07 21:34:32 +0000436 // A null base expression indicates a null pointer. These are always
437 // evaluatable, and they are false unless the offset is zero.
438 if (!Base) {
439 Result = !Value.Offset.isZero();
440 return true;
441 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000442
John McCall95007602010-05-10 23:27:23 +0000443 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000444 // FIXME: C++11 requires such conversions. Remove this check.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000445 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000446
John McCalleb3e4f32010-05-07 21:34:32 +0000447 // We have a non-null base expression. These are generally known to
448 // be true, but if it'a decl-ref to a weak symbol it can be null at
449 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000450 Result = true;
Richard Smith83c68212011-10-31 05:11:32 +0000451 return !IsWeakLValue(Value);
Eli Friedman334046a2009-06-14 02:17:33 +0000452}
453
Richard Smith0b0a0b62011-10-29 20:57:55 +0000454static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000455 switch (Val.getKind()) {
456 case APValue::Uninitialized:
457 return false;
458 case APValue::Int:
459 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000460 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000461 case APValue::Float:
462 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000463 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000464 case APValue::ComplexInt:
465 Result = Val.getComplexIntReal().getBoolValue() ||
466 Val.getComplexIntImag().getBoolValue();
467 return true;
468 case APValue::ComplexFloat:
469 Result = !Val.getComplexFloatReal().isZero() ||
470 !Val.getComplexFloatImag().isZero();
471 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000472 case APValue::LValue: {
473 LValue PointerResult;
474 PointerResult.setFrom(Val);
475 return EvalPointerValueAsBool(PointerResult, Result);
476 }
Richard Smith11562c52011-10-28 17:51:58 +0000477 case APValue::Vector:
478 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000479 }
480
Richard Smith11562c52011-10-28 17:51:58 +0000481 llvm_unreachable("unknown APValue kind");
482}
483
484static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
485 EvalInfo &Info) {
486 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000487 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000488 if (!Evaluate(Val, Info, E))
489 return false;
490 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000491}
492
Mike Stump11289f42009-09-09 15:08:12 +0000493static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000494 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000495 unsigned DestWidth = Ctx.getIntWidth(DestType);
496 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000497 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000498
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000499 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000500 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000501 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000502 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
503 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000504}
505
Mike Stump11289f42009-09-09 15:08:12 +0000506static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000507 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000508 bool ignored;
509 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000510 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000511 APFloat::rmNearestTiesToEven, &ignored);
512 return Result;
513}
514
Mike Stump11289f42009-09-09 15:08:12 +0000515static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000516 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000517 unsigned DestWidth = Ctx.getIntWidth(DestType);
518 APSInt Result = Value;
519 // Figure out if this is a truncate, extend or noop cast.
520 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000521 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000522 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000523 return Result;
524}
525
Mike Stump11289f42009-09-09 15:08:12 +0000526static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000527 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000528
529 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
530 Result.convertFromAPInt(Value, Value.isSigned(),
531 APFloat::rmNearestTiesToEven);
532 return Result;
533}
534
Richard Smith27908702011-10-24 17:54:18 +0000535/// Try to evaluate the initializer for a variable declaration.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000536static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +0000537 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000538 // If this is a parameter to an active constexpr function call, perform
539 // argument substitution.
540 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithfec09922011-11-01 16:57:24 +0000541 if (!Frame || !Frame->Arguments)
542 return false;
543 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
544 return true;
Richard Smith254a73d2011-10-28 22:34:42 +0000545 }
Richard Smith27908702011-10-24 17:54:18 +0000546
Richard Smithcecf1842011-11-01 21:06:14 +0000547 // Never evaluate the initializer of a weak variable. We can't be sure that
548 // this is the definition which will be used.
549 if (IsWeakDecl(VD))
550 return false;
551
Richard Smith27908702011-10-24 17:54:18 +0000552 const Expr *Init = VD->getAnyInitializer();
553 if (!Init)
Richard Smith0b0a0b62011-10-29 20:57:55 +0000554 return false;
Richard Smith27908702011-10-24 17:54:18 +0000555
Richard Smith0b0a0b62011-10-29 20:57:55 +0000556 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smithfec09922011-11-01 16:57:24 +0000557 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000558 return !Result.isUninit();
559 }
Richard Smith27908702011-10-24 17:54:18 +0000560
561 if (VD->isEvaluatingValue())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000562 return false;
Richard Smith27908702011-10-24 17:54:18 +0000563
564 VD->setEvaluatingValue();
565
Richard Smith0b0a0b62011-10-29 20:57:55 +0000566 Expr::EvalStatus EStatus;
567 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith11562c52011-10-28 17:51:58 +0000568 // FIXME: The caller will need to know whether the value was a constant
569 // expression. If not, we should propagate up a diagnostic.
Richard Smithed5165f2011-11-04 05:33:44 +0000570 APValue EvalResult;
571 if (!EvaluateConstantExpression(EvalResult, InitInfo, Init)) {
Richard Smith27908702011-10-24 17:54:18 +0000572 VD->setEvaluatedValue(APValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000573 return false;
574 }
Richard Smith27908702011-10-24 17:54:18 +0000575
Richard Smithed5165f2011-11-04 05:33:44 +0000576 VD->setEvaluatedValue(EvalResult);
577 Result = CCValue(EvalResult, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000578 return true;
Richard Smith27908702011-10-24 17:54:18 +0000579}
580
Richard Smith11562c52011-10-28 17:51:58 +0000581static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000582 Qualifiers Quals = T.getQualifiers();
583 return Quals.hasConst() && !Quals.hasVolatile();
584}
585
Richard Smith11562c52011-10-28 17:51:58 +0000586bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000587 const LValue &LVal, CCValue &RVal) {
Richard Smith11562c52011-10-28 17:51:58 +0000588 const Expr *Base = LVal.Base;
Richard Smithfec09922011-11-01 16:57:24 +0000589 CallStackFrame *Frame = LVal.Frame;
Richard Smith11562c52011-10-28 17:51:58 +0000590
591 // FIXME: Indirection through a null pointer deserves a diagnostic.
592 if (!Base)
593 return false;
594
Richard Smith8b3497e2011-10-31 01:37:14 +0000595 if (const ValueDecl *D = GetLValueBaseDecl(LVal)) {
Richard Smith11562c52011-10-28 17:51:58 +0000596 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
597 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +0000598 // expressions are constant expressions too. Inside constexpr functions,
599 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +0000600 // In C, such things can also be folded, although they are not ICEs.
601 //
Richard Smith254a73d2011-10-28 22:34:42 +0000602 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
603 // interpretation of C++11 suggests that volatile parameters are OK if
604 // they're never read (there's no prohibition against constructing volatile
605 // objects in constant expressions), but lvalue-to-rvalue conversions on
606 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +0000607 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith96e0c102011-11-04 02:25:55 +0000608 QualType VT = VD->getType();
Richard Smitha08acd82011-11-07 03:22:51 +0000609 if (!VD || VD->isInvalidDecl())
Richard Smith96e0c102011-11-04 02:25:55 +0000610 return false;
611 if (!isa<ParmVarDecl>(VD)) {
612 if (!IsConstNonVolatile(VT))
613 return false;
Richard Smitha08acd82011-11-07 03:22:51 +0000614 // FIXME: Allow folding of values of any literal type in all languages.
615 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
616 !VD->isConstexpr())
Richard Smith96e0c102011-11-04 02:25:55 +0000617 return false;
618 }
619 if (!EvaluateVarDeclInit(Info, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +0000620 return false;
621
Richard Smith0b0a0b62011-10-29 20:57:55 +0000622 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smith96e0c102011-11-04 02:25:55 +0000623 // If the lvalue refers to a subobject or has been cast to some other
624 // type, don't use it.
625 return LVal.Offset.isZero() &&
626 Info.Ctx.hasSameUnqualifiedType(Type, VT);
Richard Smith11562c52011-10-28 17:51:58 +0000627
628 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
629 // conversion. This happens when the declaration and the lvalue should be
630 // considered synonymous, for instance when initializing an array of char
631 // from a string literal. Continue as if the initializer lvalue was the
632 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +0000633 assert(RVal.getLValueOffset().isZero() &&
634 "offset for lvalue init of non-reference");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000635 Base = RVal.getLValueBase();
Richard Smithfec09922011-11-01 16:57:24 +0000636 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +0000637 }
638
Richard Smith96e0c102011-11-04 02:25:55 +0000639 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
640 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
641 const SubobjectDesignator &Designator = LVal.Designator;
642 if (Designator.Invalid || Designator.Entries.size() != 1)
643 return false;
644
645 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +0000646 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000647 if (Index > S->getLength())
648 return false;
649 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
650 Type->isUnsignedIntegerType());
651 if (Index < S->getLength())
652 Value = S->getCodeUnit(Index);
653 RVal = CCValue(Value);
654 return true;
655 }
656
657 // FIXME: Support accessing subobjects of objects of literal types. A simple
658 // byte offset is insufficient for C++11 semantics: we need to know how the
659 // reference was formed (which union member was named, for instance).
660
661 // Beyond this point, we don't support accessing subobjects.
662 if (!LVal.Offset.isZero() ||
663 !Info.Ctx.hasSameUnqualifiedType(Type, Base->getType()))
664 return false;
665
Richard Smithfec09922011-11-01 16:57:24 +0000666 // If this is a temporary expression with a nontrivial initializer, grab the
667 // value from the relevant stack frame.
668 if (Frame) {
669 RVal = Frame->Temporaries[Base];
670 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000671 }
Richard Smith11562c52011-10-28 17:51:58 +0000672
673 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
674 // initializer until now for such expressions. Such an expression can't be
675 // an ICE in C, so this only matters for fold.
676 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
677 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
678 return Evaluate(RVal, Info, CLE->getInitializer());
679 }
680
681 return false;
682}
683
Mike Stump876387b2009-10-27 22:09:17 +0000684namespace {
Richard Smith254a73d2011-10-28 22:34:42 +0000685enum EvalStmtResult {
686 /// Evaluation failed.
687 ESR_Failed,
688 /// Hit a 'return' statement.
689 ESR_Returned,
690 /// Evaluation succeeded.
691 ESR_Succeeded
692};
693}
694
695// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000696static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +0000697 const Stmt *S) {
698 switch (S->getStmtClass()) {
699 default:
700 return ESR_Failed;
701
702 case Stmt::NullStmtClass:
703 case Stmt::DeclStmtClass:
704 return ESR_Succeeded;
705
706 case Stmt::ReturnStmtClass:
707 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
708 return ESR_Returned;
709 return ESR_Failed;
710
711 case Stmt::CompoundStmtClass: {
712 const CompoundStmt *CS = cast<CompoundStmt>(S);
713 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
714 BE = CS->body_end(); BI != BE; ++BI) {
715 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
716 if (ESR != ESR_Succeeded)
717 return ESR;
718 }
719 return ESR_Succeeded;
720 }
721 }
722}
723
724/// Evaluate a function call.
725static bool HandleFunctionCall(ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000726 EvalInfo &Info, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000727 // FIXME: Implement a proper call limit, along with a command-line flag.
728 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
729 return false;
730
Richard Smith0b0a0b62011-10-29 20:57:55 +0000731 SmallVector<CCValue, 16> ArgValues(Args.size());
Richard Smith254a73d2011-10-28 22:34:42 +0000732 // FIXME: Deal with default arguments and 'this'.
733 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
734 I != E; ++I)
735 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
736 return false;
737
738 CallStackFrame Frame(Info, ArgValues.data());
739 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
740}
741
742namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000743class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000744 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000745 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000746public:
747
Richard Smith725810a2011-10-16 21:26:27 +0000748 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000749
750 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000751 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000752 return true;
753 }
754
Peter Collingbournee9200682011-05-13 03:29:01 +0000755 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
756 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000757 return Visit(E->getResultExpr());
758 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000759 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000760 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000761 return true;
762 return false;
763 }
John McCall31168b02011-06-15 23:02:42 +0000764 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000765 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000766 return true;
767 return false;
768 }
769 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000770 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000771 return true;
772 return false;
773 }
774
Mike Stump876387b2009-10-27 22:09:17 +0000775 // We don't want to evaluate BlockExprs multiple times, as they generate
776 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000777 bool VisitBlockExpr(const BlockExpr *E) { return true; }
778 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
779 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000780 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000781 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
782 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
783 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
784 bool VisitStringLiteral(const StringLiteral *E) { return false; }
785 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
786 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000787 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000788 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000789 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000790 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000791 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000792 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
793 bool VisitBinAssign(const BinaryOperator *E) { return true; }
794 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
795 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000796 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000797 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
798 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
799 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
800 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
801 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000802 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000803 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000804 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000805 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000806 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000807
808 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000809 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000810 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
811 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000812 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000813 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000814 return false;
815 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000816
Peter Collingbournee9200682011-05-13 03:29:01 +0000817 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000818};
819
John McCallc07a0c72011-02-17 10:25:35 +0000820class OpaqueValueEvaluation {
821 EvalInfo &info;
822 OpaqueValueExpr *opaqueValue;
823
824public:
825 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
826 Expr *value)
827 : info(info), opaqueValue(opaqueValue) {
828
829 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000830 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000831 this->opaqueValue = 0;
832 return;
833 }
John McCallc07a0c72011-02-17 10:25:35 +0000834 }
835
836 bool hasError() const { return opaqueValue == 0; }
837
838 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000839 // FIXME: This will not work for recursive constexpr functions using opaque
840 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000841 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
842 }
843};
844
Mike Stump876387b2009-10-27 22:09:17 +0000845} // end anonymous namespace
846
Eli Friedman9a156e52008-11-12 09:44:48 +0000847//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000848// Generic Evaluation
849//===----------------------------------------------------------------------===//
850namespace {
851
852template <class Derived, typename RetTy=void>
853class ExprEvaluatorBase
854 : public ConstStmtVisitor<Derived, RetTy> {
855private:
Richard Smith0b0a0b62011-10-29 20:57:55 +0000856 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000857 return static_cast<Derived*>(this)->Success(V, E);
858 }
859 RetTy DerivedError(const Expr *E) {
860 return static_cast<Derived*>(this)->Error(E);
861 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000862 RetTy DerivedValueInitialization(const Expr *E) {
863 return static_cast<Derived*>(this)->ValueInitialization(E);
864 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000865
866protected:
867 EvalInfo &Info;
868 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
869 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
870
Richard Smith4ce706a2011-10-11 21:43:33 +0000871 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
872
Richard Smithfec09922011-11-01 16:57:24 +0000873 bool MakeTemporary(const Expr *Key, const Expr *Value, LValue &Result) {
874 if (!Evaluate(Info.CurrentCall->Temporaries[Key], Info, Value))
875 return false;
Richard Smith96e0c102011-11-04 02:25:55 +0000876 Result.setExpr(Key, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +0000877 return true;
878 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000879public:
880 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
881
882 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000883 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000884 }
885 RetTy VisitExpr(const Expr *E) {
886 return DerivedError(E);
887 }
888
889 RetTy VisitParenExpr(const ParenExpr *E)
890 { return StmtVisitorTy::Visit(E->getSubExpr()); }
891 RetTy VisitUnaryExtension(const UnaryOperator *E)
892 { return StmtVisitorTy::Visit(E->getSubExpr()); }
893 RetTy VisitUnaryPlus(const UnaryOperator *E)
894 { return StmtVisitorTy::Visit(E->getSubExpr()); }
895 RetTy VisitChooseExpr(const ChooseExpr *E)
896 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
897 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
898 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000899 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
900 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000901
902 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
903 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
904 if (opaque.hasError())
905 return DerivedError(E);
906
907 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +0000908 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000909 return DerivedError(E);
910
911 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
912 }
913
914 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
915 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +0000916 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000917 return DerivedError(E);
918
Richard Smith11562c52011-10-28 17:51:58 +0000919 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +0000920 return StmtVisitorTy::Visit(EvalExpr);
921 }
922
923 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000924 const CCValue *Value = Info.getOpaqueValue(E);
925 if (!Value)
Peter Collingbournee9200682011-05-13 03:29:01 +0000926 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
927 : DerivedError(E));
Richard Smith0b0a0b62011-10-29 20:57:55 +0000928 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000929 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000930
Richard Smith254a73d2011-10-28 22:34:42 +0000931 RetTy VisitCallExpr(const CallExpr *E) {
932 const Expr *Callee = E->getCallee();
933 QualType CalleeType = Callee->getType();
934
935 // FIXME: Handle the case where Callee is a (parenthesized) MemberExpr for a
936 // non-static member function.
937 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember))
938 return DerivedError(E);
939
940 if (!CalleeType->isFunctionType() && !CalleeType->isFunctionPointerType())
941 return DerivedError(E);
942
Richard Smith0b0a0b62011-10-29 20:57:55 +0000943 CCValue Call;
Richard Smith254a73d2011-10-28 22:34:42 +0000944 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
945 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
946 return DerivedError(Callee);
947
948 const FunctionDecl *FD = 0;
949 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Call.getLValueBase()))
950 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
951 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Call.getLValueBase()))
952 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
953 if (!FD)
954 return DerivedError(Callee);
955
956 // Don't call function pointers which have been cast to some other type.
957 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
958 return DerivedError(E);
959
960 const FunctionDecl *Definition;
961 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +0000962 CCValue CCResult;
963 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +0000964 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
965
966 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
Richard Smithed5165f2011-11-04 05:33:44 +0000967 HandleFunctionCall(Args, Body, Info, CCResult) &&
968 CheckConstantExpression(CCResult, Result))
969 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +0000970
971 return DerivedError(E);
972 }
973
Richard Smith11562c52011-10-28 17:51:58 +0000974 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
975 return StmtVisitorTy::Visit(E->getInitializer());
976 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000977 RetTy VisitInitListExpr(const InitListExpr *E) {
978 if (Info.getLangOpts().CPlusPlus0x) {
979 if (E->getNumInits() == 0)
980 return DerivedValueInitialization(E);
981 if (E->getNumInits() == 1)
982 return StmtVisitorTy::Visit(E->getInit(0));
983 }
984 return DerivedError(E);
985 }
986 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
987 return DerivedValueInitialization(E);
988 }
989 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
990 return DerivedValueInitialization(E);
991 }
992
Richard Smith11562c52011-10-28 17:51:58 +0000993 RetTy VisitCastExpr(const CastExpr *E) {
994 switch (E->getCastKind()) {
995 default:
996 break;
997
998 case CK_NoOp:
999 return StmtVisitorTy::Visit(E->getSubExpr());
1000
1001 case CK_LValueToRValue: {
1002 LValue LVal;
1003 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001004 CCValue RVal;
Richard Smith11562c52011-10-28 17:51:58 +00001005 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
1006 return DerivedSuccess(RVal, E);
1007 }
1008 break;
1009 }
1010 }
1011
1012 return DerivedError(E);
1013 }
1014
Richard Smith4a678122011-10-24 18:44:57 +00001015 /// Visit a value which is evaluated, but whose value is ignored.
1016 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001017 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00001018 if (!Evaluate(Scratch, Info, E))
1019 Info.EvalStatus.HasSideEffects = true;
1020 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001021};
1022
1023}
1024
1025//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001026// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001027//
1028// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
1029// function designators (in C), decl references to void objects (in C), and
1030// temporaries (if building with -Wno-address-of-temporary).
1031//
1032// LValue evaluation produces values comprising a base expression of one of the
1033// following types:
1034// * DeclRefExpr
1035// * MemberExpr for a static member
1036// * CompoundLiteralExpr in C
1037// * StringLiteral
1038// * PredefinedExpr
1039// * ObjCEncodeExpr
1040// * AddrLabelExpr
1041// * BlockExpr
1042// * CallExpr for a MakeStringConstant builtin
Richard Smithfec09922011-11-01 16:57:24 +00001043// plus an offset in bytes. It can also produce lvalues referring to locals. In
1044// that case, the Frame will point to a stack frame, and the Expr is used as a
1045// key to find the relevant temporary's value.
Eli Friedman9a156e52008-11-12 09:44:48 +00001046//===----------------------------------------------------------------------===//
1047namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001048class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001049 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001050 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +00001051 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +00001052
Peter Collingbournee9200682011-05-13 03:29:01 +00001053 bool Success(const Expr *E) {
Richard Smith96e0c102011-11-04 02:25:55 +00001054 Result.setExpr(E);
John McCall45d55e42010-05-07 21:00:08 +00001055 return true;
1056 }
Eli Friedman9a156e52008-11-12 09:44:48 +00001057public:
Mike Stump11289f42009-09-09 15:08:12 +00001058
John McCall45d55e42010-05-07 21:00:08 +00001059 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +00001060 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +00001061
Richard Smith0b0a0b62011-10-29 20:57:55 +00001062 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001063 Result.setFrom(V);
1064 return true;
1065 }
1066 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00001067 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001068 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001069
Richard Smith11562c52011-10-28 17:51:58 +00001070 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
1071
Peter Collingbournee9200682011-05-13 03:29:01 +00001072 bool VisitDeclRefExpr(const DeclRefExpr *E);
1073 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001074 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001075 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1076 bool VisitMemberExpr(const MemberExpr *E);
1077 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
1078 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
1079 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
1080 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001081
Peter Collingbournee9200682011-05-13 03:29:01 +00001082 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00001083 switch (E->getCastKind()) {
1084 default:
Richard Smith11562c52011-10-28 17:51:58 +00001085 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001086
Eli Friedmance3e02a2011-10-11 00:13:24 +00001087 case CK_LValueBitCast:
Richard Smith96e0c102011-11-04 02:25:55 +00001088 if (!Visit(E->getSubExpr()))
1089 return false;
1090 Result.Designator.setInvalid();
1091 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00001092
Richard Smith11562c52011-10-28 17:51:58 +00001093 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
1094 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlssonde55f642009-10-03 16:30:22 +00001095 }
1096 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00001097
Eli Friedman449fe542009-03-23 04:56:01 +00001098 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00001099
Eli Friedman9a156e52008-11-12 09:44:48 +00001100};
1101} // end anonymous namespace
1102
Richard Smith11562c52011-10-28 17:51:58 +00001103/// Evaluate an expression as an lvalue. This can be legitimately called on
1104/// expressions which are not glvalues, in a few cases:
1105/// * function designators in C,
1106/// * "extern void" objects,
1107/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00001108static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001109 assert((E->isGLValue() || E->getType()->isFunctionType() ||
1110 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
1111 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00001112 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001113}
1114
Peter Collingbournee9200682011-05-13 03:29:01 +00001115bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001116 if (isa<FunctionDecl>(E->getDecl()))
John McCall45d55e42010-05-07 21:00:08 +00001117 return Success(E);
Richard Smith11562c52011-10-28 17:51:58 +00001118 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
1119 return VisitVarDecl(E, VD);
1120 return Error(E);
1121}
Richard Smith733237d2011-10-24 23:14:33 +00001122
Richard Smith11562c52011-10-28 17:51:58 +00001123bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00001124 if (!VD->getType()->isReferenceType()) {
1125 if (isa<ParmVarDecl>(VD)) {
Richard Smith96e0c102011-11-04 02:25:55 +00001126 Result.setExpr(E, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00001127 return true;
1128 }
Richard Smith11562c52011-10-28 17:51:58 +00001129 return Success(E);
Richard Smithfec09922011-11-01 16:57:24 +00001130 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00001131
Richard Smith0b0a0b62011-10-29 20:57:55 +00001132 CCValue V;
Richard Smithfec09922011-11-01 16:57:24 +00001133 if (EvaluateVarDeclInit(Info, VD, Info.CurrentCall, V))
Richard Smith0b0a0b62011-10-29 20:57:55 +00001134 return Success(V, E);
Richard Smith11562c52011-10-28 17:51:58 +00001135
1136 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +00001137}
1138
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001139bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
1140 const MaterializeTemporaryExpr *E) {
Richard Smithfec09922011-11-01 16:57:24 +00001141 return MakeTemporary(E, E->GetTemporaryExpr(), Result);
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001142}
1143
Peter Collingbournee9200682011-05-13 03:29:01 +00001144bool
1145LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001146 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1147 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
1148 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00001149 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001150}
1151
Peter Collingbournee9200682011-05-13 03:29:01 +00001152bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001153 // Handle static data members.
1154 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
1155 VisitIgnoredValue(E->getBase());
1156 return VisitVarDecl(E, VD);
1157 }
1158
Richard Smith254a73d2011-10-28 22:34:42 +00001159 // Handle static member functions.
1160 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
1161 if (MD->isStatic()) {
1162 VisitIgnoredValue(E->getBase());
1163 return Success(E);
1164 }
1165 }
1166
Eli Friedman9a156e52008-11-12 09:44:48 +00001167 QualType Ty;
1168 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +00001169 if (!EvaluatePointer(E->getBase(), Result, Info))
1170 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001171 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +00001172 } else {
John McCall45d55e42010-05-07 21:00:08 +00001173 if (!Visit(E->getBase()))
1174 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001175 Ty = E->getBase()->getType();
1176 }
1177
Peter Collingbournee9200682011-05-13 03:29:01 +00001178 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +00001179 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001180
Peter Collingbournee9200682011-05-13 03:29:01 +00001181 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001182 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +00001183 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001184
1185 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +00001186 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001187
Eli Friedmana3c122d2011-07-07 01:54:01 +00001188 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001189 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Richard Smith96e0c102011-11-04 02:25:55 +00001190 Result.Designator.addDecl(FD);
John McCall45d55e42010-05-07 21:00:08 +00001191 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +00001192}
1193
Peter Collingbournee9200682011-05-13 03:29:01 +00001194bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001195 // FIXME: Deal with vectors as array subscript bases.
1196 if (E->getBase()->getType()->isVectorType())
1197 return false;
1198
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001199 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00001200 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001201
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001202 APSInt Index;
1203 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00001204 return false;
Richard Smith96e0c102011-11-04 02:25:55 +00001205 uint64_t IndexValue
1206 = Index.isSigned() ? static_cast<uint64_t>(Index.getSExtValue())
1207 : Index.getZExtValue();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001208
Ken Dyck40775002010-01-11 17:06:35 +00001209 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
Richard Smith96e0c102011-11-04 02:25:55 +00001210 Result.Offset += IndexValue * ElementSize;
1211 Result.Designator.adjustIndex(IndexValue);
John McCall45d55e42010-05-07 21:00:08 +00001212 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001213}
Eli Friedman9a156e52008-11-12 09:44:48 +00001214
Peter Collingbournee9200682011-05-13 03:29:01 +00001215bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00001216 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00001217}
1218
Eli Friedman9a156e52008-11-12 09:44:48 +00001219//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001220// Pointer Evaluation
1221//===----------------------------------------------------------------------===//
1222
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001223namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001224class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001225 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001226 LValue &Result;
1227
Peter Collingbournee9200682011-05-13 03:29:01 +00001228 bool Success(const Expr *E) {
Richard Smith96e0c102011-11-04 02:25:55 +00001229 Result.setExpr(E);
John McCall45d55e42010-05-07 21:00:08 +00001230 return true;
1231 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001232public:
Mike Stump11289f42009-09-09 15:08:12 +00001233
John McCall45d55e42010-05-07 21:00:08 +00001234 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001235 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001236
Richard Smith0b0a0b62011-10-29 20:57:55 +00001237 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001238 Result.setFrom(V);
1239 return true;
1240 }
1241 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +00001242 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001243 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001244 bool ValueInitialization(const Expr *E) {
1245 return Success((Expr*)0);
1246 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001247
John McCall45d55e42010-05-07 21:00:08 +00001248 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001249 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00001250 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001251 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00001252 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001253 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00001254 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001255 bool VisitCallExpr(const CallExpr *E);
1256 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00001257 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00001258 return Success(E);
1259 return false;
Mike Stumpa6703322009-02-19 22:01:56 +00001260 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001261 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +00001262 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +00001263
Eli Friedman449fe542009-03-23 04:56:01 +00001264 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001265};
Chris Lattner05706e882008-07-11 18:11:29 +00001266} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001267
John McCall45d55e42010-05-07 21:00:08 +00001268static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001269 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00001270 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00001271}
1272
John McCall45d55e42010-05-07 21:00:08 +00001273bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001274 if (E->getOpcode() != BO_Add &&
1275 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +00001276 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001277
Chris Lattner05706e882008-07-11 18:11:29 +00001278 const Expr *PExp = E->getLHS();
1279 const Expr *IExp = E->getRHS();
1280 if (IExp->getType()->isPointerType())
1281 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00001282
John McCall45d55e42010-05-07 21:00:08 +00001283 if (!EvaluatePointer(PExp, Result, Info))
1284 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001285
John McCall45d55e42010-05-07 21:00:08 +00001286 llvm::APSInt Offset;
1287 if (!EvaluateInteger(IExp, Offset, Info))
1288 return false;
1289 int64_t AdditionalOffset
1290 = Offset.isSigned() ? Offset.getSExtValue()
1291 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00001292 if (E->getOpcode() == BO_Sub)
1293 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00001294
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001295 // Compute the new offset in the appropriate width.
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001296 QualType PointeeType =
1297 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +00001298 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +00001299
Anders Carlssonef56fba2009-02-19 04:55:58 +00001300 // Explicitly handle GNU void* and function pointer arithmetic extensions.
1301 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +00001302 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +00001303 else
John McCall45d55e42010-05-07 21:00:08 +00001304 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +00001305
Richard Smith96e0c102011-11-04 02:25:55 +00001306 Result.Offset += AdditionalOffset * SizeOfPointee;
1307 Result.Designator.adjustIndex(AdditionalOffset);
John McCall45d55e42010-05-07 21:00:08 +00001308 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001309}
Eli Friedman9a156e52008-11-12 09:44:48 +00001310
John McCall45d55e42010-05-07 21:00:08 +00001311bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1312 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001313}
Mike Stump11289f42009-09-09 15:08:12 +00001314
Chris Lattner05706e882008-07-11 18:11:29 +00001315
Peter Collingbournee9200682011-05-13 03:29:01 +00001316bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1317 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00001318
Eli Friedman847a2bc2009-12-27 05:43:15 +00001319 switch (E->getCastKind()) {
1320 default:
1321 break;
1322
John McCalle3027922010-08-25 11:45:40 +00001323 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00001324 case CK_CPointerToObjCPointerCast:
1325 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001326 case CK_AnyPointerToBlockPointerCast:
Richard Smith96e0c102011-11-04 02:25:55 +00001327 if (!Visit(SubExpr))
1328 return false;
1329 Result.Designator.setInvalid();
1330 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00001331
Anders Carlsson18275092010-10-31 20:41:46 +00001332 case CK_DerivedToBase:
1333 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001334 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00001335 return false;
1336
1337 // Now figure out the necessary offset to add to the baseLV to get from
1338 // the derived class to the base class.
Anders Carlsson18275092010-10-31 20:41:46 +00001339 QualType Ty = E->getSubExpr()->getType();
1340 const CXXRecordDecl *DerivedDecl =
1341 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
1342
1343 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1344 PathE = E->path_end(); PathI != PathE; ++PathI) {
1345 const CXXBaseSpecifier *Base = *PathI;
1346
1347 // FIXME: If the base is virtual, we'd need to determine the type of the
1348 // most derived class and we don't support that right now.
1349 if (Base->isVirtual())
1350 return false;
1351
1352 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1353 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1354
Richard Smith0b0a0b62011-10-29 20:57:55 +00001355 Result.getLValueOffset() += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +00001356 DerivedDecl = BaseDecl;
1357 }
1358
Richard Smith96e0c102011-11-04 02:25:55 +00001359 // FIXME
1360 Result.Designator.setInvalid();
1361
Anders Carlsson18275092010-10-31 20:41:46 +00001362 return true;
1363 }
1364
Richard Smith0b0a0b62011-10-29 20:57:55 +00001365 case CK_NullToPointer:
1366 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00001367
John McCalle3027922010-08-25 11:45:40 +00001368 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001369 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00001370 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00001371 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00001372
John McCall45d55e42010-05-07 21:00:08 +00001373 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001374 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1375 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
John McCall45d55e42010-05-07 21:00:08 +00001376 Result.Base = 0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001377 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00001378 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00001379 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00001380 return true;
1381 } else {
1382 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001383 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00001384 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001385 }
1386 }
John McCalle3027922010-08-25 11:45:40 +00001387 case CK_ArrayToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00001388 // FIXME: Support array-to-pointer decay on array rvalues.
1389 if (!SubExpr->isGLValue())
1390 return Error(E);
Richard Smith96e0c102011-11-04 02:25:55 +00001391 if (!EvaluateLValue(SubExpr, Result, Info))
1392 return false;
1393 // The result is a pointer to the first element of the array.
1394 Result.Designator.addIndex(0);
1395 return true;
Richard Smithdd785442011-10-31 20:57:44 +00001396
John McCalle3027922010-08-25 11:45:40 +00001397 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00001398 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001399 }
1400
Richard Smith11562c52011-10-28 17:51:58 +00001401 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00001402}
Chris Lattner05706e882008-07-11 18:11:29 +00001403
Peter Collingbournee9200682011-05-13 03:29:01 +00001404bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +00001405 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +00001406 Builtin::BI__builtin___CFStringMakeConstantString ||
1407 E->isBuiltinCall(Info.Ctx) ==
1408 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +00001409 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00001410
Peter Collingbournee9200682011-05-13 03:29:01 +00001411 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001412}
Chris Lattner05706e882008-07-11 18:11:29 +00001413
1414//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001415// Vector Evaluation
1416//===----------------------------------------------------------------------===//
1417
1418namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001419 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00001420 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1421 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001422 public:
Mike Stump11289f42009-09-09 15:08:12 +00001423
Richard Smith2d406342011-10-22 21:10:00 +00001424 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1425 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001426
Richard Smith2d406342011-10-22 21:10:00 +00001427 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1428 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1429 // FIXME: remove this APValue copy.
1430 Result = APValue(V.data(), V.size());
1431 return true;
1432 }
Richard Smithed5165f2011-11-04 05:33:44 +00001433 bool Success(const CCValue &V, const Expr *E) {
1434 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00001435 Result = V;
1436 return true;
1437 }
1438 bool Error(const Expr *E) { return false; }
1439 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00001440
Richard Smith2d406342011-10-22 21:10:00 +00001441 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00001442 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00001443 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00001444 bool VisitInitListExpr(const InitListExpr *E);
1445 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001446 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001447 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00001448 // shufflevector, ExtVectorElementExpr
1449 // (Note that these require implementing conversions
1450 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001451 };
1452} // end anonymous namespace
1453
1454static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001455 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00001456 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001457}
1458
Richard Smith2d406342011-10-22 21:10:00 +00001459bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1460 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001461 QualType EltTy = VTy->getElementType();
1462 unsigned NElts = VTy->getNumElements();
1463 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +00001464
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001465 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00001466 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001467
Eli Friedmanc757de22011-03-25 00:43:55 +00001468 switch (E->getCastKind()) {
1469 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00001470 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00001471 if (SETy->isIntegerType()) {
1472 APSInt IntResult;
1473 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001474 return Error(E);
1475 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00001476 } else if (SETy->isRealFloatingType()) {
1477 APFloat F(0.0);
1478 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001479 return Error(E);
1480 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00001481 } else {
Richard Smith2d406342011-10-22 21:10:00 +00001482 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001483 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001484
1485 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00001486 SmallVector<APValue, 4> Elts(NElts, Val);
1487 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00001488 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001489 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +00001490 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +00001491 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +00001492 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001493
Eli Friedmanc757de22011-03-25 00:43:55 +00001494 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +00001495 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +00001496
Eli Friedmanc757de22011-03-25 00:43:55 +00001497 APSInt Init;
1498 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001499 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001500
Eli Friedmanc757de22011-03-25 00:43:55 +00001501 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1502 "Vectors must be composed of ints or floats");
1503
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001504 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +00001505 for (unsigned i = 0; i != NElts; ++i) {
1506 APSInt Tmp = Init.extOrTrunc(EltWidth);
1507
1508 if (EltTy->isIntegerType())
1509 Elts.push_back(APValue(Tmp));
1510 else
1511 Elts.push_back(APValue(APFloat(Tmp)));
1512
1513 Init >>= EltWidth;
1514 }
Richard Smith2d406342011-10-22 21:10:00 +00001515 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001516 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001517 default:
Richard Smith11562c52011-10-28 17:51:58 +00001518 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001519 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001520}
1521
Richard Smith2d406342011-10-22 21:10:00 +00001522bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001523VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00001524 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001525 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00001526 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00001527
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001528 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001529 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001530
John McCall875679e2010-06-11 17:54:15 +00001531 // If a vector is initialized with a single element, that value
1532 // becomes every element of the vector, not just the first.
1533 // This is the behavior described in the IBM AltiVec documentation.
1534 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00001535
1536 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00001537 // vector (OpenCL 6.1.6).
1538 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00001539 return Visit(E->getInit(0));
1540
John McCall875679e2010-06-11 17:54:15 +00001541 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001542 if (EltTy->isIntegerType()) {
1543 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00001544 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001545 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001546 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001547 } else {
1548 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00001549 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001550 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001551 InitValue = APValue(f);
1552 }
1553 for (unsigned i = 0; i < NumElements; i++) {
1554 Elements.push_back(InitValue);
1555 }
1556 } else {
1557 for (unsigned i = 0; i < NumElements; i++) {
1558 if (EltTy->isIntegerType()) {
1559 llvm::APSInt sInt(32);
1560 if (i < NumInits) {
1561 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001562 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001563 } else {
1564 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1565 }
1566 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00001567 } else {
John McCall875679e2010-06-11 17:54:15 +00001568 llvm::APFloat f(0.0);
1569 if (i < NumInits) {
1570 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001571 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001572 } else {
1573 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1574 }
1575 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00001576 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001577 }
1578 }
Richard Smith2d406342011-10-22 21:10:00 +00001579 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001580}
1581
Richard Smith2d406342011-10-22 21:10:00 +00001582bool
1583VectorExprEvaluator::ValueInitialization(const Expr *E) {
1584 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00001585 QualType EltTy = VT->getElementType();
1586 APValue ZeroElement;
1587 if (EltTy->isIntegerType())
1588 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1589 else
1590 ZeroElement =
1591 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1592
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001593 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00001594 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001595}
1596
Richard Smith2d406342011-10-22 21:10:00 +00001597bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00001598 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00001599 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001600}
1601
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001602//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001603// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001604//
1605// As a GNU extension, we support casting pointers to sufficiently-wide integer
1606// types and back in constant folding. Integer values are thus represented
1607// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00001608//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001609
1610namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001611class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001612 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001613 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001614public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001615 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001616 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001617
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001618 bool Success(const llvm::APSInt &SI, const Expr *E) {
1619 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001620 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001621 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001622 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001623 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001624 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001625 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001626 return true;
1627 }
1628
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001629 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001630 assert(E->getType()->isIntegralOrEnumerationType() &&
1631 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001632 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001633 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001634 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001635 Result.getInt().setIsUnsigned(
1636 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001637 return true;
1638 }
1639
1640 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001641 assert(E->getType()->isIntegralOrEnumerationType() &&
1642 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001643 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001644 return true;
1645 }
1646
Ken Dyckdbc01912011-03-11 02:13:43 +00001647 bool Success(CharUnits Size, const Expr *E) {
1648 return Success(Size.getQuantity(), E);
1649 }
1650
1651
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001652 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001653 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001654 if (Info.EvalStatus.Diag == 0) {
1655 Info.EvalStatus.DiagLoc = L;
1656 Info.EvalStatus.Diag = D;
1657 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001658 }
Chris Lattner99415702008-07-12 00:14:42 +00001659 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001660 }
Mike Stump11289f42009-09-09 15:08:12 +00001661
Richard Smith0b0a0b62011-10-29 20:57:55 +00001662 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00001663 if (V.isLValue()) {
1664 Result = V;
1665 return true;
1666 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001667 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001668 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001669 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001670 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001671 }
Mike Stump11289f42009-09-09 15:08:12 +00001672
Richard Smith4ce706a2011-10-11 21:43:33 +00001673 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1674
Peter Collingbournee9200682011-05-13 03:29:01 +00001675 //===--------------------------------------------------------------------===//
1676 // Visitor Methods
1677 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001678
Chris Lattner7174bf32008-07-12 00:38:25 +00001679 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001680 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001681 }
1682 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001683 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001684 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001685
1686 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1687 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001688 if (CheckReferencedDecl(E, E->getDecl()))
1689 return true;
1690
1691 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001692 }
1693 bool VisitMemberExpr(const MemberExpr *E) {
1694 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00001695 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001696 return true;
1697 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001698
1699 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001700 }
1701
Peter Collingbournee9200682011-05-13 03:29:01 +00001702 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001703 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001704 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001705 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001706
Peter Collingbournee9200682011-05-13 03:29:01 +00001707 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001708 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001709
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001710 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001711 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001712 }
Mike Stump11289f42009-09-09 15:08:12 +00001713
Richard Smith4ce706a2011-10-11 21:43:33 +00001714 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001715 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001716 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001717 }
1718
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001719 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001720 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001721 }
1722
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001723 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1724 return Success(E->getValue(), E);
1725 }
1726
John Wiegley6242b6a2011-04-28 00:16:57 +00001727 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1728 return Success(E->getValue(), E);
1729 }
1730
John Wiegleyf9f65842011-04-25 06:54:41 +00001731 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1732 return Success(E->getValue(), E);
1733 }
1734
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001735 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001736 bool VisitUnaryImag(const UnaryOperator *E);
1737
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001738 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001739 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001740
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001741private:
Ken Dyck160146e2010-01-27 17:10:57 +00001742 CharUnits GetAlignOfExpr(const Expr *E);
1743 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001744 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001745 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001746 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001747};
Chris Lattner05706e882008-07-11 18:11:29 +00001748} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001749
Richard Smith11562c52011-10-28 17:51:58 +00001750/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1751/// produce either the integer value or a pointer.
1752///
1753/// GCC has a heinous extension which folds casts between pointer types and
1754/// pointer-sized integral types. We support this by allowing the evaluation of
1755/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1756/// Some simple arithmetic on such values is supported (they are treated much
1757/// like char*).
Richard Smith0b0a0b62011-10-29 20:57:55 +00001758static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
1759 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001760 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001761 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001762}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001763
Daniel Dunbarce399542009-02-20 18:22:23 +00001764static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001765 CCValue Val;
Daniel Dunbarce399542009-02-20 18:22:23 +00001766 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1767 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001768 Result = Val.getInt();
1769 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001770}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001771
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001772bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001773 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001774 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001775 // Check for signedness/width mismatches between E type and ECD value.
1776 bool SameSign = (ECD->getInitVal().isSigned()
1777 == E->getType()->isSignedIntegerOrEnumerationType());
1778 bool SameWidth = (ECD->getInitVal().getBitWidth()
1779 == Info.Ctx.getIntWidth(E->getType()));
1780 if (SameSign && SameWidth)
1781 return Success(ECD->getInitVal(), E);
1782 else {
1783 // Get rid of mismatch (otherwise Success assertions will fail)
1784 // by computing a new value matching the type of E.
1785 llvm::APSInt Val = ECD->getInitVal();
1786 if (!SameSign)
1787 Val.setIsSigned(!ECD->getInitVal().isSigned());
1788 if (!SameWidth)
1789 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1790 return Success(Val, E);
1791 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001792 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001793 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001794}
1795
Chris Lattner86ee2862008-10-06 06:40:35 +00001796/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1797/// as GCC.
1798static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1799 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001800 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001801 enum gcc_type_class {
1802 no_type_class = -1,
1803 void_type_class, integer_type_class, char_type_class,
1804 enumeral_type_class, boolean_type_class,
1805 pointer_type_class, reference_type_class, offset_type_class,
1806 real_type_class, complex_type_class,
1807 function_type_class, method_type_class,
1808 record_type_class, union_type_class,
1809 array_type_class, string_type_class,
1810 lang_type_class
1811 };
Mike Stump11289f42009-09-09 15:08:12 +00001812
1813 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001814 // ideal, however it is what gcc does.
1815 if (E->getNumArgs() == 0)
1816 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001817
Chris Lattner86ee2862008-10-06 06:40:35 +00001818 QualType ArgTy = E->getArg(0)->getType();
1819 if (ArgTy->isVoidType())
1820 return void_type_class;
1821 else if (ArgTy->isEnumeralType())
1822 return enumeral_type_class;
1823 else if (ArgTy->isBooleanType())
1824 return boolean_type_class;
1825 else if (ArgTy->isCharType())
1826 return string_type_class; // gcc doesn't appear to use char_type_class
1827 else if (ArgTy->isIntegerType())
1828 return integer_type_class;
1829 else if (ArgTy->isPointerType())
1830 return pointer_type_class;
1831 else if (ArgTy->isReferenceType())
1832 return reference_type_class;
1833 else if (ArgTy->isRealType())
1834 return real_type_class;
1835 else if (ArgTy->isComplexType())
1836 return complex_type_class;
1837 else if (ArgTy->isFunctionType())
1838 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001839 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001840 return record_type_class;
1841 else if (ArgTy->isUnionType())
1842 return union_type_class;
1843 else if (ArgTy->isArrayType())
1844 return array_type_class;
1845 else if (ArgTy->isUnionType())
1846 return union_type_class;
1847 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001848 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001849 return -1;
1850}
1851
John McCall95007602010-05-10 23:27:23 +00001852/// Retrieves the "underlying object type" of the given expression,
1853/// as used by __builtin_object_size.
1854QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1855 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1856 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1857 return VD->getType();
1858 } else if (isa<CompoundLiteralExpr>(E)) {
1859 return E->getType();
1860 }
1861
1862 return QualType();
1863}
1864
Peter Collingbournee9200682011-05-13 03:29:01 +00001865bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001866 // TODO: Perhaps we should let LLVM lower this?
1867 LValue Base;
1868 if (!EvaluatePointer(E->getArg(0), Base, Info))
1869 return false;
1870
1871 // If we can prove the base is null, lower to zero now.
1872 const Expr *LVBase = Base.getLValueBase();
1873 if (!LVBase) return Success(0, E);
1874
1875 QualType T = GetObjectType(LVBase);
1876 if (T.isNull() ||
1877 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001878 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001879 T->isVariablyModifiedType() ||
1880 T->isDependentType())
1881 return false;
1882
1883 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1884 CharUnits Offset = Base.getLValueOffset();
1885
1886 if (!Offset.isNegative() && Offset <= Size)
1887 Size -= Offset;
1888 else
1889 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001890 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001891}
1892
Peter Collingbournee9200682011-05-13 03:29:01 +00001893bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001894 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001895 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001896 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001897
1898 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001899 if (TryEvaluateBuiltinObjectSize(E))
1900 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001901
Eric Christopher99469702010-01-19 22:58:35 +00001902 // If evaluating the argument has side-effects we can't determine
1903 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001904 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001905 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001906 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001907 return Success(0, E);
1908 }
Mike Stump876387b2009-10-27 22:09:17 +00001909
Mike Stump722cedf2009-10-26 18:35:08 +00001910 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1911 }
1912
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001913 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001914 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001915
Anders Carlsson4c76e932008-11-24 04:21:33 +00001916 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001917 // __builtin_constant_p always has one operand: it returns true if that
1918 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001919 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001920
1921 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001922 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001923 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001924 return Success(Operand, E);
1925 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001926
1927 case Builtin::BI__builtin_expect:
1928 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001929
1930 case Builtin::BIstrlen:
1931 case Builtin::BI__builtin_strlen:
1932 // As an extension, we support strlen() and __builtin_strlen() as constant
1933 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001934 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001935 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1936 // The string literal may have embedded null characters. Find the first
1937 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001938 StringRef Str = S->getString();
1939 StringRef::size_type Pos = Str.find(0);
1940 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001941 Str = Str.substr(0, Pos);
1942
1943 return Success(Str.size(), E);
1944 }
1945
1946 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001947
1948 case Builtin::BI__atomic_is_lock_free: {
1949 APSInt SizeVal;
1950 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1951 return false;
1952
1953 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1954 // of two less than the maximum inline atomic width, we know it is
1955 // lock-free. If the size isn't a power of two, or greater than the
1956 // maximum alignment where we promote atomics, we know it is not lock-free
1957 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1958 // the answer can only be determined at runtime; for example, 16-byte
1959 // atomics have lock-free implementations on some, but not all,
1960 // x86-64 processors.
1961
1962 // Check power-of-two.
1963 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1964 if (!Size.isPowerOfTwo())
1965#if 0
1966 // FIXME: Suppress this folding until the ABI for the promotion width
1967 // settles.
1968 return Success(0, E);
1969#else
1970 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1971#endif
1972
1973#if 0
1974 // Check against promotion width.
1975 // FIXME: Suppress this folding until the ABI for the promotion width
1976 // settles.
1977 unsigned PromoteWidthBits =
1978 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1979 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1980 return Success(0, E);
1981#endif
1982
1983 // Check against inlining width.
1984 unsigned InlineWidthBits =
1985 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1986 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1987 return Success(1, E);
1988
1989 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1990 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001991 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001992}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001993
Richard Smith8b3497e2011-10-31 01:37:14 +00001994static bool HasSameBase(const LValue &A, const LValue &B) {
1995 if (!A.getLValueBase())
1996 return !B.getLValueBase();
1997 if (!B.getLValueBase())
1998 return false;
1999
2000 if (A.getLValueBase() != B.getLValueBase()) {
2001 const Decl *ADecl = GetLValueBaseDecl(A);
2002 if (!ADecl)
2003 return false;
2004 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00002005 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00002006 return false;
2007 }
2008
2009 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00002010 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00002011}
2012
Chris Lattnere13042c2008-07-11 19:10:17 +00002013bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002014 if (E->isAssignmentOp())
2015 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
2016
John McCalle3027922010-08-25 11:45:40 +00002017 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002018 VisitIgnoredValue(E->getLHS());
2019 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00002020 }
2021
2022 if (E->isLogicalOp()) {
2023 // These need to be handled specially because the operands aren't
2024 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00002025 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00002026
Richard Smith11562c52011-10-28 17:51:58 +00002027 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00002028 // We were able to evaluate the LHS, see if we can get away with not
2029 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00002030 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002031 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00002032
Richard Smith11562c52011-10-28 17:51:58 +00002033 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00002034 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002035 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00002036 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002037 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00002038 }
2039 } else {
Richard Smith11562c52011-10-28 17:51:58 +00002040 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00002041 // We can't evaluate the LHS; however, sometimes the result
2042 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00002043 if (rhsResult == (E->getOpcode() == BO_LOr) ||
2044 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002045 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00002046 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00002047 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002048
2049 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00002050 }
2051 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00002052 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00002053
Eli Friedman5a332ea2008-11-13 06:09:17 +00002054 return false;
2055 }
2056
Anders Carlssonacc79812008-11-16 07:17:21 +00002057 QualType LHSTy = E->getLHS()->getType();
2058 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002059
2060 if (LHSTy->isAnyComplexType()) {
2061 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00002062 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002063
2064 if (!EvaluateComplex(E->getLHS(), LHS, Info))
2065 return false;
2066
2067 if (!EvaluateComplex(E->getRHS(), RHS, Info))
2068 return false;
2069
2070 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00002071 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002072 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00002073 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002074 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
2075
John McCalle3027922010-08-25 11:45:40 +00002076 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002077 return Success((CR_r == APFloat::cmpEqual &&
2078 CR_i == APFloat::cmpEqual), E);
2079 else {
John McCalle3027922010-08-25 11:45:40 +00002080 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002081 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00002082 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00002083 CR_r == APFloat::cmpLessThan ||
2084 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00002085 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00002086 CR_i == APFloat::cmpLessThan ||
2087 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002088 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002089 } else {
John McCalle3027922010-08-25 11:45:40 +00002090 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002091 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
2092 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
2093 else {
John McCalle3027922010-08-25 11:45:40 +00002094 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002095 "Invalid compex comparison.");
2096 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
2097 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
2098 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002099 }
2100 }
Mike Stump11289f42009-09-09 15:08:12 +00002101
Anders Carlssonacc79812008-11-16 07:17:21 +00002102 if (LHSTy->isRealFloatingType() &&
2103 RHSTy->isRealFloatingType()) {
2104 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00002105
Anders Carlssonacc79812008-11-16 07:17:21 +00002106 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2107 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002108
Anders Carlssonacc79812008-11-16 07:17:21 +00002109 if (!EvaluateFloat(E->getLHS(), LHS, Info))
2110 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002111
Anders Carlssonacc79812008-11-16 07:17:21 +00002112 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00002113
Anders Carlssonacc79812008-11-16 07:17:21 +00002114 switch (E->getOpcode()) {
2115 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002116 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00002117 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002118 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00002119 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002120 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00002121 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002122 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00002123 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00002124 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002125 E);
John McCalle3027922010-08-25 11:45:40 +00002126 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002127 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00002128 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00002129 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00002130 || CR == APFloat::cmpLessThan
2131 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00002132 }
Anders Carlssonacc79812008-11-16 07:17:21 +00002133 }
Mike Stump11289f42009-09-09 15:08:12 +00002134
Eli Friedmana38da572009-04-28 19:17:36 +00002135 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00002136 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00002137 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002138 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
2139 return false;
Eli Friedman64004332009-03-23 04:38:34 +00002140
John McCall45d55e42010-05-07 21:00:08 +00002141 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002142 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
2143 return false;
Eli Friedman64004332009-03-23 04:38:34 +00002144
Richard Smith8b3497e2011-10-31 01:37:14 +00002145 // Reject differing bases from the normal codepath; we special-case
2146 // comparisons to null.
2147 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00002148 // Inequalities and subtractions between unrelated pointers have
2149 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00002150 if (!E->isEqualityOp())
2151 return false;
Eli Friedmanc6be94b2011-10-31 22:28:05 +00002152 // A constant address may compare equal to the address of a symbol.
2153 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00002154 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00002155 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
2156 (!RHSValue.Base && !RHSValue.Offset.isZero()))
2157 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002158 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00002159 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00002160 // distinct. However, we do know that the address of a literal will be
2161 // non-null.
2162 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
2163 LHSValue.Base && RHSValue.Base)
Eli Friedman334046a2009-06-14 02:17:33 +00002164 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002165 // We can't tell whether weak symbols will end up pointing to the same
2166 // object.
2167 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Eli Friedman334046a2009-06-14 02:17:33 +00002168 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002169 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00002170 // (Note that clang defaults to -fmerge-all-constants, which can
2171 // lead to inconsistent results for comparisons involving the address
2172 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00002173 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00002174 }
Eli Friedman64004332009-03-23 04:38:34 +00002175
John McCalle3027922010-08-25 11:45:40 +00002176 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00002177 QualType Type = E->getLHS()->getType();
2178 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002179
Ken Dyck02990832010-01-15 12:37:54 +00002180 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00002181 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00002182 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00002183
Ken Dyck02990832010-01-15 12:37:54 +00002184 CharUnits Diff = LHSValue.getLValueOffset() -
2185 RHSValue.getLValueOffset();
2186 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002187 }
Richard Smith8b3497e2011-10-31 01:37:14 +00002188
2189 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
2190 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
2191 switch (E->getOpcode()) {
2192 default: llvm_unreachable("missing comparison operator");
2193 case BO_LT: return Success(LHSOffset < RHSOffset, E);
2194 case BO_GT: return Success(LHSOffset > RHSOffset, E);
2195 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
2196 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
2197 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
2198 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002199 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002200 }
2201 }
Douglas Gregorb90df602010-06-16 00:17:44 +00002202 if (!LHSTy->isIntegralOrEnumerationType() ||
2203 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002204 // We can't continue from here for non-integral types, and they
2205 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00002206 return false;
2207 }
2208
Anders Carlsson9c181652008-07-08 14:35:21 +00002209 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002210 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00002211 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00002212 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00002213
Richard Smith11562c52011-10-28 17:51:58 +00002214 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002215 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002216 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00002217
2218 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00002219 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00002220 CharUnits AdditionalOffset = CharUnits::fromQuantity(
2221 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00002222 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00002223 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00002224 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00002225 LHSVal.getLValueOffset() -= AdditionalOffset;
2226 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00002227 return true;
2228 }
2229
2230 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00002231 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00002232 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002233 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
2234 LHSVal.getInt().getZExtValue());
2235 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00002236 return true;
2237 }
2238
2239 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00002240 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00002241 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00002242
Richard Smith11562c52011-10-28 17:51:58 +00002243 APSInt &LHS = LHSVal.getInt();
2244 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00002245
Anders Carlsson9c181652008-07-08 14:35:21 +00002246 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002247 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002248 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00002249 case BO_Mul: return Success(LHS * RHS, E);
2250 case BO_Add: return Success(LHS + RHS, E);
2251 case BO_Sub: return Success(LHS - RHS, E);
2252 case BO_And: return Success(LHS & RHS, E);
2253 case BO_Xor: return Success(LHS ^ RHS, E);
2254 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002255 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00002256 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002257 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002258 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002259 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00002260 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002261 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002262 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002263 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00002264 // During constant-folding, a negative shift is an opposite shift.
2265 if (RHS.isSigned() && RHS.isNegative()) {
2266 RHS = -RHS;
2267 goto shift_right;
2268 }
2269
2270 shift_left:
2271 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00002272 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2273 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002274 }
John McCalle3027922010-08-25 11:45:40 +00002275 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00002276 // During constant-folding, a negative shift is an opposite shift.
2277 if (RHS.isSigned() && RHS.isNegative()) {
2278 RHS = -RHS;
2279 goto shift_left;
2280 }
2281
2282 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00002283 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00002284 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2285 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002286 }
Mike Stump11289f42009-09-09 15:08:12 +00002287
Richard Smith11562c52011-10-28 17:51:58 +00002288 case BO_LT: return Success(LHS < RHS, E);
2289 case BO_GT: return Success(LHS > RHS, E);
2290 case BO_LE: return Success(LHS <= RHS, E);
2291 case BO_GE: return Success(LHS >= RHS, E);
2292 case BO_EQ: return Success(LHS == RHS, E);
2293 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00002294 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002295}
2296
Ken Dyck160146e2010-01-27 17:10:57 +00002297CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002298 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2299 // the result is the size of the referenced type."
2300 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2301 // result shall be the alignment of the referenced type."
2302 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2303 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00002304
2305 // __alignof is defined to return the preferred alignment.
2306 return Info.Ctx.toCharUnitsFromBits(
2307 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00002308}
2309
Ken Dyck160146e2010-01-27 17:10:57 +00002310CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00002311 E = E->IgnoreParens();
2312
2313 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00002314 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00002315 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002316 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2317 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00002318
Chris Lattner68061312009-01-24 21:53:27 +00002319 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002320 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2321 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00002322
Chris Lattner24aeeab2009-01-24 21:09:06 +00002323 return GetAlignOfType(E->getType());
2324}
2325
2326
Peter Collingbournee190dee2011-03-11 19:24:49 +00002327/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2328/// a result as the expression's type.
2329bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2330 const UnaryExprOrTypeTraitExpr *E) {
2331 switch(E->getKind()) {
2332 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00002333 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00002334 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002335 else
Ken Dyckdbc01912011-03-11 02:13:43 +00002336 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002337 }
Eli Friedman64004332009-03-23 04:38:34 +00002338
Peter Collingbournee190dee2011-03-11 19:24:49 +00002339 case UETT_VecStep: {
2340 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00002341
Peter Collingbournee190dee2011-03-11 19:24:49 +00002342 if (Ty->isVectorType()) {
2343 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00002344
Peter Collingbournee190dee2011-03-11 19:24:49 +00002345 // The vec_step built-in functions that take a 3-component
2346 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2347 if (n == 3)
2348 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002349
Peter Collingbournee190dee2011-03-11 19:24:49 +00002350 return Success(n, E);
2351 } else
2352 return Success(1, E);
2353 }
2354
2355 case UETT_SizeOf: {
2356 QualType SrcTy = E->getTypeOfArgument();
2357 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2358 // the result is the size of the referenced type."
2359 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2360 // result shall be the alignment of the referenced type."
2361 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2362 SrcTy = Ref->getPointeeType();
2363
2364 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2365 // extension.
2366 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
2367 return Success(1, E);
2368
2369 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2370 if (!SrcTy->isConstantSizeType())
2371 return false;
2372
2373 // Get information about the size.
2374 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
2375 }
2376 }
2377
2378 llvm_unreachable("unknown expr/type trait");
2379 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002380}
2381
Peter Collingbournee9200682011-05-13 03:29:01 +00002382bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00002383 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00002384 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00002385 if (n == 0)
2386 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002387 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00002388 for (unsigned i = 0; i != n; ++i) {
2389 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
2390 switch (ON.getKind()) {
2391 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00002392 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00002393 APSInt IdxResult;
2394 if (!EvaluateInteger(Idx, IdxResult, Info))
2395 return false;
2396 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
2397 if (!AT)
2398 return false;
2399 CurrentType = AT->getElementType();
2400 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
2401 Result += IdxResult.getSExtValue() * ElementSize;
2402 break;
2403 }
2404
2405 case OffsetOfExpr::OffsetOfNode::Field: {
2406 FieldDecl *MemberDecl = ON.getField();
2407 const RecordType *RT = CurrentType->getAs<RecordType>();
2408 if (!RT)
2409 return false;
2410 RecordDecl *RD = RT->getDecl();
2411 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00002412 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00002413 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002414 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00002415 CurrentType = MemberDecl->getType().getNonReferenceType();
2416 break;
2417 }
2418
2419 case OffsetOfExpr::OffsetOfNode::Identifier:
2420 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00002421 return false;
2422
2423 case OffsetOfExpr::OffsetOfNode::Base: {
2424 CXXBaseSpecifier *BaseSpec = ON.getBase();
2425 if (BaseSpec->isVirtual())
2426 return false;
2427
2428 // Find the layout of the class whose base we are looking into.
2429 const RecordType *RT = CurrentType->getAs<RecordType>();
2430 if (!RT)
2431 return false;
2432 RecordDecl *RD = RT->getDecl();
2433 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
2434
2435 // Find the base class itself.
2436 CurrentType = BaseSpec->getType();
2437 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2438 if (!BaseRT)
2439 return false;
2440
2441 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00002442 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00002443 break;
2444 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002445 }
2446 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002447 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00002448}
2449
Chris Lattnere13042c2008-07-11 19:10:17 +00002450bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002451 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002452 // LNot's operand isn't necessarily an integer, so we handle it specially.
2453 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00002454 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00002455 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002456 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00002457 }
2458
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002459 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00002460 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002461 return false;
2462
Richard Smith11562c52011-10-28 17:51:58 +00002463 // Get the operand value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002464 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00002465 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00002466 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002467
Chris Lattnerf09ad162008-07-11 22:15:16 +00002468 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002469 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00002470 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2471 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002472 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00002473 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00002474 // FIXME: Should extension allow i-c-e extension expressions in its scope?
2475 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00002476 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002477 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00002478 // The result is just the value.
2479 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002480 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00002481 if (!Val.isInt()) return false;
2482 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00002483 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00002484 if (!Val.isInt()) return false;
2485 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00002486 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002487}
Mike Stump11289f42009-09-09 15:08:12 +00002488
Chris Lattner477c4be2008-07-12 01:15:53 +00002489/// HandleCast - This is used to evaluate implicit or explicit casts where the
2490/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00002491bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
2492 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002493 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00002494 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002495
Eli Friedmanc757de22011-03-25 00:43:55 +00002496 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00002497 case CK_BaseToDerived:
2498 case CK_DerivedToBase:
2499 case CK_UncheckedDerivedToBase:
2500 case CK_Dynamic:
2501 case CK_ToUnion:
2502 case CK_ArrayToPointerDecay:
2503 case CK_FunctionToPointerDecay:
2504 case CK_NullToPointer:
2505 case CK_NullToMemberPointer:
2506 case CK_BaseToDerivedMemberPointer:
2507 case CK_DerivedToBaseMemberPointer:
2508 case CK_ConstructorConversion:
2509 case CK_IntegralToPointer:
2510 case CK_ToVoid:
2511 case CK_VectorSplat:
2512 case CK_IntegralToFloating:
2513 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002514 case CK_CPointerToObjCPointerCast:
2515 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002516 case CK_AnyPointerToBlockPointerCast:
2517 case CK_ObjCObjectLValueCast:
2518 case CK_FloatingRealToComplex:
2519 case CK_FloatingComplexToReal:
2520 case CK_FloatingComplexCast:
2521 case CK_FloatingComplexToIntegralComplex:
2522 case CK_IntegralRealToComplex:
2523 case CK_IntegralComplexCast:
2524 case CK_IntegralComplexToFloatingComplex:
2525 llvm_unreachable("invalid cast kind for integral value");
2526
Eli Friedman9faf2f92011-03-25 19:07:11 +00002527 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002528 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00002529 case CK_LValueBitCast:
2530 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00002531 case CK_ARCProduceObject:
2532 case CK_ARCConsumeObject:
2533 case CK_ARCReclaimReturnedObject:
2534 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00002535 return false;
2536
2537 case CK_LValueToRValue:
2538 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002539 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002540
2541 case CK_MemberPointerToBoolean:
2542 case CK_PointerToBoolean:
2543 case CK_IntegralToBoolean:
2544 case CK_FloatingToBoolean:
2545 case CK_FloatingComplexToBoolean:
2546 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002547 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002548 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002549 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002550 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002551 }
2552
Eli Friedmanc757de22011-03-25 00:43:55 +00002553 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00002554 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00002555 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002556
Eli Friedman742421e2009-02-20 01:15:07 +00002557 if (!Result.isInt()) {
2558 // Only allow casts of lvalues if they are lossless.
2559 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2560 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002561
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002562 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002563 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00002564 }
Mike Stump11289f42009-09-09 15:08:12 +00002565
Eli Friedmanc757de22011-03-25 00:43:55 +00002566 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00002567 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00002568 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00002569 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002570
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002571 if (LV.getLValueBase()) {
2572 // Only allow based lvalue casts if they are lossless.
2573 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2574 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002575
John McCall45d55e42010-05-07 21:00:08 +00002576 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002577 return true;
2578 }
2579
Ken Dyck02990832010-01-15 12:37:54 +00002580 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2581 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002582 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002583 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002584
Eli Friedmanc757de22011-03-25 00:43:55 +00002585 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00002586 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002587 if (!EvaluateComplex(SubExpr, C, Info))
2588 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00002589 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002590 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00002591
Eli Friedmanc757de22011-03-25 00:43:55 +00002592 case CK_FloatingToIntegral: {
2593 APFloat F(0.0);
2594 if (!EvaluateFloat(SubExpr, F, Info))
2595 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00002596
Eli Friedmanc757de22011-03-25 00:43:55 +00002597 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2598 }
2599 }
Mike Stump11289f42009-09-09 15:08:12 +00002600
Eli Friedmanc757de22011-03-25 00:43:55 +00002601 llvm_unreachable("unknown cast resulting in integral value");
2602 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002603}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002604
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002605bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2606 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002607 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002608 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2609 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2610 return Success(LV.getComplexIntReal(), E);
2611 }
2612
2613 return Visit(E->getSubExpr());
2614}
2615
Eli Friedman4e7a2412009-02-27 04:45:43 +00002616bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002617 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002618 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002619 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2620 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2621 return Success(LV.getComplexIntImag(), E);
2622 }
2623
Richard Smith4a678122011-10-24 18:44:57 +00002624 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00002625 return Success(0, E);
2626}
2627
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002628bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2629 return Success(E->getPackLength(), E);
2630}
2631
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002632bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2633 return Success(E->getValue(), E);
2634}
2635
Chris Lattner05706e882008-07-11 18:11:29 +00002636//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002637// Float Evaluation
2638//===----------------------------------------------------------------------===//
2639
2640namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002641class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002642 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002643 APFloat &Result;
2644public:
2645 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002646 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002647
Richard Smith0b0a0b62011-10-29 20:57:55 +00002648 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002649 Result = V.getFloat();
2650 return true;
2651 }
2652 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002653 return false;
2654 }
2655
Richard Smith4ce706a2011-10-11 21:43:33 +00002656 bool ValueInitialization(const Expr *E) {
2657 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2658 return true;
2659 }
2660
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002661 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002662
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002663 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002664 bool VisitBinaryOperator(const BinaryOperator *E);
2665 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002666 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002667
John McCallb1fb0d32010-05-07 22:08:54 +00002668 bool VisitUnaryReal(const UnaryOperator *E);
2669 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002670
John McCallb1fb0d32010-05-07 22:08:54 +00002671 // FIXME: Missing: array subscript of vector, member of vector,
2672 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002673};
2674} // end anonymous namespace
2675
2676static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002677 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002678 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002679}
2680
Jay Foad39c79802011-01-12 09:06:06 +00002681static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002682 QualType ResultTy,
2683 const Expr *Arg,
2684 bool SNaN,
2685 llvm::APFloat &Result) {
2686 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2687 if (!S) return false;
2688
2689 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2690
2691 llvm::APInt fill;
2692
2693 // Treat empty strings as if they were zero.
2694 if (S->getString().empty())
2695 fill = llvm::APInt(32, 0);
2696 else if (S->getString().getAsInteger(0, fill))
2697 return false;
2698
2699 if (SNaN)
2700 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2701 else
2702 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2703 return true;
2704}
2705
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002706bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002707 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002708 default:
2709 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2710
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002711 case Builtin::BI__builtin_huge_val:
2712 case Builtin::BI__builtin_huge_valf:
2713 case Builtin::BI__builtin_huge_vall:
2714 case Builtin::BI__builtin_inf:
2715 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002716 case Builtin::BI__builtin_infl: {
2717 const llvm::fltSemantics &Sem =
2718 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002719 Result = llvm::APFloat::getInf(Sem);
2720 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002721 }
Mike Stump11289f42009-09-09 15:08:12 +00002722
John McCall16291492010-02-28 13:00:19 +00002723 case Builtin::BI__builtin_nans:
2724 case Builtin::BI__builtin_nansf:
2725 case Builtin::BI__builtin_nansl:
2726 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2727 true, Result);
2728
Chris Lattner0b7282e2008-10-06 06:31:58 +00002729 case Builtin::BI__builtin_nan:
2730 case Builtin::BI__builtin_nanf:
2731 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002732 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002733 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002734 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2735 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002736
2737 case Builtin::BI__builtin_fabs:
2738 case Builtin::BI__builtin_fabsf:
2739 case Builtin::BI__builtin_fabsl:
2740 if (!EvaluateFloat(E->getArg(0), Result, Info))
2741 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002742
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002743 if (Result.isNegative())
2744 Result.changeSign();
2745 return true;
2746
Mike Stump11289f42009-09-09 15:08:12 +00002747 case Builtin::BI__builtin_copysign:
2748 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002749 case Builtin::BI__builtin_copysignl: {
2750 APFloat RHS(0.);
2751 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2752 !EvaluateFloat(E->getArg(1), RHS, Info))
2753 return false;
2754 Result.copySign(RHS);
2755 return true;
2756 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002757 }
2758}
2759
John McCallb1fb0d32010-05-07 22:08:54 +00002760bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002761 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2762 ComplexValue CV;
2763 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2764 return false;
2765 Result = CV.FloatReal;
2766 return true;
2767 }
2768
2769 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002770}
2771
2772bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002773 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2774 ComplexValue CV;
2775 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2776 return false;
2777 Result = CV.FloatImag;
2778 return true;
2779 }
2780
Richard Smith4a678122011-10-24 18:44:57 +00002781 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00002782 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2783 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002784 return true;
2785}
2786
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002787bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002788 switch (E->getOpcode()) {
2789 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002790 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00002791 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00002792 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00002793 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2794 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002795 Result.changeSign();
2796 return true;
2797 }
2798}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002799
Eli Friedman24c01542008-08-22 00:06:13 +00002800bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002801 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002802 VisitIgnoredValue(E->getLHS());
2803 return Visit(E->getRHS());
Eli Friedman141fbf32009-11-16 04:25:37 +00002804 }
2805
Richard Smith472d4952011-10-28 23:26:52 +00002806 // We can't evaluate pointer-to-member operations or assignments.
2807 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlssona5df61a2010-10-31 01:21:47 +00002808 return false;
2809
Eli Friedman24c01542008-08-22 00:06:13 +00002810 // FIXME: Diagnostics? I really don't understand how the warnings
2811 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002812 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002813 if (!EvaluateFloat(E->getLHS(), Result, Info))
2814 return false;
2815 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2816 return false;
2817
2818 switch (E->getOpcode()) {
2819 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002820 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002821 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2822 return true;
John McCalle3027922010-08-25 11:45:40 +00002823 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002824 Result.add(RHS, APFloat::rmNearestTiesToEven);
2825 return true;
John McCalle3027922010-08-25 11:45:40 +00002826 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002827 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2828 return true;
John McCalle3027922010-08-25 11:45:40 +00002829 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002830 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2831 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002832 }
2833}
2834
2835bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2836 Result = E->getValue();
2837 return true;
2838}
2839
Peter Collingbournee9200682011-05-13 03:29:01 +00002840bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2841 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002842
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002843 switch (E->getCastKind()) {
2844 default:
Richard Smith11562c52011-10-28 17:51:58 +00002845 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002846
2847 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002848 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002849 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002850 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002851 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002852 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002853 return true;
2854 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002855
2856 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002857 if (!Visit(SubExpr))
2858 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002859 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2860 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002861 return true;
2862 }
John McCalld7646252010-11-14 08:17:51 +00002863
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002864 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002865 ComplexValue V;
2866 if (!EvaluateComplex(SubExpr, V, Info))
2867 return false;
2868 Result = V.getComplexFloatReal();
2869 return true;
2870 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002871 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002872
2873 return false;
2874}
2875
Eli Friedman24c01542008-08-22 00:06:13 +00002876//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002877// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002878//===----------------------------------------------------------------------===//
2879
2880namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002881class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002882 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002883 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002884
Anders Carlsson537969c2008-11-16 20:27:53 +00002885public:
John McCall93d91dc2010-05-07 17:22:02 +00002886 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002887 : ExprEvaluatorBaseTy(info), Result(Result) {}
2888
Richard Smith0b0a0b62011-10-29 20:57:55 +00002889 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002890 Result.setFrom(V);
2891 return true;
2892 }
2893 bool Error(const Expr *E) {
2894 return false;
2895 }
Mike Stump11289f42009-09-09 15:08:12 +00002896
Anders Carlsson537969c2008-11-16 20:27:53 +00002897 //===--------------------------------------------------------------------===//
2898 // Visitor Methods
2899 //===--------------------------------------------------------------------===//
2900
Peter Collingbournee9200682011-05-13 03:29:01 +00002901 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002902
Peter Collingbournee9200682011-05-13 03:29:01 +00002903 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002904
John McCall93d91dc2010-05-07 17:22:02 +00002905 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002906 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002907 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002908};
2909} // end anonymous namespace
2910
John McCall93d91dc2010-05-07 17:22:02 +00002911static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2912 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002913 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002914 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002915}
2916
Peter Collingbournee9200682011-05-13 03:29:01 +00002917bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2918 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002919
2920 if (SubExpr->getType()->isRealFloatingType()) {
2921 Result.makeComplexFloat();
2922 APFloat &Imag = Result.FloatImag;
2923 if (!EvaluateFloat(SubExpr, Imag, Info))
2924 return false;
2925
2926 Result.FloatReal = APFloat(Imag.getSemantics());
2927 return true;
2928 } else {
2929 assert(SubExpr->getType()->isIntegerType() &&
2930 "Unexpected imaginary literal.");
2931
2932 Result.makeComplexInt();
2933 APSInt &Imag = Result.IntImag;
2934 if (!EvaluateInteger(SubExpr, Imag, Info))
2935 return false;
2936
2937 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2938 return true;
2939 }
2940}
2941
Peter Collingbournee9200682011-05-13 03:29:01 +00002942bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002943
John McCallfcef3cf2010-12-14 17:51:41 +00002944 switch (E->getCastKind()) {
2945 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002946 case CK_BaseToDerived:
2947 case CK_DerivedToBase:
2948 case CK_UncheckedDerivedToBase:
2949 case CK_Dynamic:
2950 case CK_ToUnion:
2951 case CK_ArrayToPointerDecay:
2952 case CK_FunctionToPointerDecay:
2953 case CK_NullToPointer:
2954 case CK_NullToMemberPointer:
2955 case CK_BaseToDerivedMemberPointer:
2956 case CK_DerivedToBaseMemberPointer:
2957 case CK_MemberPointerToBoolean:
2958 case CK_ConstructorConversion:
2959 case CK_IntegralToPointer:
2960 case CK_PointerToIntegral:
2961 case CK_PointerToBoolean:
2962 case CK_ToVoid:
2963 case CK_VectorSplat:
2964 case CK_IntegralCast:
2965 case CK_IntegralToBoolean:
2966 case CK_IntegralToFloating:
2967 case CK_FloatingToIntegral:
2968 case CK_FloatingToBoolean:
2969 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002970 case CK_CPointerToObjCPointerCast:
2971 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002972 case CK_AnyPointerToBlockPointerCast:
2973 case CK_ObjCObjectLValueCast:
2974 case CK_FloatingComplexToReal:
2975 case CK_FloatingComplexToBoolean:
2976 case CK_IntegralComplexToReal:
2977 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002978 case CK_ARCProduceObject:
2979 case CK_ARCConsumeObject:
2980 case CK_ARCReclaimReturnedObject:
2981 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002982 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002983
John McCallfcef3cf2010-12-14 17:51:41 +00002984 case CK_LValueToRValue:
2985 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002986 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00002987
2988 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00002989 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002990 case CK_UserDefinedConversion:
2991 return false;
2992
2993 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002994 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002995 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002996 return false;
2997
John McCallfcef3cf2010-12-14 17:51:41 +00002998 Result.makeComplexFloat();
2999 Result.FloatImag = APFloat(Real.getSemantics());
3000 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003001 }
3002
John McCallfcef3cf2010-12-14 17:51:41 +00003003 case CK_FloatingComplexCast: {
3004 if (!Visit(E->getSubExpr()))
3005 return false;
3006
3007 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3008 QualType From
3009 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3010
3011 Result.FloatReal
3012 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
3013 Result.FloatImag
3014 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
3015 return true;
3016 }
3017
3018 case CK_FloatingComplexToIntegralComplex: {
3019 if (!Visit(E->getSubExpr()))
3020 return false;
3021
3022 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3023 QualType From
3024 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3025 Result.makeComplexInt();
3026 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
3027 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
3028 return true;
3029 }
3030
3031 case CK_IntegralRealToComplex: {
3032 APSInt &Real = Result.IntReal;
3033 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
3034 return false;
3035
3036 Result.makeComplexInt();
3037 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
3038 return true;
3039 }
3040
3041 case CK_IntegralComplexCast: {
3042 if (!Visit(E->getSubExpr()))
3043 return false;
3044
3045 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3046 QualType From
3047 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3048
3049 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
3050 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
3051 return true;
3052 }
3053
3054 case CK_IntegralComplexToFloatingComplex: {
3055 if (!Visit(E->getSubExpr()))
3056 return false;
3057
3058 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3059 QualType From
3060 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3061 Result.makeComplexFloat();
3062 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
3063 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
3064 return true;
3065 }
3066 }
3067
3068 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003069 return false;
3070}
3071
John McCall93d91dc2010-05-07 17:22:02 +00003072bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003073 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003074 VisitIgnoredValue(E->getLHS());
3075 return Visit(E->getRHS());
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003076 }
John McCall93d91dc2010-05-07 17:22:02 +00003077 if (!Visit(E->getLHS()))
3078 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003079
John McCall93d91dc2010-05-07 17:22:02 +00003080 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003081 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00003082 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003083
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003084 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
3085 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003086 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00003087 default: return false;
John McCalle3027922010-08-25 11:45:40 +00003088 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003089 if (Result.isComplexFloat()) {
3090 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
3091 APFloat::rmNearestTiesToEven);
3092 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
3093 APFloat::rmNearestTiesToEven);
3094 } else {
3095 Result.getComplexIntReal() += RHS.getComplexIntReal();
3096 Result.getComplexIntImag() += RHS.getComplexIntImag();
3097 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003098 break;
John McCalle3027922010-08-25 11:45:40 +00003099 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003100 if (Result.isComplexFloat()) {
3101 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
3102 APFloat::rmNearestTiesToEven);
3103 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
3104 APFloat::rmNearestTiesToEven);
3105 } else {
3106 Result.getComplexIntReal() -= RHS.getComplexIntReal();
3107 Result.getComplexIntImag() -= RHS.getComplexIntImag();
3108 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003109 break;
John McCalle3027922010-08-25 11:45:40 +00003110 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003111 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00003112 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003113 APFloat &LHS_r = LHS.getComplexFloatReal();
3114 APFloat &LHS_i = LHS.getComplexFloatImag();
3115 APFloat &RHS_r = RHS.getComplexFloatReal();
3116 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00003117
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003118 APFloat Tmp = LHS_r;
3119 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3120 Result.getComplexFloatReal() = Tmp;
3121 Tmp = LHS_i;
3122 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3123 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
3124
3125 Tmp = LHS_r;
3126 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3127 Result.getComplexFloatImag() = Tmp;
3128 Tmp = LHS_i;
3129 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3130 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
3131 } else {
John McCall93d91dc2010-05-07 17:22:02 +00003132 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00003133 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003134 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
3135 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00003136 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003137 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
3138 LHS.getComplexIntImag() * RHS.getComplexIntReal());
3139 }
3140 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003141 case BO_Div:
3142 if (Result.isComplexFloat()) {
3143 ComplexValue LHS = Result;
3144 APFloat &LHS_r = LHS.getComplexFloatReal();
3145 APFloat &LHS_i = LHS.getComplexFloatImag();
3146 APFloat &RHS_r = RHS.getComplexFloatReal();
3147 APFloat &RHS_i = RHS.getComplexFloatImag();
3148 APFloat &Res_r = Result.getComplexFloatReal();
3149 APFloat &Res_i = Result.getComplexFloatImag();
3150
3151 APFloat Den = RHS_r;
3152 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3153 APFloat Tmp = RHS_i;
3154 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3155 Den.add(Tmp, APFloat::rmNearestTiesToEven);
3156
3157 Res_r = LHS_r;
3158 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3159 Tmp = LHS_i;
3160 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3161 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
3162 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
3163
3164 Res_i = LHS_i;
3165 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3166 Tmp = LHS_r;
3167 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3168 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
3169 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
3170 } else {
3171 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
3172 // FIXME: what about diagnostics?
3173 return false;
3174 }
3175 ComplexValue LHS = Result;
3176 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
3177 RHS.getComplexIntImag() * RHS.getComplexIntImag();
3178 Result.getComplexIntReal() =
3179 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
3180 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
3181 Result.getComplexIntImag() =
3182 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
3183 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
3184 }
3185 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003186 }
3187
John McCall93d91dc2010-05-07 17:22:02 +00003188 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003189}
3190
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003191bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
3192 // Get the operand value into 'Result'.
3193 if (!Visit(E->getSubExpr()))
3194 return false;
3195
3196 switch (E->getOpcode()) {
3197 default:
3198 // FIXME: what about diagnostics?
3199 return false;
3200 case UO_Extension:
3201 return true;
3202 case UO_Plus:
3203 // The result is always just the subexpr.
3204 return true;
3205 case UO_Minus:
3206 if (Result.isComplexFloat()) {
3207 Result.getComplexFloatReal().changeSign();
3208 Result.getComplexFloatImag().changeSign();
3209 }
3210 else {
3211 Result.getComplexIntReal() = -Result.getComplexIntReal();
3212 Result.getComplexIntImag() = -Result.getComplexIntImag();
3213 }
3214 return true;
3215 case UO_Not:
3216 if (Result.isComplexFloat())
3217 Result.getComplexFloatImag().changeSign();
3218 else
3219 Result.getComplexIntImag() = -Result.getComplexIntImag();
3220 return true;
3221 }
3222}
3223
Anders Carlsson537969c2008-11-16 20:27:53 +00003224//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00003225// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00003226//===----------------------------------------------------------------------===//
3227
Richard Smith0b0a0b62011-10-29 20:57:55 +00003228static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003229 // In C, function designators are not lvalues, but we evaluate them as if they
3230 // are.
3231 if (E->isGLValue() || E->getType()->isFunctionType()) {
3232 LValue LV;
3233 if (!EvaluateLValue(E, LV, Info))
3234 return false;
3235 LV.moveInto(Result);
3236 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003237 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003238 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003239 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003240 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003241 return false;
John McCall45d55e42010-05-07 21:00:08 +00003242 } else if (E->getType()->hasPointerRepresentation()) {
3243 LValue LV;
3244 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003245 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003246 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00003247 } else if (E->getType()->isRealFloatingType()) {
3248 llvm::APFloat F(0.0);
3249 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003250 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003251 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00003252 } else if (E->getType()->isAnyComplexType()) {
3253 ComplexValue C;
3254 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003255 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003256 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00003257 } else if (E->getType()->isMemberPointerType()) {
3258 // FIXME: Implement evaluation of pointer-to-member types.
3259 return false;
3260 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
3261 // FIXME: Implement evaluation of array rvalues.
3262 return false;
3263 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
3264 // FIXME: Implement evaluation of record rvalues.
3265 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003266 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00003267 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003268
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00003269 return true;
3270}
3271
Richard Smithed5165f2011-11-04 05:33:44 +00003272/// EvaluateConstantExpression - Evaluate an expression as a constant expression
3273/// in-place in an APValue. In some cases, the in-place evaluation is essential,
3274/// since later initializers for an object can indirectly refer to subobjects
3275/// which were initialized earlier.
3276static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
3277 const Expr *E) {
3278 if (E->isRValue() && E->getType()->isLiteralType()) {
3279 // Evaluate arrays and record types in-place, so that later initializers can
3280 // refer to earlier-initialized members of the object.
3281 if (E->getType()->isArrayType())
3282 // FIXME: Implement evaluation of array rvalues.
3283 return false;
3284 else if (E->getType()->isRecordType())
3285 // FIXME: Implement evaluation of record rvalues.
3286 return false;
3287 }
3288
3289 // For any other type, in-place evaluation is unimportant.
3290 CCValue CoreConstResult;
3291 return Evaluate(CoreConstResult, Info, E) &&
3292 CheckConstantExpression(CoreConstResult, Result);
3293}
3294
Richard Smith11562c52011-10-28 17:51:58 +00003295
Richard Smith7b553f12011-10-29 00:50:52 +00003296/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00003297/// any crazy technique (that has nothing to do with language standards) that
3298/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00003299/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3300/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00003301bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
John McCallc07a0c72011-02-17 10:25:35 +00003302 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00003303
Richard Smith0b0a0b62011-10-29 20:57:55 +00003304 CCValue Value;
3305 if (!::Evaluate(Value, Info, this))
Richard Smith11562c52011-10-28 17:51:58 +00003306 return false;
3307
3308 if (isGLValue()) {
3309 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003310 LV.setFrom(Value);
3311 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3312 return false;
Richard Smith11562c52011-10-28 17:51:58 +00003313 }
3314
Richard Smith0b0a0b62011-10-29 20:57:55 +00003315 // Check this core constant expression is a constant expression, and if so,
Richard Smithed5165f2011-11-04 05:33:44 +00003316 // convert it to one.
3317 return CheckConstantExpression(Value, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00003318}
3319
Jay Foad39c79802011-01-12 09:06:06 +00003320bool Expr::EvaluateAsBooleanCondition(bool &Result,
3321 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003322 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00003323 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00003324 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00003325 Result);
John McCall1be1c632010-01-05 23:42:56 +00003326}
3327
Richard Smithcaf33902011-10-10 18:28:20 +00003328bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003329 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003330 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smith11562c52011-10-28 17:51:58 +00003331 !ExprResult.Val.isInt()) {
3332 return false;
3333 }
3334 Result = ExprResult.Val.getInt();
3335 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00003336}
3337
Jay Foad39c79802011-01-12 09:06:06 +00003338bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00003339 EvalInfo Info(Ctx, Result);
3340
John McCall45d55e42010-05-07 21:00:08 +00003341 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00003342 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
3343 CheckLValueConstantExpression(LV, Result.Val);
Eli Friedman7d45c482009-09-13 10:17:44 +00003344}
3345
Richard Smith7b553f12011-10-29 00:50:52 +00003346/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3347/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00003348bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00003349 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00003350 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00003351}
Anders Carlsson59689ed2008-11-22 21:04:56 +00003352
Jay Foad39c79802011-01-12 09:06:06 +00003353bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00003354 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003355}
3356
Richard Smithcaf33902011-10-10 18:28:20 +00003357APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003358 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003359 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00003360 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00003361 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003362 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00003363
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003364 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00003365}
John McCall864e3962010-05-07 05:32:02 +00003366
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003367 bool Expr::EvalResult::isGlobalLValue() const {
3368 assert(Val.isLValue());
3369 return IsGlobalLValue(Val.getLValueBase());
3370 }
3371
3372
John McCall864e3962010-05-07 05:32:02 +00003373/// isIntegerConstantExpr - this recursive routine will test if an expression is
3374/// an integer constant expression.
3375
3376/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
3377/// comma, etc
3378///
3379/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
3380/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
3381/// cast+dereference.
3382
3383// CheckICE - This function does the fundamental ICE checking: the returned
3384// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
3385// Note that to reduce code duplication, this helper does no evaluation
3386// itself; the caller checks whether the expression is evaluatable, and
3387// in the rare cases where CheckICE actually cares about the evaluated
3388// value, it calls into Evalute.
3389//
3390// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00003391// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00003392// 1: This expression is not an ICE, but if it isn't evaluated, it's
3393// a legal subexpression for an ICE. This return value is used to handle
3394// the comma operator in C99 mode.
3395// 2: This expression is not an ICE, and is not a legal subexpression for one.
3396
Dan Gohman28ade552010-07-26 21:25:24 +00003397namespace {
3398
John McCall864e3962010-05-07 05:32:02 +00003399struct ICEDiag {
3400 unsigned Val;
3401 SourceLocation Loc;
3402
3403 public:
3404 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
3405 ICEDiag() : Val(0) {}
3406};
3407
Dan Gohman28ade552010-07-26 21:25:24 +00003408}
3409
3410static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00003411
3412static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
3413 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003414 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003415 !EVResult.Val.isInt()) {
3416 return ICEDiag(2, E->getLocStart());
3417 }
3418 return NoDiag();
3419}
3420
3421static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
3422 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00003423 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00003424 return ICEDiag(2, E->getLocStart());
3425 }
3426
3427 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00003428#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00003429#define STMT(Node, Base) case Expr::Node##Class:
3430#define EXPR(Node, Base)
3431#include "clang/AST/StmtNodes.inc"
3432 case Expr::PredefinedExprClass:
3433 case Expr::FloatingLiteralClass:
3434 case Expr::ImaginaryLiteralClass:
3435 case Expr::StringLiteralClass:
3436 case Expr::ArraySubscriptExprClass:
3437 case Expr::MemberExprClass:
3438 case Expr::CompoundAssignOperatorClass:
3439 case Expr::CompoundLiteralExprClass:
3440 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00003441 case Expr::DesignatedInitExprClass:
3442 case Expr::ImplicitValueInitExprClass:
3443 case Expr::ParenListExprClass:
3444 case Expr::VAArgExprClass:
3445 case Expr::AddrLabelExprClass:
3446 case Expr::StmtExprClass:
3447 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00003448 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00003449 case Expr::CXXDynamicCastExprClass:
3450 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00003451 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00003452 case Expr::CXXNullPtrLiteralExprClass:
3453 case Expr::CXXThisExprClass:
3454 case Expr::CXXThrowExprClass:
3455 case Expr::CXXNewExprClass:
3456 case Expr::CXXDeleteExprClass:
3457 case Expr::CXXPseudoDestructorExprClass:
3458 case Expr::UnresolvedLookupExprClass:
3459 case Expr::DependentScopeDeclRefExprClass:
3460 case Expr::CXXConstructExprClass:
3461 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00003462 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00003463 case Expr::CXXTemporaryObjectExprClass:
3464 case Expr::CXXUnresolvedConstructExprClass:
3465 case Expr::CXXDependentScopeMemberExprClass:
3466 case Expr::UnresolvedMemberExprClass:
3467 case Expr::ObjCStringLiteralClass:
3468 case Expr::ObjCEncodeExprClass:
3469 case Expr::ObjCMessageExprClass:
3470 case Expr::ObjCSelectorExprClass:
3471 case Expr::ObjCProtocolExprClass:
3472 case Expr::ObjCIvarRefExprClass:
3473 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00003474 case Expr::ObjCIsaExprClass:
3475 case Expr::ShuffleVectorExprClass:
3476 case Expr::BlockExprClass:
3477 case Expr::BlockDeclRefExprClass:
3478 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00003479 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00003480 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00003481 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00003482 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00003483 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00003484 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00003485 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003486 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00003487 return ICEDiag(2, E->getLocStart());
3488
Sebastian Redl12757ab2011-09-24 17:48:14 +00003489 case Expr::InitListExprClass:
3490 if (Ctx.getLangOptions().CPlusPlus0x) {
3491 const InitListExpr *ILE = cast<InitListExpr>(E);
3492 if (ILE->getNumInits() == 0)
3493 return NoDiag();
3494 if (ILE->getNumInits() == 1)
3495 return CheckICE(ILE->getInit(0), Ctx);
3496 // Fall through for more than 1 expression.
3497 }
3498 return ICEDiag(2, E->getLocStart());
3499
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003500 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00003501 case Expr::GNUNullExprClass:
3502 // GCC considers the GNU __null value to be an integral constant expression.
3503 return NoDiag();
3504
John McCall7c454bb2011-07-15 05:09:51 +00003505 case Expr::SubstNonTypeTemplateParmExprClass:
3506 return
3507 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
3508
John McCall864e3962010-05-07 05:32:02 +00003509 case Expr::ParenExprClass:
3510 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00003511 case Expr::GenericSelectionExprClass:
3512 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003513 case Expr::IntegerLiteralClass:
3514 case Expr::CharacterLiteralClass:
3515 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00003516 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00003517 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003518 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00003519 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00003520 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003521 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00003522 return NoDiag();
3523 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00003524 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00003525 // C99 6.6/3 allows function calls within unevaluated subexpressions of
3526 // constant expressions, but they can never be ICEs because an ICE cannot
3527 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00003528 const CallExpr *CE = cast<CallExpr>(E);
3529 if (CE->isBuiltinCall(Ctx))
3530 return CheckEvalInICE(E, Ctx);
3531 return ICEDiag(2, E->getLocStart());
3532 }
3533 case Expr::DeclRefExprClass:
3534 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
3535 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00003536 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00003537 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3538
3539 // Parameter variables are never constants. Without this check,
3540 // getAnyInitializer() can find a default argument, which leads
3541 // to chaos.
3542 if (isa<ParmVarDecl>(D))
3543 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3544
3545 // C++ 7.1.5.1p2
3546 // A variable of non-volatile const-qualified integral or enumeration
3547 // type initialized by an ICE can be used in ICEs.
3548 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCall864e3962010-05-07 05:32:02 +00003549 // Look for a declaration of this variable that has an initializer.
3550 const VarDecl *ID = 0;
3551 const Expr *Init = Dcl->getAnyInitializer(ID);
3552 if (Init) {
3553 if (ID->isInitKnownICE()) {
3554 // We have already checked whether this subexpression is an
3555 // integral constant expression.
3556 if (ID->isInitICE())
3557 return NoDiag();
3558 else
3559 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3560 }
3561
3562 // It's an ICE whether or not the definition we found is
3563 // out-of-line. See DR 721 and the discussion in Clang PR
3564 // 6206 for details.
3565
3566 if (Dcl->isCheckingICE()) {
3567 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3568 }
3569
3570 Dcl->setCheckingICE();
3571 ICEDiag Result = CheckICE(Init, Ctx);
3572 // Cache the result of the ICE test.
3573 Dcl->setInitKnownICE(Result.Val == 0);
3574 return Result;
3575 }
3576 }
3577 }
3578 return ICEDiag(2, E->getLocStart());
3579 case Expr::UnaryOperatorClass: {
3580 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3581 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003582 case UO_PostInc:
3583 case UO_PostDec:
3584 case UO_PreInc:
3585 case UO_PreDec:
3586 case UO_AddrOf:
3587 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00003588 // C99 6.6/3 allows increment and decrement within unevaluated
3589 // subexpressions of constant expressions, but they can never be ICEs
3590 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003591 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00003592 case UO_Extension:
3593 case UO_LNot:
3594 case UO_Plus:
3595 case UO_Minus:
3596 case UO_Not:
3597 case UO_Real:
3598 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003599 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003600 }
3601
3602 // OffsetOf falls through here.
3603 }
3604 case Expr::OffsetOfExprClass: {
3605 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00003606 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00003607 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00003608 // compliance: we should warn earlier for offsetof expressions with
3609 // array subscripts that aren't ICEs, and if the array subscripts
3610 // are ICEs, the value of the offsetof must be an integer constant.
3611 return CheckEvalInICE(E, Ctx);
3612 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003613 case Expr::UnaryExprOrTypeTraitExprClass: {
3614 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3615 if ((Exp->getKind() == UETT_SizeOf) &&
3616 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003617 return ICEDiag(2, E->getLocStart());
3618 return NoDiag();
3619 }
3620 case Expr::BinaryOperatorClass: {
3621 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3622 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003623 case BO_PtrMemD:
3624 case BO_PtrMemI:
3625 case BO_Assign:
3626 case BO_MulAssign:
3627 case BO_DivAssign:
3628 case BO_RemAssign:
3629 case BO_AddAssign:
3630 case BO_SubAssign:
3631 case BO_ShlAssign:
3632 case BO_ShrAssign:
3633 case BO_AndAssign:
3634 case BO_XorAssign:
3635 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00003636 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3637 // constant expressions, but they can never be ICEs because an ICE cannot
3638 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003639 return ICEDiag(2, E->getLocStart());
3640
John McCalle3027922010-08-25 11:45:40 +00003641 case BO_Mul:
3642 case BO_Div:
3643 case BO_Rem:
3644 case BO_Add:
3645 case BO_Sub:
3646 case BO_Shl:
3647 case BO_Shr:
3648 case BO_LT:
3649 case BO_GT:
3650 case BO_LE:
3651 case BO_GE:
3652 case BO_EQ:
3653 case BO_NE:
3654 case BO_And:
3655 case BO_Xor:
3656 case BO_Or:
3657 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003658 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3659 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003660 if (Exp->getOpcode() == BO_Div ||
3661 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00003662 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00003663 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003664 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003665 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003666 if (REval == 0)
3667 return ICEDiag(1, E->getLocStart());
3668 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003669 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003670 if (LEval.isMinSignedValue())
3671 return ICEDiag(1, E->getLocStart());
3672 }
3673 }
3674 }
John McCalle3027922010-08-25 11:45:40 +00003675 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003676 if (Ctx.getLangOptions().C99) {
3677 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3678 // if it isn't evaluated.
3679 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3680 return ICEDiag(1, E->getLocStart());
3681 } else {
3682 // In both C89 and C++, commas in ICEs are illegal.
3683 return ICEDiag(2, E->getLocStart());
3684 }
3685 }
3686 if (LHSResult.Val >= RHSResult.Val)
3687 return LHSResult;
3688 return RHSResult;
3689 }
John McCalle3027922010-08-25 11:45:40 +00003690 case BO_LAnd:
3691 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003692 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003693
3694 // C++0x [expr.const]p2:
3695 // [...] subexpressions of logical AND (5.14), logical OR
3696 // (5.15), and condi- tional (5.16) operations that are not
3697 // evaluated are not considered.
3698 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3699 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003700 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003701 return LHSResult;
3702
3703 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003704 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003705 return LHSResult;
3706 }
3707
John McCall864e3962010-05-07 05:32:02 +00003708 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3709 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3710 // Rare case where the RHS has a comma "side-effect"; we need
3711 // to actually check the condition to see whether the side
3712 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003713 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003714 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003715 return RHSResult;
3716 return NoDiag();
3717 }
3718
3719 if (LHSResult.Val >= RHSResult.Val)
3720 return LHSResult;
3721 return RHSResult;
3722 }
3723 }
3724 }
3725 case Expr::ImplicitCastExprClass:
3726 case Expr::CStyleCastExprClass:
3727 case Expr::CXXFunctionalCastExprClass:
3728 case Expr::CXXStaticCastExprClass:
3729 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00003730 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003731 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003732 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00003733 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00003734 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3735 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00003736 switch (cast<CastExpr>(E)->getCastKind()) {
3737 case CK_LValueToRValue:
3738 case CK_NoOp:
3739 case CK_IntegralToBoolean:
3740 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003741 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003742 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00003743 return ICEDiag(2, E->getLocStart());
3744 }
John McCall864e3962010-05-07 05:32:02 +00003745 }
John McCallc07a0c72011-02-17 10:25:35 +00003746 case Expr::BinaryConditionalOperatorClass: {
3747 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3748 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3749 if (CommonResult.Val == 2) return CommonResult;
3750 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3751 if (FalseResult.Val == 2) return FalseResult;
3752 if (CommonResult.Val == 1) return CommonResult;
3753 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003754 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003755 return FalseResult;
3756 }
John McCall864e3962010-05-07 05:32:02 +00003757 case Expr::ConditionalOperatorClass: {
3758 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3759 // If the condition (ignoring parens) is a __builtin_constant_p call,
3760 // then only the true side is actually considered in an integer constant
3761 // expression, and it is fully evaluated. This is an important GNU
3762 // extension. See GCC PR38377 for discussion.
3763 if (const CallExpr *CallCE
3764 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3765 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3766 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003767 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003768 !EVResult.Val.isInt()) {
3769 return ICEDiag(2, E->getLocStart());
3770 }
3771 return NoDiag();
3772 }
3773 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003774 if (CondResult.Val == 2)
3775 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003776
3777 // C++0x [expr.const]p2:
3778 // subexpressions of [...] conditional (5.16) operations that
3779 // are not evaluated are not considered
3780 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003781 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003782 : false;
3783 ICEDiag TrueResult = NoDiag();
3784 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3785 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3786 ICEDiag FalseResult = NoDiag();
3787 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3788 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3789
John McCall864e3962010-05-07 05:32:02 +00003790 if (TrueResult.Val == 2)
3791 return TrueResult;
3792 if (FalseResult.Val == 2)
3793 return FalseResult;
3794 if (CondResult.Val == 1)
3795 return CondResult;
3796 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3797 return NoDiag();
3798 // Rare case where the diagnostics depend on which side is evaluated
3799 // Note that if we get here, CondResult is 0, and at least one of
3800 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003801 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003802 return FalseResult;
3803 }
3804 return TrueResult;
3805 }
3806 case Expr::CXXDefaultArgExprClass:
3807 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3808 case Expr::ChooseExprClass: {
3809 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3810 }
3811 }
3812
3813 // Silence a GCC warning
3814 return ICEDiag(2, E->getLocStart());
3815}
3816
3817bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3818 SourceLocation *Loc, bool isEvaluated) const {
3819 ICEDiag d = CheckICE(this, Ctx);
3820 if (d.Val != 0) {
3821 if (Loc) *Loc = d.Loc;
3822 return false;
3823 }
Richard Smith11562c52011-10-28 17:51:58 +00003824 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00003825 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00003826 return true;
3827}