blob: 6456376d48f64e3b2131ead65f51c4a76fc3d2e5 [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 Smith96e0c102011-11-04 02:25:55 +000049 /// A path from a glvalue to a subobject of that glvalue.
50 struct SubobjectDesignator {
51 /// True if the subobject was named in a manner not supported by C++11. Such
52 /// lvalues can still be folded, but they are not core constant expressions
53 /// and we cannot perform lvalue-to-rvalue conversions on them.
54 bool Invalid : 1;
55
56 /// Whether this designates an array element.
57 bool ArrayElement : 1;
58
59 /// Whether this designates 'one past the end' of the current subobject.
60 bool OnePastTheEnd : 1;
61
62 union PathEntry {
63 /// If the current subobject is of class type, this indicates which
64 /// subobject of that type is accessed next.
65 const Decl *BaseOrMember;
66 /// If the current subobject is of array type, this indicates which index
67 /// within that array is accessed next.
68 uint64_t Index;
69 };
70 /// The entries on the path from the glvalue to the designated subobject.
71 SmallVector<PathEntry, 8> Entries;
72
73 SubobjectDesignator() :
74 Invalid(false), ArrayElement(false), OnePastTheEnd(false) {}
75
76 void setInvalid() {
77 Invalid = true;
78 Entries.clear();
79 }
80 /// Update this designator to refer to the given element within this array.
81 void addIndex(uint64_t N) {
82 if (Invalid) return;
83 if (OnePastTheEnd) {
84 setInvalid();
85 return;
86 }
87 PathEntry Entry;
88 Entry.Index = N;
89 Entries.push_back(Entry);
90 ArrayElement = true;
91 }
92 /// Update this designator to refer to the given base or member of this
93 /// object.
94 void addDecl(const Decl *D) {
95 if (Invalid) return;
96 if (OnePastTheEnd) {
97 setInvalid();
98 return;
99 }
100 PathEntry Entry;
101 Entry.BaseOrMember = D;
102 Entries.push_back(Entry);
103 ArrayElement = false;
104 }
105 /// Add N to the address of this subobject.
106 void adjustIndex(uint64_t N) {
107 if (Invalid) return;
108 if (ArrayElement) {
109 Entries.back().Index += N;
110 return;
111 }
112 if (OnePastTheEnd && N == (uint64_t)-1)
113 OnePastTheEnd = false;
114 else if (!OnePastTheEnd && N == 1)
115 OnePastTheEnd = true;
116 else if (N != 0)
117 setInvalid();
118 }
119 };
120
Richard Smith0b0a0b62011-10-29 20:57:55 +0000121 /// A core constant value. This can be the value of any constant expression,
122 /// or a pointer or reference to a non-static object or function parameter.
123 class CCValue : public APValue {
124 typedef llvm::APSInt APSInt;
125 typedef llvm::APFloat APFloat;
Richard Smithfec09922011-11-01 16:57:24 +0000126 /// If the value is a reference or pointer into a parameter or temporary,
127 /// this is the corresponding call stack frame.
128 CallStackFrame *CallFrame;
Richard Smith96e0c102011-11-04 02:25:55 +0000129 /// If the value is a reference or pointer, this is a description of how the
130 /// subobject was specified.
131 SubobjectDesignator Designator;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000132 public:
Richard Smithfec09922011-11-01 16:57:24 +0000133 struct GlobalValue {};
134
Richard Smith0b0a0b62011-10-29 20:57:55 +0000135 CCValue() {}
136 explicit CCValue(const APSInt &I) : APValue(I) {}
137 explicit CCValue(const APFloat &F) : APValue(F) {}
138 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
139 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
140 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smithfec09922011-11-01 16:57:24 +0000141 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000142 CCValue(const Expr *B, const CharUnits &O, CallStackFrame *F,
143 const SubobjectDesignator &D) :
144 APValue(B, O), CallFrame(F), Designator(D) {}
Richard Smithfec09922011-11-01 16:57:24 +0000145 CCValue(const APValue &V, GlobalValue) :
Richard Smith96e0c102011-11-04 02:25:55 +0000146 APValue(V), CallFrame(0), Designator() {}
Richard Smith0b0a0b62011-10-29 20:57:55 +0000147
Richard Smithfec09922011-11-01 16:57:24 +0000148 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000149 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +0000150 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000151 }
Richard Smith96e0c102011-11-04 02:25:55 +0000152 SubobjectDesignator &getLValueDesignator() {
153 assert(getKind() == LValue);
154 return Designator;
155 }
156 const SubobjectDesignator &getLValueDesignator() const {
157 return const_cast<CCValue*>(this)->getLValueDesignator();
158 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000159 };
160
Richard Smith254a73d2011-10-28 22:34:42 +0000161 /// A stack frame in the constexpr call stack.
162 struct CallStackFrame {
163 EvalInfo &Info;
164
165 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000166 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000167
168 /// ParmBindings - Parameter bindings for this function call, indexed by
169 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000170 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000171
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000172 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
173 typedef MapTy::const_iterator temp_iterator;
174 /// Temporaries - Temporary lvalues materialized within this stack frame.
175 MapTy Temporaries;
176
177 CallStackFrame(EvalInfo &Info, const CCValue *Arguments);
178 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000179 };
180
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000181 struct EvalInfo {
182 const ASTContext &Ctx;
183
184 /// EvalStatus - Contains information about the evaluation.
185 Expr::EvalStatus &EvalStatus;
186
187 /// CurrentCall - The top of the constexpr call stack.
188 CallStackFrame *CurrentCall;
189
190 /// NumCalls - The number of calls we've evaluated so far.
191 unsigned NumCalls;
192
193 /// CallStackDepth - The number of calls in the call stack right now.
194 unsigned CallStackDepth;
195
196 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
197 /// OpaqueValues - Values used as the common expression in a
198 /// BinaryConditionalOperator.
199 MapTy OpaqueValues;
200
201 /// BottomFrame - The frame in which evaluation started. This must be
202 /// initialized last.
203 CallStackFrame BottomFrame;
204
205
206 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
207 : Ctx(C), EvalStatus(S), CurrentCall(0), NumCalls(0), CallStackDepth(0),
208 BottomFrame(*this, 0) {}
209
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000210 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
211 MapTy::const_iterator i = OpaqueValues.find(e);
212 if (i == OpaqueValues.end()) return 0;
213 return &i->second;
214 }
215
216 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
217 };
218
219 CallStackFrame::CallStackFrame(EvalInfo &Info, const CCValue *Arguments)
Richard Smithfec09922011-11-01 16:57:24 +0000220 : Info(Info), Caller(Info.CurrentCall), Arguments(Arguments) {
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000221 Info.CurrentCall = this;
222 ++Info.CallStackDepth;
223 }
224
225 CallStackFrame::~CallStackFrame() {
226 assert(Info.CurrentCall == this && "calls retired out of order");
227 --Info.CallStackDepth;
228 Info.CurrentCall = Caller;
229 }
230
John McCall93d91dc2010-05-07 17:22:02 +0000231 struct ComplexValue {
232 private:
233 bool IsInt;
234
235 public:
236 APSInt IntReal, IntImag;
237 APFloat FloatReal, FloatImag;
238
239 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
240
241 void makeComplexFloat() { IsInt = false; }
242 bool isComplexFloat() const { return !IsInt; }
243 APFloat &getComplexFloatReal() { return FloatReal; }
244 APFloat &getComplexFloatImag() { return FloatImag; }
245
246 void makeComplexInt() { IsInt = true; }
247 bool isComplexInt() const { return IsInt; }
248 APSInt &getComplexIntReal() { return IntReal; }
249 APSInt &getComplexIntImag() { return IntImag; }
250
Richard Smith0b0a0b62011-10-29 20:57:55 +0000251 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000252 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000253 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000254 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000255 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000256 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000257 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000258 assert(v.isComplexFloat() || v.isComplexInt());
259 if (v.isComplexFloat()) {
260 makeComplexFloat();
261 FloatReal = v.getComplexFloatReal();
262 FloatImag = v.getComplexFloatImag();
263 } else {
264 makeComplexInt();
265 IntReal = v.getComplexIntReal();
266 IntImag = v.getComplexIntImag();
267 }
268 }
John McCall93d91dc2010-05-07 17:22:02 +0000269 };
John McCall45d55e42010-05-07 21:00:08 +0000270
271 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000272 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000273 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000274 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000275 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000276
Richard Smith8b3497e2011-10-31 01:37:14 +0000277 const Expr *getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000278 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000279 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000280 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000281 SubobjectDesignator &getLValueDesignator() { return Designator; }
282 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000283
Richard Smith0b0a0b62011-10-29 20:57:55 +0000284 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000285 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000286 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000287 void setFrom(const CCValue &V) {
288 assert(V.isLValue());
289 Base = V.getLValueBase();
290 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000291 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000292 Designator = V.getLValueDesignator();
293 }
294
295 void setExpr(const Expr *E, CallStackFrame *F = 0) {
296 Base = E;
297 Offset = CharUnits::Zero();
298 Frame = F;
299 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000300 }
John McCall45d55e42010-05-07 21:00:08 +0000301 };
John McCall93d91dc2010-05-07 17:22:02 +0000302}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000303
Richard Smith0b0a0b62011-10-29 20:57:55 +0000304static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000305static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
306 const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000307static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
308static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000309static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000310static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000311 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000312static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000313static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000314
315//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000316// Misc utilities
317//===----------------------------------------------------------------------===//
318
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000319static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000320 if (!E) return true;
321
322 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
323 if (isa<FunctionDecl>(DRE->getDecl()))
324 return true;
325 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
326 return VD->hasGlobalStorage();
327 return false;
328 }
329
330 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
331 return CLE->isFileScope();
332
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000333 if (isa<MemberExpr>(E) || isa<MaterializeTemporaryExpr>(E))
Richard Smith11562c52011-10-28 17:51:58 +0000334 return false;
335
John McCall95007602010-05-10 23:27:23 +0000336 return true;
337}
338
Richard Smith0b0a0b62011-10-29 20:57:55 +0000339/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000340/// constant expression, and if it is, produce the corresponding constant value.
341static bool CheckConstantExpression(const CCValue &CCValue, APValue &Value) {
342 if (CCValue.isLValue() && !IsGlobalLValue(CCValue.getLValueBase()))
343 return false;
344
345 // Slice off the extra bits.
346 Value = CCValue;
347 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000348}
349
Richard Smith83c68212011-10-31 05:11:32 +0000350const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
351 if (!LVal.Base)
352 return 0;
353
354 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVal.Base))
355 return DRE->getDecl();
356
357 // FIXME: Static data members accessed via a MemberExpr are represented as
358 // that MemberExpr. We should use the Decl directly instead.
359 if (const MemberExpr *ME = dyn_cast<MemberExpr>(LVal.Base)) {
360 assert(!isa<FieldDecl>(ME->getMemberDecl()) && "shouldn't see fields here");
361 return ME->getMemberDecl();
362 }
363
364 return 0;
365}
366
367static bool IsLiteralLValue(const LValue &Value) {
368 return Value.Base &&
369 !isa<DeclRefExpr>(Value.Base) &&
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000370 !isa<MemberExpr>(Value.Base) &&
371 !isa<MaterializeTemporaryExpr>(Value.Base);
Richard Smith83c68212011-10-31 05:11:32 +0000372}
373
Richard Smithcecf1842011-11-01 21:06:14 +0000374static bool IsWeakDecl(const ValueDecl *Decl) {
Richard Smith83c68212011-10-31 05:11:32 +0000375 return Decl->hasAttr<WeakAttr>() ||
376 Decl->hasAttr<WeakRefAttr>() ||
377 Decl->isWeakImported();
378}
379
Richard Smithcecf1842011-11-01 21:06:14 +0000380static bool IsWeakLValue(const LValue &Value) {
381 const ValueDecl *Decl = GetLValueBaseDecl(Value);
382 return Decl && IsWeakDecl(Decl);
383}
384
Richard Smith11562c52011-10-28 17:51:58 +0000385static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCall45d55e42010-05-07 21:00:08 +0000386 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000387
John McCalleb3e4f32010-05-07 21:34:32 +0000388 // A null base expression indicates a null pointer. These are always
389 // evaluatable, and they are false unless the offset is zero.
390 if (!Base) {
391 Result = !Value.Offset.isZero();
392 return true;
393 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000394
John McCall95007602010-05-10 23:27:23 +0000395 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000396 // FIXME: C++11 requires such conversions. Remove this check.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000397 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000398
John McCalleb3e4f32010-05-07 21:34:32 +0000399 // We have a non-null base expression. These are generally known to
400 // be true, but if it'a decl-ref to a weak symbol it can be null at
401 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000402 Result = true;
Richard Smith83c68212011-10-31 05:11:32 +0000403 return !IsWeakLValue(Value);
Eli Friedman334046a2009-06-14 02:17:33 +0000404}
405
Richard Smith0b0a0b62011-10-29 20:57:55 +0000406static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000407 switch (Val.getKind()) {
408 case APValue::Uninitialized:
409 return false;
410 case APValue::Int:
411 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000412 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000413 case APValue::Float:
414 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000415 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000416 case APValue::ComplexInt:
417 Result = Val.getComplexIntReal().getBoolValue() ||
418 Val.getComplexIntImag().getBoolValue();
419 return true;
420 case APValue::ComplexFloat:
421 Result = !Val.getComplexFloatReal().isZero() ||
422 !Val.getComplexFloatImag().isZero();
423 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000424 case APValue::LValue: {
425 LValue PointerResult;
426 PointerResult.setFrom(Val);
427 return EvalPointerValueAsBool(PointerResult, Result);
428 }
Richard Smith11562c52011-10-28 17:51:58 +0000429 case APValue::Vector:
430 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000431 }
432
Richard Smith11562c52011-10-28 17:51:58 +0000433 llvm_unreachable("unknown APValue kind");
434}
435
436static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
437 EvalInfo &Info) {
438 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000439 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000440 if (!Evaluate(Val, Info, E))
441 return false;
442 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000443}
444
Mike Stump11289f42009-09-09 15:08:12 +0000445static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000446 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000447 unsigned DestWidth = Ctx.getIntWidth(DestType);
448 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000449 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000450
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000451 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000452 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000453 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000454 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
455 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000456}
457
Mike Stump11289f42009-09-09 15:08:12 +0000458static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000459 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000460 bool ignored;
461 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000462 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000463 APFloat::rmNearestTiesToEven, &ignored);
464 return Result;
465}
466
Mike Stump11289f42009-09-09 15:08:12 +0000467static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000468 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000469 unsigned DestWidth = Ctx.getIntWidth(DestType);
470 APSInt Result = Value;
471 // Figure out if this is a truncate, extend or noop cast.
472 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000473 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000474 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000475 return Result;
476}
477
Mike Stump11289f42009-09-09 15:08:12 +0000478static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000479 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000480
481 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
482 Result.convertFromAPInt(Value, Value.isSigned(),
483 APFloat::rmNearestTiesToEven);
484 return Result;
485}
486
Richard Smith27908702011-10-24 17:54:18 +0000487/// Try to evaluate the initializer for a variable declaration.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000488static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +0000489 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000490 // If this is a parameter to an active constexpr function call, perform
491 // argument substitution.
492 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithfec09922011-11-01 16:57:24 +0000493 if (!Frame || !Frame->Arguments)
494 return false;
495 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
496 return true;
Richard Smith254a73d2011-10-28 22:34:42 +0000497 }
Richard Smith27908702011-10-24 17:54:18 +0000498
Richard Smithcecf1842011-11-01 21:06:14 +0000499 // Never evaluate the initializer of a weak variable. We can't be sure that
500 // this is the definition which will be used.
501 if (IsWeakDecl(VD))
502 return false;
503
Richard Smith27908702011-10-24 17:54:18 +0000504 const Expr *Init = VD->getAnyInitializer();
505 if (!Init)
Richard Smith0b0a0b62011-10-29 20:57:55 +0000506 return false;
Richard Smith27908702011-10-24 17:54:18 +0000507
Richard Smith0b0a0b62011-10-29 20:57:55 +0000508 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smithfec09922011-11-01 16:57:24 +0000509 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000510 return !Result.isUninit();
511 }
Richard Smith27908702011-10-24 17:54:18 +0000512
513 if (VD->isEvaluatingValue())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000514 return false;
Richard Smith27908702011-10-24 17:54:18 +0000515
516 VD->setEvaluatingValue();
517
Richard Smith0b0a0b62011-10-29 20:57:55 +0000518 Expr::EvalStatus EStatus;
519 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith11562c52011-10-28 17:51:58 +0000520 // FIXME: The caller will need to know whether the value was a constant
521 // expression. If not, we should propagate up a diagnostic.
Richard Smithed5165f2011-11-04 05:33:44 +0000522 APValue EvalResult;
523 if (!EvaluateConstantExpression(EvalResult, InitInfo, Init)) {
Richard Smith27908702011-10-24 17:54:18 +0000524 VD->setEvaluatedValue(APValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000525 return false;
526 }
Richard Smith27908702011-10-24 17:54:18 +0000527
Richard Smithed5165f2011-11-04 05:33:44 +0000528 VD->setEvaluatedValue(EvalResult);
529 Result = CCValue(EvalResult, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000530 return true;
Richard Smith27908702011-10-24 17:54:18 +0000531}
532
Richard Smith11562c52011-10-28 17:51:58 +0000533static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000534 Qualifiers Quals = T.getQualifiers();
535 return Quals.hasConst() && !Quals.hasVolatile();
536}
537
Richard Smith11562c52011-10-28 17:51:58 +0000538bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000539 const LValue &LVal, CCValue &RVal) {
Richard Smith11562c52011-10-28 17:51:58 +0000540 const Expr *Base = LVal.Base;
Richard Smithfec09922011-11-01 16:57:24 +0000541 CallStackFrame *Frame = LVal.Frame;
Richard Smith11562c52011-10-28 17:51:58 +0000542
543 // FIXME: Indirection through a null pointer deserves a diagnostic.
544 if (!Base)
545 return false;
546
Richard Smith8b3497e2011-10-31 01:37:14 +0000547 if (const ValueDecl *D = GetLValueBaseDecl(LVal)) {
Richard Smith11562c52011-10-28 17:51:58 +0000548 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
549 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +0000550 // expressions are constant expressions too. Inside constexpr functions,
551 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +0000552 // In C, such things can also be folded, although they are not ICEs.
553 //
Richard Smith254a73d2011-10-28 22:34:42 +0000554 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
555 // interpretation of C++11 suggests that volatile parameters are OK if
556 // they're never read (there's no prohibition against constructing volatile
557 // objects in constant expressions), but lvalue-to-rvalue conversions on
558 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +0000559 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith96e0c102011-11-04 02:25:55 +0000560 QualType VT = VD->getType();
Richard Smitha08acd82011-11-07 03:22:51 +0000561 if (!VD || VD->isInvalidDecl())
Richard Smith96e0c102011-11-04 02:25:55 +0000562 return false;
563 if (!isa<ParmVarDecl>(VD)) {
564 if (!IsConstNonVolatile(VT))
565 return false;
Richard Smitha08acd82011-11-07 03:22:51 +0000566 // FIXME: Allow folding of values of any literal type in all languages.
567 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
568 !VD->isConstexpr())
Richard Smith96e0c102011-11-04 02:25:55 +0000569 return false;
570 }
571 if (!EvaluateVarDeclInit(Info, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +0000572 return false;
573
Richard Smith0b0a0b62011-10-29 20:57:55 +0000574 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smith96e0c102011-11-04 02:25:55 +0000575 // If the lvalue refers to a subobject or has been cast to some other
576 // type, don't use it.
577 return LVal.Offset.isZero() &&
578 Info.Ctx.hasSameUnqualifiedType(Type, VT);
Richard Smith11562c52011-10-28 17:51:58 +0000579
580 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
581 // conversion. This happens when the declaration and the lvalue should be
582 // considered synonymous, for instance when initializing an array of char
583 // from a string literal. Continue as if the initializer lvalue was the
584 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +0000585 assert(RVal.getLValueOffset().isZero() &&
586 "offset for lvalue init of non-reference");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000587 Base = RVal.getLValueBase();
Richard Smithfec09922011-11-01 16:57:24 +0000588 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +0000589 }
590
Richard Smith96e0c102011-11-04 02:25:55 +0000591 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
592 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
593 const SubobjectDesignator &Designator = LVal.Designator;
594 if (Designator.Invalid || Designator.Entries.size() != 1)
595 return false;
596
597 assert(Type->isIntegerType() && "string element not integer type");
598 uint64_t Index = Designator.Entries[0].Index;
599 if (Index > S->getLength())
600 return false;
601 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
602 Type->isUnsignedIntegerType());
603 if (Index < S->getLength())
604 Value = S->getCodeUnit(Index);
605 RVal = CCValue(Value);
606 return true;
607 }
608
609 // FIXME: Support accessing subobjects of objects of literal types. A simple
610 // byte offset is insufficient for C++11 semantics: we need to know how the
611 // reference was formed (which union member was named, for instance).
612
613 // Beyond this point, we don't support accessing subobjects.
614 if (!LVal.Offset.isZero() ||
615 !Info.Ctx.hasSameUnqualifiedType(Type, Base->getType()))
616 return false;
617
Richard Smithfec09922011-11-01 16:57:24 +0000618 // If this is a temporary expression with a nontrivial initializer, grab the
619 // value from the relevant stack frame.
620 if (Frame) {
621 RVal = Frame->Temporaries[Base];
622 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000623 }
Richard Smith11562c52011-10-28 17:51:58 +0000624
625 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
626 // initializer until now for such expressions. Such an expression can't be
627 // an ICE in C, so this only matters for fold.
628 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
629 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
630 return Evaluate(RVal, Info, CLE->getInitializer());
631 }
632
633 return false;
634}
635
Mike Stump876387b2009-10-27 22:09:17 +0000636namespace {
Richard Smith254a73d2011-10-28 22:34:42 +0000637enum EvalStmtResult {
638 /// Evaluation failed.
639 ESR_Failed,
640 /// Hit a 'return' statement.
641 ESR_Returned,
642 /// Evaluation succeeded.
643 ESR_Succeeded
644};
645}
646
647// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000648static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +0000649 const Stmt *S) {
650 switch (S->getStmtClass()) {
651 default:
652 return ESR_Failed;
653
654 case Stmt::NullStmtClass:
655 case Stmt::DeclStmtClass:
656 return ESR_Succeeded;
657
658 case Stmt::ReturnStmtClass:
659 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
660 return ESR_Returned;
661 return ESR_Failed;
662
663 case Stmt::CompoundStmtClass: {
664 const CompoundStmt *CS = cast<CompoundStmt>(S);
665 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
666 BE = CS->body_end(); BI != BE; ++BI) {
667 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
668 if (ESR != ESR_Succeeded)
669 return ESR;
670 }
671 return ESR_Succeeded;
672 }
673 }
674}
675
676/// Evaluate a function call.
677static bool HandleFunctionCall(ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000678 EvalInfo &Info, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000679 // FIXME: Implement a proper call limit, along with a command-line flag.
680 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
681 return false;
682
Richard Smith0b0a0b62011-10-29 20:57:55 +0000683 SmallVector<CCValue, 16> ArgValues(Args.size());
Richard Smith254a73d2011-10-28 22:34:42 +0000684 // FIXME: Deal with default arguments and 'this'.
685 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
686 I != E; ++I)
687 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
688 return false;
689
690 CallStackFrame Frame(Info, ArgValues.data());
691 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
692}
693
694namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000695class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000696 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000697 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000698public:
699
Richard Smith725810a2011-10-16 21:26:27 +0000700 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000701
702 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000703 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000704 return true;
705 }
706
Peter Collingbournee9200682011-05-13 03:29:01 +0000707 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
708 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000709 return Visit(E->getResultExpr());
710 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000711 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000712 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000713 return true;
714 return false;
715 }
John McCall31168b02011-06-15 23:02:42 +0000716 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000717 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000718 return true;
719 return false;
720 }
721 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000722 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000723 return true;
724 return false;
725 }
726
Mike Stump876387b2009-10-27 22:09:17 +0000727 // We don't want to evaluate BlockExprs multiple times, as they generate
728 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000729 bool VisitBlockExpr(const BlockExpr *E) { return true; }
730 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
731 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000732 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000733 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
734 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
735 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
736 bool VisitStringLiteral(const StringLiteral *E) { return false; }
737 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
738 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000739 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000740 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000741 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000742 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000743 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000744 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
745 bool VisitBinAssign(const BinaryOperator *E) { return true; }
746 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
747 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000748 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000749 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
750 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
751 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
752 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
753 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000754 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000755 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000756 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000757 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000758 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000759
760 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000761 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000762 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
763 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000764 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000765 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000766 return false;
767 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000768
Peter Collingbournee9200682011-05-13 03:29:01 +0000769 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000770};
771
John McCallc07a0c72011-02-17 10:25:35 +0000772class OpaqueValueEvaluation {
773 EvalInfo &info;
774 OpaqueValueExpr *opaqueValue;
775
776public:
777 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
778 Expr *value)
779 : info(info), opaqueValue(opaqueValue) {
780
781 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000782 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000783 this->opaqueValue = 0;
784 return;
785 }
John McCallc07a0c72011-02-17 10:25:35 +0000786 }
787
788 bool hasError() const { return opaqueValue == 0; }
789
790 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000791 // FIXME: This will not work for recursive constexpr functions using opaque
792 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000793 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
794 }
795};
796
Mike Stump876387b2009-10-27 22:09:17 +0000797} // end anonymous namespace
798
Eli Friedman9a156e52008-11-12 09:44:48 +0000799//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000800// Generic Evaluation
801//===----------------------------------------------------------------------===//
802namespace {
803
804template <class Derived, typename RetTy=void>
805class ExprEvaluatorBase
806 : public ConstStmtVisitor<Derived, RetTy> {
807private:
Richard Smith0b0a0b62011-10-29 20:57:55 +0000808 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000809 return static_cast<Derived*>(this)->Success(V, E);
810 }
811 RetTy DerivedError(const Expr *E) {
812 return static_cast<Derived*>(this)->Error(E);
813 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000814 RetTy DerivedValueInitialization(const Expr *E) {
815 return static_cast<Derived*>(this)->ValueInitialization(E);
816 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000817
818protected:
819 EvalInfo &Info;
820 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
821 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
822
Richard Smith4ce706a2011-10-11 21:43:33 +0000823 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
824
Richard Smithfec09922011-11-01 16:57:24 +0000825 bool MakeTemporary(const Expr *Key, const Expr *Value, LValue &Result) {
826 if (!Evaluate(Info.CurrentCall->Temporaries[Key], Info, Value))
827 return false;
Richard Smith96e0c102011-11-04 02:25:55 +0000828 Result.setExpr(Key, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +0000829 return true;
830 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000831public:
832 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
833
834 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000835 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000836 }
837 RetTy VisitExpr(const Expr *E) {
838 return DerivedError(E);
839 }
840
841 RetTy VisitParenExpr(const ParenExpr *E)
842 { return StmtVisitorTy::Visit(E->getSubExpr()); }
843 RetTy VisitUnaryExtension(const UnaryOperator *E)
844 { return StmtVisitorTy::Visit(E->getSubExpr()); }
845 RetTy VisitUnaryPlus(const UnaryOperator *E)
846 { return StmtVisitorTy::Visit(E->getSubExpr()); }
847 RetTy VisitChooseExpr(const ChooseExpr *E)
848 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
849 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
850 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000851 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
852 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000853
854 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
855 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
856 if (opaque.hasError())
857 return DerivedError(E);
858
859 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +0000860 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000861 return DerivedError(E);
862
863 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
864 }
865
866 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
867 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +0000868 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000869 return DerivedError(E);
870
Richard Smith11562c52011-10-28 17:51:58 +0000871 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +0000872 return StmtVisitorTy::Visit(EvalExpr);
873 }
874
875 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000876 const CCValue *Value = Info.getOpaqueValue(E);
877 if (!Value)
Peter Collingbournee9200682011-05-13 03:29:01 +0000878 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
879 : DerivedError(E));
Richard Smith0b0a0b62011-10-29 20:57:55 +0000880 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000881 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000882
Richard Smith254a73d2011-10-28 22:34:42 +0000883 RetTy VisitCallExpr(const CallExpr *E) {
884 const Expr *Callee = E->getCallee();
885 QualType CalleeType = Callee->getType();
886
887 // FIXME: Handle the case where Callee is a (parenthesized) MemberExpr for a
888 // non-static member function.
889 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember))
890 return DerivedError(E);
891
892 if (!CalleeType->isFunctionType() && !CalleeType->isFunctionPointerType())
893 return DerivedError(E);
894
Richard Smith0b0a0b62011-10-29 20:57:55 +0000895 CCValue Call;
Richard Smith254a73d2011-10-28 22:34:42 +0000896 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
897 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
898 return DerivedError(Callee);
899
900 const FunctionDecl *FD = 0;
901 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Call.getLValueBase()))
902 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
903 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Call.getLValueBase()))
904 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
905 if (!FD)
906 return DerivedError(Callee);
907
908 // Don't call function pointers which have been cast to some other type.
909 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
910 return DerivedError(E);
911
912 const FunctionDecl *Definition;
913 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +0000914 CCValue CCResult;
915 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +0000916 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
917
918 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
Richard Smithed5165f2011-11-04 05:33:44 +0000919 HandleFunctionCall(Args, Body, Info, CCResult) &&
920 CheckConstantExpression(CCResult, Result))
921 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +0000922
923 return DerivedError(E);
924 }
925
Richard Smith11562c52011-10-28 17:51:58 +0000926 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
927 return StmtVisitorTy::Visit(E->getInitializer());
928 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000929 RetTy VisitInitListExpr(const InitListExpr *E) {
930 if (Info.getLangOpts().CPlusPlus0x) {
931 if (E->getNumInits() == 0)
932 return DerivedValueInitialization(E);
933 if (E->getNumInits() == 1)
934 return StmtVisitorTy::Visit(E->getInit(0));
935 }
936 return DerivedError(E);
937 }
938 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
939 return DerivedValueInitialization(E);
940 }
941 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
942 return DerivedValueInitialization(E);
943 }
944
Richard Smith11562c52011-10-28 17:51:58 +0000945 RetTy VisitCastExpr(const CastExpr *E) {
946 switch (E->getCastKind()) {
947 default:
948 break;
949
950 case CK_NoOp:
951 return StmtVisitorTy::Visit(E->getSubExpr());
952
953 case CK_LValueToRValue: {
954 LValue LVal;
955 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000956 CCValue RVal;
Richard Smith11562c52011-10-28 17:51:58 +0000957 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
958 return DerivedSuccess(RVal, E);
959 }
960 break;
961 }
962 }
963
964 return DerivedError(E);
965 }
966
Richard Smith4a678122011-10-24 18:44:57 +0000967 /// Visit a value which is evaluated, but whose value is ignored.
968 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000969 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +0000970 if (!Evaluate(Scratch, Info, E))
971 Info.EvalStatus.HasSideEffects = true;
972 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000973};
974
975}
976
977//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000978// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +0000979//
980// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
981// function designators (in C), decl references to void objects (in C), and
982// temporaries (if building with -Wno-address-of-temporary).
983//
984// LValue evaluation produces values comprising a base expression of one of the
985// following types:
986// * DeclRefExpr
987// * MemberExpr for a static member
988// * CompoundLiteralExpr in C
989// * StringLiteral
990// * PredefinedExpr
991// * ObjCEncodeExpr
992// * AddrLabelExpr
993// * BlockExpr
994// * CallExpr for a MakeStringConstant builtin
Richard Smithfec09922011-11-01 16:57:24 +0000995// plus an offset in bytes. It can also produce lvalues referring to locals. In
996// that case, the Frame will point to a stack frame, and the Expr is used as a
997// key to find the relevant temporary's value.
Eli Friedman9a156e52008-11-12 09:44:48 +0000998//===----------------------------------------------------------------------===//
999namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001000class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001001 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001002 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +00001003 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +00001004
Peter Collingbournee9200682011-05-13 03:29:01 +00001005 bool Success(const Expr *E) {
Richard Smith96e0c102011-11-04 02:25:55 +00001006 Result.setExpr(E);
John McCall45d55e42010-05-07 21:00:08 +00001007 return true;
1008 }
Eli Friedman9a156e52008-11-12 09:44:48 +00001009public:
Mike Stump11289f42009-09-09 15:08:12 +00001010
John McCall45d55e42010-05-07 21:00:08 +00001011 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +00001012 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +00001013
Richard Smith0b0a0b62011-10-29 20:57:55 +00001014 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001015 Result.setFrom(V);
1016 return true;
1017 }
1018 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00001019 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001020 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001021
Richard Smith11562c52011-10-28 17:51:58 +00001022 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
1023
Peter Collingbournee9200682011-05-13 03:29:01 +00001024 bool VisitDeclRefExpr(const DeclRefExpr *E);
1025 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001026 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001027 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1028 bool VisitMemberExpr(const MemberExpr *E);
1029 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
1030 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
1031 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
1032 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001033
Peter Collingbournee9200682011-05-13 03:29:01 +00001034 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00001035 switch (E->getCastKind()) {
1036 default:
Richard Smith11562c52011-10-28 17:51:58 +00001037 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001038
Eli Friedmance3e02a2011-10-11 00:13:24 +00001039 case CK_LValueBitCast:
Richard Smith96e0c102011-11-04 02:25:55 +00001040 if (!Visit(E->getSubExpr()))
1041 return false;
1042 Result.Designator.setInvalid();
1043 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00001044
Richard Smith11562c52011-10-28 17:51:58 +00001045 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
1046 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlssonde55f642009-10-03 16:30:22 +00001047 }
1048 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00001049
Eli Friedman449fe542009-03-23 04:56:01 +00001050 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00001051
Eli Friedman9a156e52008-11-12 09:44:48 +00001052};
1053} // end anonymous namespace
1054
Richard Smith11562c52011-10-28 17:51:58 +00001055/// Evaluate an expression as an lvalue. This can be legitimately called on
1056/// expressions which are not glvalues, in a few cases:
1057/// * function designators in C,
1058/// * "extern void" objects,
1059/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00001060static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001061 assert((E->isGLValue() || E->getType()->isFunctionType() ||
1062 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
1063 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00001064 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001065}
1066
Peter Collingbournee9200682011-05-13 03:29:01 +00001067bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001068 if (isa<FunctionDecl>(E->getDecl()))
John McCall45d55e42010-05-07 21:00:08 +00001069 return Success(E);
Richard Smith11562c52011-10-28 17:51:58 +00001070 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
1071 return VisitVarDecl(E, VD);
1072 return Error(E);
1073}
Richard Smith733237d2011-10-24 23:14:33 +00001074
Richard Smith11562c52011-10-28 17:51:58 +00001075bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00001076 if (!VD->getType()->isReferenceType()) {
1077 if (isa<ParmVarDecl>(VD)) {
Richard Smith96e0c102011-11-04 02:25:55 +00001078 Result.setExpr(E, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00001079 return true;
1080 }
Richard Smith11562c52011-10-28 17:51:58 +00001081 return Success(E);
Richard Smithfec09922011-11-01 16:57:24 +00001082 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00001083
Richard Smith0b0a0b62011-10-29 20:57:55 +00001084 CCValue V;
Richard Smithfec09922011-11-01 16:57:24 +00001085 if (EvaluateVarDeclInit(Info, VD, Info.CurrentCall, V))
Richard Smith0b0a0b62011-10-29 20:57:55 +00001086 return Success(V, E);
Richard Smith11562c52011-10-28 17:51:58 +00001087
1088 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +00001089}
1090
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001091bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
1092 const MaterializeTemporaryExpr *E) {
Richard Smithfec09922011-11-01 16:57:24 +00001093 return MakeTemporary(E, E->GetTemporaryExpr(), Result);
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001094}
1095
Peter Collingbournee9200682011-05-13 03:29:01 +00001096bool
1097LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001098 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1099 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
1100 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00001101 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001102}
1103
Peter Collingbournee9200682011-05-13 03:29:01 +00001104bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001105 // Handle static data members.
1106 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
1107 VisitIgnoredValue(E->getBase());
1108 return VisitVarDecl(E, VD);
1109 }
1110
Richard Smith254a73d2011-10-28 22:34:42 +00001111 // Handle static member functions.
1112 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
1113 if (MD->isStatic()) {
1114 VisitIgnoredValue(E->getBase());
1115 return Success(E);
1116 }
1117 }
1118
Eli Friedman9a156e52008-11-12 09:44:48 +00001119 QualType Ty;
1120 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +00001121 if (!EvaluatePointer(E->getBase(), Result, Info))
1122 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001123 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +00001124 } else {
John McCall45d55e42010-05-07 21:00:08 +00001125 if (!Visit(E->getBase()))
1126 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001127 Ty = E->getBase()->getType();
1128 }
1129
Peter Collingbournee9200682011-05-13 03:29:01 +00001130 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +00001131 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001132
Peter Collingbournee9200682011-05-13 03:29:01 +00001133 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001134 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +00001135 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001136
1137 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +00001138 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001139
Eli Friedmana3c122d2011-07-07 01:54:01 +00001140 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001141 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Richard Smith96e0c102011-11-04 02:25:55 +00001142 Result.Designator.addDecl(FD);
John McCall45d55e42010-05-07 21:00:08 +00001143 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +00001144}
1145
Peter Collingbournee9200682011-05-13 03:29:01 +00001146bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001147 // FIXME: Deal with vectors as array subscript bases.
1148 if (E->getBase()->getType()->isVectorType())
1149 return false;
1150
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001151 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00001152 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001153
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001154 APSInt Index;
1155 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00001156 return false;
Richard Smith96e0c102011-11-04 02:25:55 +00001157 uint64_t IndexValue
1158 = Index.isSigned() ? static_cast<uint64_t>(Index.getSExtValue())
1159 : Index.getZExtValue();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001160
Ken Dyck40775002010-01-11 17:06:35 +00001161 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
Richard Smith96e0c102011-11-04 02:25:55 +00001162 Result.Offset += IndexValue * ElementSize;
1163 Result.Designator.adjustIndex(IndexValue);
John McCall45d55e42010-05-07 21:00:08 +00001164 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001165}
Eli Friedman9a156e52008-11-12 09:44:48 +00001166
Peter Collingbournee9200682011-05-13 03:29:01 +00001167bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00001168 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00001169}
1170
Eli Friedman9a156e52008-11-12 09:44:48 +00001171//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001172// Pointer Evaluation
1173//===----------------------------------------------------------------------===//
1174
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001175namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001176class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001177 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001178 LValue &Result;
1179
Peter Collingbournee9200682011-05-13 03:29:01 +00001180 bool Success(const Expr *E) {
Richard Smith96e0c102011-11-04 02:25:55 +00001181 Result.setExpr(E);
John McCall45d55e42010-05-07 21:00:08 +00001182 return true;
1183 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001184public:
Mike Stump11289f42009-09-09 15:08:12 +00001185
John McCall45d55e42010-05-07 21:00:08 +00001186 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001187 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001188
Richard Smith0b0a0b62011-10-29 20:57:55 +00001189 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001190 Result.setFrom(V);
1191 return true;
1192 }
1193 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +00001194 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001195 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001196 bool ValueInitialization(const Expr *E) {
1197 return Success((Expr*)0);
1198 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001199
John McCall45d55e42010-05-07 21:00:08 +00001200 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001201 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00001202 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001203 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00001204 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001205 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00001206 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001207 bool VisitCallExpr(const CallExpr *E);
1208 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00001209 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00001210 return Success(E);
1211 return false;
Mike Stumpa6703322009-02-19 22:01:56 +00001212 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001213 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +00001214 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +00001215
Eli Friedman449fe542009-03-23 04:56:01 +00001216 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001217};
Chris Lattner05706e882008-07-11 18:11:29 +00001218} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001219
John McCall45d55e42010-05-07 21:00:08 +00001220static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001221 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00001222 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00001223}
1224
John McCall45d55e42010-05-07 21:00:08 +00001225bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001226 if (E->getOpcode() != BO_Add &&
1227 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +00001228 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001229
Chris Lattner05706e882008-07-11 18:11:29 +00001230 const Expr *PExp = E->getLHS();
1231 const Expr *IExp = E->getRHS();
1232 if (IExp->getType()->isPointerType())
1233 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00001234
John McCall45d55e42010-05-07 21:00:08 +00001235 if (!EvaluatePointer(PExp, Result, Info))
1236 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001237
John McCall45d55e42010-05-07 21:00:08 +00001238 llvm::APSInt Offset;
1239 if (!EvaluateInteger(IExp, Offset, Info))
1240 return false;
1241 int64_t AdditionalOffset
1242 = Offset.isSigned() ? Offset.getSExtValue()
1243 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00001244 if (E->getOpcode() == BO_Sub)
1245 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00001246
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001247 // Compute the new offset in the appropriate width.
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001248 QualType PointeeType =
1249 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +00001250 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +00001251
Anders Carlssonef56fba2009-02-19 04:55:58 +00001252 // Explicitly handle GNU void* and function pointer arithmetic extensions.
1253 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +00001254 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +00001255 else
John McCall45d55e42010-05-07 21:00:08 +00001256 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +00001257
Richard Smith96e0c102011-11-04 02:25:55 +00001258 Result.Offset += AdditionalOffset * SizeOfPointee;
1259 Result.Designator.adjustIndex(AdditionalOffset);
John McCall45d55e42010-05-07 21:00:08 +00001260 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001261}
Eli Friedman9a156e52008-11-12 09:44:48 +00001262
John McCall45d55e42010-05-07 21:00:08 +00001263bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1264 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001265}
Mike Stump11289f42009-09-09 15:08:12 +00001266
Chris Lattner05706e882008-07-11 18:11:29 +00001267
Peter Collingbournee9200682011-05-13 03:29:01 +00001268bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1269 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00001270
Eli Friedman847a2bc2009-12-27 05:43:15 +00001271 switch (E->getCastKind()) {
1272 default:
1273 break;
1274
John McCalle3027922010-08-25 11:45:40 +00001275 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00001276 case CK_CPointerToObjCPointerCast:
1277 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001278 case CK_AnyPointerToBlockPointerCast:
Richard Smith96e0c102011-11-04 02:25:55 +00001279 if (!Visit(SubExpr))
1280 return false;
1281 Result.Designator.setInvalid();
1282 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00001283
Anders Carlsson18275092010-10-31 20:41:46 +00001284 case CK_DerivedToBase:
1285 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001286 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00001287 return false;
1288
1289 // Now figure out the necessary offset to add to the baseLV to get from
1290 // the derived class to the base class.
Anders Carlsson18275092010-10-31 20:41:46 +00001291 QualType Ty = E->getSubExpr()->getType();
1292 const CXXRecordDecl *DerivedDecl =
1293 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
1294
1295 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1296 PathE = E->path_end(); PathI != PathE; ++PathI) {
1297 const CXXBaseSpecifier *Base = *PathI;
1298
1299 // FIXME: If the base is virtual, we'd need to determine the type of the
1300 // most derived class and we don't support that right now.
1301 if (Base->isVirtual())
1302 return false;
1303
1304 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1305 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1306
Richard Smith0b0a0b62011-10-29 20:57:55 +00001307 Result.getLValueOffset() += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +00001308 DerivedDecl = BaseDecl;
1309 }
1310
Richard Smith96e0c102011-11-04 02:25:55 +00001311 // FIXME
1312 Result.Designator.setInvalid();
1313
Anders Carlsson18275092010-10-31 20:41:46 +00001314 return true;
1315 }
1316
Richard Smith0b0a0b62011-10-29 20:57:55 +00001317 case CK_NullToPointer:
1318 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00001319
John McCalle3027922010-08-25 11:45:40 +00001320 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001321 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00001322 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00001323 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00001324
John McCall45d55e42010-05-07 21:00:08 +00001325 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001326 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1327 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
John McCall45d55e42010-05-07 21:00:08 +00001328 Result.Base = 0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001329 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00001330 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00001331 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00001332 return true;
1333 } else {
1334 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001335 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00001336 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001337 }
1338 }
John McCalle3027922010-08-25 11:45:40 +00001339 case CK_ArrayToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00001340 // FIXME: Support array-to-pointer decay on array rvalues.
1341 if (!SubExpr->isGLValue())
1342 return Error(E);
Richard Smith96e0c102011-11-04 02:25:55 +00001343 if (!EvaluateLValue(SubExpr, Result, Info))
1344 return false;
1345 // The result is a pointer to the first element of the array.
1346 Result.Designator.addIndex(0);
1347 return true;
Richard Smithdd785442011-10-31 20:57:44 +00001348
John McCalle3027922010-08-25 11:45:40 +00001349 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00001350 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001351 }
1352
Richard Smith11562c52011-10-28 17:51:58 +00001353 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00001354}
Chris Lattner05706e882008-07-11 18:11:29 +00001355
Peter Collingbournee9200682011-05-13 03:29:01 +00001356bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +00001357 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +00001358 Builtin::BI__builtin___CFStringMakeConstantString ||
1359 E->isBuiltinCall(Info.Ctx) ==
1360 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +00001361 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00001362
Peter Collingbournee9200682011-05-13 03:29:01 +00001363 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001364}
Chris Lattner05706e882008-07-11 18:11:29 +00001365
1366//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001367// Vector Evaluation
1368//===----------------------------------------------------------------------===//
1369
1370namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001371 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00001372 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1373 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001374 public:
Mike Stump11289f42009-09-09 15:08:12 +00001375
Richard Smith2d406342011-10-22 21:10:00 +00001376 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1377 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001378
Richard Smith2d406342011-10-22 21:10:00 +00001379 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1380 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1381 // FIXME: remove this APValue copy.
1382 Result = APValue(V.data(), V.size());
1383 return true;
1384 }
Richard Smithed5165f2011-11-04 05:33:44 +00001385 bool Success(const CCValue &V, const Expr *E) {
1386 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00001387 Result = V;
1388 return true;
1389 }
1390 bool Error(const Expr *E) { return false; }
1391 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00001392
Richard Smith2d406342011-10-22 21:10:00 +00001393 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00001394 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00001395 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00001396 bool VisitInitListExpr(const InitListExpr *E);
1397 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001398 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001399 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00001400 // shufflevector, ExtVectorElementExpr
1401 // (Note that these require implementing conversions
1402 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001403 };
1404} // end anonymous namespace
1405
1406static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001407 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00001408 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001409}
1410
Richard Smith2d406342011-10-22 21:10:00 +00001411bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1412 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001413 QualType EltTy = VTy->getElementType();
1414 unsigned NElts = VTy->getNumElements();
1415 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +00001416
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001417 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00001418 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001419
Eli Friedmanc757de22011-03-25 00:43:55 +00001420 switch (E->getCastKind()) {
1421 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00001422 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00001423 if (SETy->isIntegerType()) {
1424 APSInt IntResult;
1425 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001426 return Error(E);
1427 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00001428 } else if (SETy->isRealFloatingType()) {
1429 APFloat F(0.0);
1430 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001431 return Error(E);
1432 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00001433 } else {
Richard Smith2d406342011-10-22 21:10:00 +00001434 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001435 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001436
1437 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00001438 SmallVector<APValue, 4> Elts(NElts, Val);
1439 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00001440 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001441 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +00001442 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +00001443 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +00001444 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001445
Eli Friedmanc757de22011-03-25 00:43:55 +00001446 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +00001447 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +00001448
Eli Friedmanc757de22011-03-25 00:43:55 +00001449 APSInt Init;
1450 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001451 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001452
Eli Friedmanc757de22011-03-25 00:43:55 +00001453 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1454 "Vectors must be composed of ints or floats");
1455
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001456 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +00001457 for (unsigned i = 0; i != NElts; ++i) {
1458 APSInt Tmp = Init.extOrTrunc(EltWidth);
1459
1460 if (EltTy->isIntegerType())
1461 Elts.push_back(APValue(Tmp));
1462 else
1463 Elts.push_back(APValue(APFloat(Tmp)));
1464
1465 Init >>= EltWidth;
1466 }
Richard Smith2d406342011-10-22 21:10:00 +00001467 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001468 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001469 default:
Richard Smith11562c52011-10-28 17:51:58 +00001470 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001471 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001472}
1473
Richard Smith2d406342011-10-22 21:10:00 +00001474bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001475VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00001476 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001477 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00001478 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00001479
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001480 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001481 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001482
John McCall875679e2010-06-11 17:54:15 +00001483 // If a vector is initialized with a single element, that value
1484 // becomes every element of the vector, not just the first.
1485 // This is the behavior described in the IBM AltiVec documentation.
1486 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00001487
1488 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00001489 // vector (OpenCL 6.1.6).
1490 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00001491 return Visit(E->getInit(0));
1492
John McCall875679e2010-06-11 17:54:15 +00001493 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001494 if (EltTy->isIntegerType()) {
1495 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00001496 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001497 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001498 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001499 } else {
1500 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00001501 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001502 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001503 InitValue = APValue(f);
1504 }
1505 for (unsigned i = 0; i < NumElements; i++) {
1506 Elements.push_back(InitValue);
1507 }
1508 } else {
1509 for (unsigned i = 0; i < NumElements; i++) {
1510 if (EltTy->isIntegerType()) {
1511 llvm::APSInt sInt(32);
1512 if (i < NumInits) {
1513 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001514 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001515 } else {
1516 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1517 }
1518 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00001519 } else {
John McCall875679e2010-06-11 17:54:15 +00001520 llvm::APFloat f(0.0);
1521 if (i < NumInits) {
1522 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001523 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001524 } else {
1525 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1526 }
1527 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00001528 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001529 }
1530 }
Richard Smith2d406342011-10-22 21:10:00 +00001531 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001532}
1533
Richard Smith2d406342011-10-22 21:10:00 +00001534bool
1535VectorExprEvaluator::ValueInitialization(const Expr *E) {
1536 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00001537 QualType EltTy = VT->getElementType();
1538 APValue ZeroElement;
1539 if (EltTy->isIntegerType())
1540 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1541 else
1542 ZeroElement =
1543 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1544
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001545 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00001546 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001547}
1548
Richard Smith2d406342011-10-22 21:10:00 +00001549bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00001550 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00001551 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001552}
1553
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001554//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001555// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001556//
1557// As a GNU extension, we support casting pointers to sufficiently-wide integer
1558// types and back in constant folding. Integer values are thus represented
1559// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00001560//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001561
1562namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001563class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001564 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001565 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001566public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001567 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001568 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001569
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001570 bool Success(const llvm::APSInt &SI, const Expr *E) {
1571 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001572 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001573 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001574 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001575 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001576 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001577 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001578 return true;
1579 }
1580
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001581 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001582 assert(E->getType()->isIntegralOrEnumerationType() &&
1583 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001584 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001585 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001586 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001587 Result.getInt().setIsUnsigned(
1588 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001589 return true;
1590 }
1591
1592 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001593 assert(E->getType()->isIntegralOrEnumerationType() &&
1594 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001595 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001596 return true;
1597 }
1598
Ken Dyckdbc01912011-03-11 02:13:43 +00001599 bool Success(CharUnits Size, const Expr *E) {
1600 return Success(Size.getQuantity(), E);
1601 }
1602
1603
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001604 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001605 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001606 if (Info.EvalStatus.Diag == 0) {
1607 Info.EvalStatus.DiagLoc = L;
1608 Info.EvalStatus.Diag = D;
1609 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001610 }
Chris Lattner99415702008-07-12 00:14:42 +00001611 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001612 }
Mike Stump11289f42009-09-09 15:08:12 +00001613
Richard Smith0b0a0b62011-10-29 20:57:55 +00001614 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00001615 if (V.isLValue()) {
1616 Result = V;
1617 return true;
1618 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001619 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001620 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001621 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001622 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001623 }
Mike Stump11289f42009-09-09 15:08:12 +00001624
Richard Smith4ce706a2011-10-11 21:43:33 +00001625 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1626
Peter Collingbournee9200682011-05-13 03:29:01 +00001627 //===--------------------------------------------------------------------===//
1628 // Visitor Methods
1629 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001630
Chris Lattner7174bf32008-07-12 00:38:25 +00001631 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001632 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001633 }
1634 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001635 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001636 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001637
1638 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1639 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001640 if (CheckReferencedDecl(E, E->getDecl()))
1641 return true;
1642
1643 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001644 }
1645 bool VisitMemberExpr(const MemberExpr *E) {
1646 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00001647 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001648 return true;
1649 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001650
1651 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001652 }
1653
Peter Collingbournee9200682011-05-13 03:29:01 +00001654 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001655 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001656 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001657 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001658
Peter Collingbournee9200682011-05-13 03:29:01 +00001659 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001660 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001661
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001662 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001663 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001664 }
Mike Stump11289f42009-09-09 15:08:12 +00001665
Richard Smith4ce706a2011-10-11 21:43:33 +00001666 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001667 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001668 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001669 }
1670
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001671 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001672 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001673 }
1674
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001675 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1676 return Success(E->getValue(), E);
1677 }
1678
John Wiegley6242b6a2011-04-28 00:16:57 +00001679 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1680 return Success(E->getValue(), E);
1681 }
1682
John Wiegleyf9f65842011-04-25 06:54:41 +00001683 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1684 return Success(E->getValue(), E);
1685 }
1686
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001687 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001688 bool VisitUnaryImag(const UnaryOperator *E);
1689
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001690 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001691 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001692
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001693private:
Ken Dyck160146e2010-01-27 17:10:57 +00001694 CharUnits GetAlignOfExpr(const Expr *E);
1695 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001696 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001697 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001698 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001699};
Chris Lattner05706e882008-07-11 18:11:29 +00001700} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001701
Richard Smith11562c52011-10-28 17:51:58 +00001702/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1703/// produce either the integer value or a pointer.
1704///
1705/// GCC has a heinous extension which folds casts between pointer types and
1706/// pointer-sized integral types. We support this by allowing the evaluation of
1707/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1708/// Some simple arithmetic on such values is supported (they are treated much
1709/// like char*).
Richard Smith0b0a0b62011-10-29 20:57:55 +00001710static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
1711 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001712 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001713 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001714}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001715
Daniel Dunbarce399542009-02-20 18:22:23 +00001716static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001717 CCValue Val;
Daniel Dunbarce399542009-02-20 18:22:23 +00001718 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1719 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001720 Result = Val.getInt();
1721 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001722}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001723
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001724bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001725 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001726 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001727 // Check for signedness/width mismatches between E type and ECD value.
1728 bool SameSign = (ECD->getInitVal().isSigned()
1729 == E->getType()->isSignedIntegerOrEnumerationType());
1730 bool SameWidth = (ECD->getInitVal().getBitWidth()
1731 == Info.Ctx.getIntWidth(E->getType()));
1732 if (SameSign && SameWidth)
1733 return Success(ECD->getInitVal(), E);
1734 else {
1735 // Get rid of mismatch (otherwise Success assertions will fail)
1736 // by computing a new value matching the type of E.
1737 llvm::APSInt Val = ECD->getInitVal();
1738 if (!SameSign)
1739 Val.setIsSigned(!ECD->getInitVal().isSigned());
1740 if (!SameWidth)
1741 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1742 return Success(Val, E);
1743 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001744 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001745 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001746}
1747
Chris Lattner86ee2862008-10-06 06:40:35 +00001748/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1749/// as GCC.
1750static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1751 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001752 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001753 enum gcc_type_class {
1754 no_type_class = -1,
1755 void_type_class, integer_type_class, char_type_class,
1756 enumeral_type_class, boolean_type_class,
1757 pointer_type_class, reference_type_class, offset_type_class,
1758 real_type_class, complex_type_class,
1759 function_type_class, method_type_class,
1760 record_type_class, union_type_class,
1761 array_type_class, string_type_class,
1762 lang_type_class
1763 };
Mike Stump11289f42009-09-09 15:08:12 +00001764
1765 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001766 // ideal, however it is what gcc does.
1767 if (E->getNumArgs() == 0)
1768 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001769
Chris Lattner86ee2862008-10-06 06:40:35 +00001770 QualType ArgTy = E->getArg(0)->getType();
1771 if (ArgTy->isVoidType())
1772 return void_type_class;
1773 else if (ArgTy->isEnumeralType())
1774 return enumeral_type_class;
1775 else if (ArgTy->isBooleanType())
1776 return boolean_type_class;
1777 else if (ArgTy->isCharType())
1778 return string_type_class; // gcc doesn't appear to use char_type_class
1779 else if (ArgTy->isIntegerType())
1780 return integer_type_class;
1781 else if (ArgTy->isPointerType())
1782 return pointer_type_class;
1783 else if (ArgTy->isReferenceType())
1784 return reference_type_class;
1785 else if (ArgTy->isRealType())
1786 return real_type_class;
1787 else if (ArgTy->isComplexType())
1788 return complex_type_class;
1789 else if (ArgTy->isFunctionType())
1790 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001791 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001792 return record_type_class;
1793 else if (ArgTy->isUnionType())
1794 return union_type_class;
1795 else if (ArgTy->isArrayType())
1796 return array_type_class;
1797 else if (ArgTy->isUnionType())
1798 return union_type_class;
1799 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001800 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001801 return -1;
1802}
1803
John McCall95007602010-05-10 23:27:23 +00001804/// Retrieves the "underlying object type" of the given expression,
1805/// as used by __builtin_object_size.
1806QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1807 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1808 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1809 return VD->getType();
1810 } else if (isa<CompoundLiteralExpr>(E)) {
1811 return E->getType();
1812 }
1813
1814 return QualType();
1815}
1816
Peter Collingbournee9200682011-05-13 03:29:01 +00001817bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001818 // TODO: Perhaps we should let LLVM lower this?
1819 LValue Base;
1820 if (!EvaluatePointer(E->getArg(0), Base, Info))
1821 return false;
1822
1823 // If we can prove the base is null, lower to zero now.
1824 const Expr *LVBase = Base.getLValueBase();
1825 if (!LVBase) return Success(0, E);
1826
1827 QualType T = GetObjectType(LVBase);
1828 if (T.isNull() ||
1829 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001830 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001831 T->isVariablyModifiedType() ||
1832 T->isDependentType())
1833 return false;
1834
1835 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1836 CharUnits Offset = Base.getLValueOffset();
1837
1838 if (!Offset.isNegative() && Offset <= Size)
1839 Size -= Offset;
1840 else
1841 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001842 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001843}
1844
Peter Collingbournee9200682011-05-13 03:29:01 +00001845bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001846 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001847 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001848 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001849
1850 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001851 if (TryEvaluateBuiltinObjectSize(E))
1852 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001853
Eric Christopher99469702010-01-19 22:58:35 +00001854 // If evaluating the argument has side-effects we can't determine
1855 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001856 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001857 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001858 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001859 return Success(0, E);
1860 }
Mike Stump876387b2009-10-27 22:09:17 +00001861
Mike Stump722cedf2009-10-26 18:35:08 +00001862 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1863 }
1864
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001865 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001866 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001867
Anders Carlsson4c76e932008-11-24 04:21:33 +00001868 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001869 // __builtin_constant_p always has one operand: it returns true if that
1870 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001871 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001872
1873 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001874 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001875 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001876 return Success(Operand, E);
1877 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001878
1879 case Builtin::BI__builtin_expect:
1880 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001881
1882 case Builtin::BIstrlen:
1883 case Builtin::BI__builtin_strlen:
1884 // As an extension, we support strlen() and __builtin_strlen() as constant
1885 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001886 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001887 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1888 // The string literal may have embedded null characters. Find the first
1889 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001890 StringRef Str = S->getString();
1891 StringRef::size_type Pos = Str.find(0);
1892 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001893 Str = Str.substr(0, Pos);
1894
1895 return Success(Str.size(), E);
1896 }
1897
1898 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001899
1900 case Builtin::BI__atomic_is_lock_free: {
1901 APSInt SizeVal;
1902 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1903 return false;
1904
1905 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1906 // of two less than the maximum inline atomic width, we know it is
1907 // lock-free. If the size isn't a power of two, or greater than the
1908 // maximum alignment where we promote atomics, we know it is not lock-free
1909 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1910 // the answer can only be determined at runtime; for example, 16-byte
1911 // atomics have lock-free implementations on some, but not all,
1912 // x86-64 processors.
1913
1914 // Check power-of-two.
1915 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1916 if (!Size.isPowerOfTwo())
1917#if 0
1918 // FIXME: Suppress this folding until the ABI for the promotion width
1919 // settles.
1920 return Success(0, E);
1921#else
1922 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1923#endif
1924
1925#if 0
1926 // Check against promotion width.
1927 // FIXME: Suppress this folding until the ABI for the promotion width
1928 // settles.
1929 unsigned PromoteWidthBits =
1930 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1931 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1932 return Success(0, E);
1933#endif
1934
1935 // Check against inlining width.
1936 unsigned InlineWidthBits =
1937 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1938 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1939 return Success(1, E);
1940
1941 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1942 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001943 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001944}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001945
Richard Smith8b3497e2011-10-31 01:37:14 +00001946static bool HasSameBase(const LValue &A, const LValue &B) {
1947 if (!A.getLValueBase())
1948 return !B.getLValueBase();
1949 if (!B.getLValueBase())
1950 return false;
1951
1952 if (A.getLValueBase() != B.getLValueBase()) {
1953 const Decl *ADecl = GetLValueBaseDecl(A);
1954 if (!ADecl)
1955 return false;
1956 const Decl *BDecl = GetLValueBaseDecl(B);
1957 if (ADecl != BDecl)
1958 return false;
1959 }
1960
1961 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00001962 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00001963}
1964
Chris Lattnere13042c2008-07-11 19:10:17 +00001965bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001966 if (E->isAssignmentOp())
1967 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1968
John McCalle3027922010-08-25 11:45:40 +00001969 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00001970 VisitIgnoredValue(E->getLHS());
1971 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00001972 }
1973
1974 if (E->isLogicalOp()) {
1975 // These need to be handled specially because the operands aren't
1976 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001977 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001978
Richard Smith11562c52011-10-28 17:51:58 +00001979 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001980 // We were able to evaluate the LHS, see if we can get away with not
1981 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001982 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001983 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001984
Richard Smith11562c52011-10-28 17:51:58 +00001985 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001986 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001987 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001988 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001989 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001990 }
1991 } else {
Richard Smith11562c52011-10-28 17:51:58 +00001992 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001993 // We can't evaluate the LHS; however, sometimes the result
1994 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001995 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1996 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001997 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001998 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00001999 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002000
2001 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00002002 }
2003 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00002004 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00002005
Eli Friedman5a332ea2008-11-13 06:09:17 +00002006 return false;
2007 }
2008
Anders Carlssonacc79812008-11-16 07:17:21 +00002009 QualType LHSTy = E->getLHS()->getType();
2010 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002011
2012 if (LHSTy->isAnyComplexType()) {
2013 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00002014 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002015
2016 if (!EvaluateComplex(E->getLHS(), LHS, Info))
2017 return false;
2018
2019 if (!EvaluateComplex(E->getRHS(), RHS, Info))
2020 return false;
2021
2022 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00002023 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002024 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00002025 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002026 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
2027
John McCalle3027922010-08-25 11:45:40 +00002028 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002029 return Success((CR_r == APFloat::cmpEqual &&
2030 CR_i == APFloat::cmpEqual), E);
2031 else {
John McCalle3027922010-08-25 11:45:40 +00002032 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002033 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00002034 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00002035 CR_r == APFloat::cmpLessThan ||
2036 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00002037 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00002038 CR_i == APFloat::cmpLessThan ||
2039 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002040 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002041 } else {
John McCalle3027922010-08-25 11:45:40 +00002042 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002043 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
2044 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
2045 else {
John McCalle3027922010-08-25 11:45:40 +00002046 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002047 "Invalid compex comparison.");
2048 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
2049 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
2050 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002051 }
2052 }
Mike Stump11289f42009-09-09 15:08:12 +00002053
Anders Carlssonacc79812008-11-16 07:17:21 +00002054 if (LHSTy->isRealFloatingType() &&
2055 RHSTy->isRealFloatingType()) {
2056 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00002057
Anders Carlssonacc79812008-11-16 07:17:21 +00002058 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2059 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002060
Anders Carlssonacc79812008-11-16 07:17:21 +00002061 if (!EvaluateFloat(E->getLHS(), LHS, Info))
2062 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002063
Anders Carlssonacc79812008-11-16 07:17:21 +00002064 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00002065
Anders Carlssonacc79812008-11-16 07:17:21 +00002066 switch (E->getOpcode()) {
2067 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002068 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00002069 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002070 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00002071 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002072 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00002073 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002074 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00002075 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00002076 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002077 E);
John McCalle3027922010-08-25 11:45:40 +00002078 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002079 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00002080 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00002081 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00002082 || CR == APFloat::cmpLessThan
2083 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00002084 }
Anders Carlssonacc79812008-11-16 07:17:21 +00002085 }
Mike Stump11289f42009-09-09 15:08:12 +00002086
Eli Friedmana38da572009-04-28 19:17:36 +00002087 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00002088 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00002089 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002090 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
2091 return false;
Eli Friedman64004332009-03-23 04:38:34 +00002092
John McCall45d55e42010-05-07 21:00:08 +00002093 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002094 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
2095 return false;
Eli Friedman64004332009-03-23 04:38:34 +00002096
Richard Smith8b3497e2011-10-31 01:37:14 +00002097 // Reject differing bases from the normal codepath; we special-case
2098 // comparisons to null.
2099 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00002100 // Inequalities and subtractions between unrelated pointers have
2101 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00002102 if (!E->isEqualityOp())
2103 return false;
Eli Friedmanc6be94b2011-10-31 22:28:05 +00002104 // A constant address may compare equal to the address of a symbol.
2105 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00002106 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00002107 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
2108 (!RHSValue.Base && !RHSValue.Offset.isZero()))
2109 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002110 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00002111 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00002112 // distinct. However, we do know that the address of a literal will be
2113 // non-null.
2114 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
2115 LHSValue.Base && RHSValue.Base)
Eli Friedman334046a2009-06-14 02:17:33 +00002116 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002117 // We can't tell whether weak symbols will end up pointing to the same
2118 // object.
2119 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Eli Friedman334046a2009-06-14 02:17:33 +00002120 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002121 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00002122 // (Note that clang defaults to -fmerge-all-constants, which can
2123 // lead to inconsistent results for comparisons involving the address
2124 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00002125 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00002126 }
Eli Friedman64004332009-03-23 04:38:34 +00002127
John McCalle3027922010-08-25 11:45:40 +00002128 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00002129 QualType Type = E->getLHS()->getType();
2130 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002131
Ken Dyck02990832010-01-15 12:37:54 +00002132 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00002133 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00002134 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00002135
Ken Dyck02990832010-01-15 12:37:54 +00002136 CharUnits Diff = LHSValue.getLValueOffset() -
2137 RHSValue.getLValueOffset();
2138 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002139 }
Richard Smith8b3497e2011-10-31 01:37:14 +00002140
2141 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
2142 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
2143 switch (E->getOpcode()) {
2144 default: llvm_unreachable("missing comparison operator");
2145 case BO_LT: return Success(LHSOffset < RHSOffset, E);
2146 case BO_GT: return Success(LHSOffset > RHSOffset, E);
2147 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
2148 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
2149 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
2150 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002151 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002152 }
2153 }
Douglas Gregorb90df602010-06-16 00:17:44 +00002154 if (!LHSTy->isIntegralOrEnumerationType() ||
2155 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002156 // We can't continue from here for non-integral types, and they
2157 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00002158 return false;
2159 }
2160
Anders Carlsson9c181652008-07-08 14:35:21 +00002161 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002162 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00002163 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00002164 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00002165
Richard Smith11562c52011-10-28 17:51:58 +00002166 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002167 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002168 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00002169
2170 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00002171 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00002172 CharUnits AdditionalOffset = CharUnits::fromQuantity(
2173 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00002174 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00002175 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00002176 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00002177 LHSVal.getLValueOffset() -= AdditionalOffset;
2178 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00002179 return true;
2180 }
2181
2182 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00002183 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00002184 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002185 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
2186 LHSVal.getInt().getZExtValue());
2187 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00002188 return true;
2189 }
2190
2191 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00002192 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00002193 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00002194
Richard Smith11562c52011-10-28 17:51:58 +00002195 APSInt &LHS = LHSVal.getInt();
2196 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00002197
Anders Carlsson9c181652008-07-08 14:35:21 +00002198 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002199 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002200 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00002201 case BO_Mul: return Success(LHS * RHS, E);
2202 case BO_Add: return Success(LHS + RHS, E);
2203 case BO_Sub: return Success(LHS - RHS, E);
2204 case BO_And: return Success(LHS & RHS, E);
2205 case BO_Xor: return Success(LHS ^ RHS, E);
2206 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002207 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00002208 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002209 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002210 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002211 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00002212 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002213 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002214 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002215 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00002216 // During constant-folding, a negative shift is an opposite shift.
2217 if (RHS.isSigned() && RHS.isNegative()) {
2218 RHS = -RHS;
2219 goto shift_right;
2220 }
2221
2222 shift_left:
2223 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00002224 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2225 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002226 }
John McCalle3027922010-08-25 11:45:40 +00002227 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00002228 // During constant-folding, a negative shift is an opposite shift.
2229 if (RHS.isSigned() && RHS.isNegative()) {
2230 RHS = -RHS;
2231 goto shift_left;
2232 }
2233
2234 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00002235 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00002236 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2237 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002238 }
Mike Stump11289f42009-09-09 15:08:12 +00002239
Richard Smith11562c52011-10-28 17:51:58 +00002240 case BO_LT: return Success(LHS < RHS, E);
2241 case BO_GT: return Success(LHS > RHS, E);
2242 case BO_LE: return Success(LHS <= RHS, E);
2243 case BO_GE: return Success(LHS >= RHS, E);
2244 case BO_EQ: return Success(LHS == RHS, E);
2245 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00002246 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002247}
2248
Ken Dyck160146e2010-01-27 17:10:57 +00002249CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002250 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2251 // the result is the size of the referenced type."
2252 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2253 // result shall be the alignment of the referenced type."
2254 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2255 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00002256
2257 // __alignof is defined to return the preferred alignment.
2258 return Info.Ctx.toCharUnitsFromBits(
2259 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00002260}
2261
Ken Dyck160146e2010-01-27 17:10:57 +00002262CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00002263 E = E->IgnoreParens();
2264
2265 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00002266 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00002267 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002268 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2269 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00002270
Chris Lattner68061312009-01-24 21:53:27 +00002271 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002272 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2273 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00002274
Chris Lattner24aeeab2009-01-24 21:09:06 +00002275 return GetAlignOfType(E->getType());
2276}
2277
2278
Peter Collingbournee190dee2011-03-11 19:24:49 +00002279/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2280/// a result as the expression's type.
2281bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2282 const UnaryExprOrTypeTraitExpr *E) {
2283 switch(E->getKind()) {
2284 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00002285 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00002286 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002287 else
Ken Dyckdbc01912011-03-11 02:13:43 +00002288 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002289 }
Eli Friedman64004332009-03-23 04:38:34 +00002290
Peter Collingbournee190dee2011-03-11 19:24:49 +00002291 case UETT_VecStep: {
2292 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00002293
Peter Collingbournee190dee2011-03-11 19:24:49 +00002294 if (Ty->isVectorType()) {
2295 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00002296
Peter Collingbournee190dee2011-03-11 19:24:49 +00002297 // The vec_step built-in functions that take a 3-component
2298 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2299 if (n == 3)
2300 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002301
Peter Collingbournee190dee2011-03-11 19:24:49 +00002302 return Success(n, E);
2303 } else
2304 return Success(1, E);
2305 }
2306
2307 case UETT_SizeOf: {
2308 QualType SrcTy = E->getTypeOfArgument();
2309 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2310 // the result is the size of the referenced type."
2311 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2312 // result shall be the alignment of the referenced type."
2313 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2314 SrcTy = Ref->getPointeeType();
2315
2316 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2317 // extension.
2318 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
2319 return Success(1, E);
2320
2321 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2322 if (!SrcTy->isConstantSizeType())
2323 return false;
2324
2325 // Get information about the size.
2326 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
2327 }
2328 }
2329
2330 llvm_unreachable("unknown expr/type trait");
2331 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002332}
2333
Peter Collingbournee9200682011-05-13 03:29:01 +00002334bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00002335 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00002336 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00002337 if (n == 0)
2338 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002339 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00002340 for (unsigned i = 0; i != n; ++i) {
2341 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
2342 switch (ON.getKind()) {
2343 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00002344 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00002345 APSInt IdxResult;
2346 if (!EvaluateInteger(Idx, IdxResult, Info))
2347 return false;
2348 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
2349 if (!AT)
2350 return false;
2351 CurrentType = AT->getElementType();
2352 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
2353 Result += IdxResult.getSExtValue() * ElementSize;
2354 break;
2355 }
2356
2357 case OffsetOfExpr::OffsetOfNode::Field: {
2358 FieldDecl *MemberDecl = ON.getField();
2359 const RecordType *RT = CurrentType->getAs<RecordType>();
2360 if (!RT)
2361 return false;
2362 RecordDecl *RD = RT->getDecl();
2363 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00002364 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00002365 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002366 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00002367 CurrentType = MemberDecl->getType().getNonReferenceType();
2368 break;
2369 }
2370
2371 case OffsetOfExpr::OffsetOfNode::Identifier:
2372 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00002373 return false;
2374
2375 case OffsetOfExpr::OffsetOfNode::Base: {
2376 CXXBaseSpecifier *BaseSpec = ON.getBase();
2377 if (BaseSpec->isVirtual())
2378 return false;
2379
2380 // Find the layout of the class whose base we are looking into.
2381 const RecordType *RT = CurrentType->getAs<RecordType>();
2382 if (!RT)
2383 return false;
2384 RecordDecl *RD = RT->getDecl();
2385 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
2386
2387 // Find the base class itself.
2388 CurrentType = BaseSpec->getType();
2389 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2390 if (!BaseRT)
2391 return false;
2392
2393 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00002394 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00002395 break;
2396 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002397 }
2398 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002399 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00002400}
2401
Chris Lattnere13042c2008-07-11 19:10:17 +00002402bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002403 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002404 // LNot's operand isn't necessarily an integer, so we handle it specially.
2405 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00002406 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00002407 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002408 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00002409 }
2410
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002411 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00002412 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002413 return false;
2414
Richard Smith11562c52011-10-28 17:51:58 +00002415 // Get the operand value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002416 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00002417 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00002418 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002419
Chris Lattnerf09ad162008-07-11 22:15:16 +00002420 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002421 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00002422 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2423 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002424 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00002425 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00002426 // FIXME: Should extension allow i-c-e extension expressions in its scope?
2427 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00002428 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002429 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00002430 // The result is just the value.
2431 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002432 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00002433 if (!Val.isInt()) return false;
2434 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00002435 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00002436 if (!Val.isInt()) return false;
2437 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00002438 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002439}
Mike Stump11289f42009-09-09 15:08:12 +00002440
Chris Lattner477c4be2008-07-12 01:15:53 +00002441/// HandleCast - This is used to evaluate implicit or explicit casts where the
2442/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00002443bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
2444 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002445 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00002446 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002447
Eli Friedmanc757de22011-03-25 00:43:55 +00002448 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00002449 case CK_BaseToDerived:
2450 case CK_DerivedToBase:
2451 case CK_UncheckedDerivedToBase:
2452 case CK_Dynamic:
2453 case CK_ToUnion:
2454 case CK_ArrayToPointerDecay:
2455 case CK_FunctionToPointerDecay:
2456 case CK_NullToPointer:
2457 case CK_NullToMemberPointer:
2458 case CK_BaseToDerivedMemberPointer:
2459 case CK_DerivedToBaseMemberPointer:
2460 case CK_ConstructorConversion:
2461 case CK_IntegralToPointer:
2462 case CK_ToVoid:
2463 case CK_VectorSplat:
2464 case CK_IntegralToFloating:
2465 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002466 case CK_CPointerToObjCPointerCast:
2467 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002468 case CK_AnyPointerToBlockPointerCast:
2469 case CK_ObjCObjectLValueCast:
2470 case CK_FloatingRealToComplex:
2471 case CK_FloatingComplexToReal:
2472 case CK_FloatingComplexCast:
2473 case CK_FloatingComplexToIntegralComplex:
2474 case CK_IntegralRealToComplex:
2475 case CK_IntegralComplexCast:
2476 case CK_IntegralComplexToFloatingComplex:
2477 llvm_unreachable("invalid cast kind for integral value");
2478
Eli Friedman9faf2f92011-03-25 19:07:11 +00002479 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002480 case CK_Dependent:
2481 case CK_GetObjCProperty:
2482 case CK_LValueBitCast:
2483 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00002484 case CK_ARCProduceObject:
2485 case CK_ARCConsumeObject:
2486 case CK_ARCReclaimReturnedObject:
2487 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00002488 return false;
2489
2490 case CK_LValueToRValue:
2491 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002492 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002493
2494 case CK_MemberPointerToBoolean:
2495 case CK_PointerToBoolean:
2496 case CK_IntegralToBoolean:
2497 case CK_FloatingToBoolean:
2498 case CK_FloatingComplexToBoolean:
2499 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002500 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002501 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002502 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002503 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002504 }
2505
Eli Friedmanc757de22011-03-25 00:43:55 +00002506 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00002507 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00002508 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002509
Eli Friedman742421e2009-02-20 01:15:07 +00002510 if (!Result.isInt()) {
2511 // Only allow casts of lvalues if they are lossless.
2512 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2513 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002514
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002515 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002516 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00002517 }
Mike Stump11289f42009-09-09 15:08:12 +00002518
Eli Friedmanc757de22011-03-25 00:43:55 +00002519 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00002520 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00002521 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00002522 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002523
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002524 if (LV.getLValueBase()) {
2525 // Only allow based lvalue casts if they are lossless.
2526 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2527 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002528
John McCall45d55e42010-05-07 21:00:08 +00002529 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002530 return true;
2531 }
2532
Ken Dyck02990832010-01-15 12:37:54 +00002533 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2534 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002535 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002536 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002537
Eli Friedmanc757de22011-03-25 00:43:55 +00002538 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00002539 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002540 if (!EvaluateComplex(SubExpr, C, Info))
2541 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00002542 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002543 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00002544
Eli Friedmanc757de22011-03-25 00:43:55 +00002545 case CK_FloatingToIntegral: {
2546 APFloat F(0.0);
2547 if (!EvaluateFloat(SubExpr, F, Info))
2548 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00002549
Eli Friedmanc757de22011-03-25 00:43:55 +00002550 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2551 }
2552 }
Mike Stump11289f42009-09-09 15:08:12 +00002553
Eli Friedmanc757de22011-03-25 00:43:55 +00002554 llvm_unreachable("unknown cast resulting in integral value");
2555 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002556}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002557
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002558bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2559 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002560 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002561 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2562 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2563 return Success(LV.getComplexIntReal(), E);
2564 }
2565
2566 return Visit(E->getSubExpr());
2567}
2568
Eli Friedman4e7a2412009-02-27 04:45:43 +00002569bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002570 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002571 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002572 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2573 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2574 return Success(LV.getComplexIntImag(), E);
2575 }
2576
Richard Smith4a678122011-10-24 18:44:57 +00002577 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00002578 return Success(0, E);
2579}
2580
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002581bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2582 return Success(E->getPackLength(), E);
2583}
2584
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002585bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2586 return Success(E->getValue(), E);
2587}
2588
Chris Lattner05706e882008-07-11 18:11:29 +00002589//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002590// Float Evaluation
2591//===----------------------------------------------------------------------===//
2592
2593namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002594class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002595 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002596 APFloat &Result;
2597public:
2598 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002599 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002600
Richard Smith0b0a0b62011-10-29 20:57:55 +00002601 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002602 Result = V.getFloat();
2603 return true;
2604 }
2605 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002606 return false;
2607 }
2608
Richard Smith4ce706a2011-10-11 21:43:33 +00002609 bool ValueInitialization(const Expr *E) {
2610 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2611 return true;
2612 }
2613
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002614 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002615
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002616 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002617 bool VisitBinaryOperator(const BinaryOperator *E);
2618 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002619 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002620
John McCallb1fb0d32010-05-07 22:08:54 +00002621 bool VisitUnaryReal(const UnaryOperator *E);
2622 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002623
John McCallb1fb0d32010-05-07 22:08:54 +00002624 // FIXME: Missing: array subscript of vector, member of vector,
2625 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002626};
2627} // end anonymous namespace
2628
2629static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002630 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002631 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002632}
2633
Jay Foad39c79802011-01-12 09:06:06 +00002634static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002635 QualType ResultTy,
2636 const Expr *Arg,
2637 bool SNaN,
2638 llvm::APFloat &Result) {
2639 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2640 if (!S) return false;
2641
2642 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2643
2644 llvm::APInt fill;
2645
2646 // Treat empty strings as if they were zero.
2647 if (S->getString().empty())
2648 fill = llvm::APInt(32, 0);
2649 else if (S->getString().getAsInteger(0, fill))
2650 return false;
2651
2652 if (SNaN)
2653 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2654 else
2655 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2656 return true;
2657}
2658
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002659bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002660 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002661 default:
2662 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2663
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002664 case Builtin::BI__builtin_huge_val:
2665 case Builtin::BI__builtin_huge_valf:
2666 case Builtin::BI__builtin_huge_vall:
2667 case Builtin::BI__builtin_inf:
2668 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002669 case Builtin::BI__builtin_infl: {
2670 const llvm::fltSemantics &Sem =
2671 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002672 Result = llvm::APFloat::getInf(Sem);
2673 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002674 }
Mike Stump11289f42009-09-09 15:08:12 +00002675
John McCall16291492010-02-28 13:00:19 +00002676 case Builtin::BI__builtin_nans:
2677 case Builtin::BI__builtin_nansf:
2678 case Builtin::BI__builtin_nansl:
2679 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2680 true, Result);
2681
Chris Lattner0b7282e2008-10-06 06:31:58 +00002682 case Builtin::BI__builtin_nan:
2683 case Builtin::BI__builtin_nanf:
2684 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002685 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002686 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002687 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2688 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002689
2690 case Builtin::BI__builtin_fabs:
2691 case Builtin::BI__builtin_fabsf:
2692 case Builtin::BI__builtin_fabsl:
2693 if (!EvaluateFloat(E->getArg(0), Result, Info))
2694 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002695
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002696 if (Result.isNegative())
2697 Result.changeSign();
2698 return true;
2699
Mike Stump11289f42009-09-09 15:08:12 +00002700 case Builtin::BI__builtin_copysign:
2701 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002702 case Builtin::BI__builtin_copysignl: {
2703 APFloat RHS(0.);
2704 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2705 !EvaluateFloat(E->getArg(1), RHS, Info))
2706 return false;
2707 Result.copySign(RHS);
2708 return true;
2709 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002710 }
2711}
2712
John McCallb1fb0d32010-05-07 22:08:54 +00002713bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002714 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2715 ComplexValue CV;
2716 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2717 return false;
2718 Result = CV.FloatReal;
2719 return true;
2720 }
2721
2722 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002723}
2724
2725bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002726 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2727 ComplexValue CV;
2728 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2729 return false;
2730 Result = CV.FloatImag;
2731 return true;
2732 }
2733
Richard Smith4a678122011-10-24 18:44:57 +00002734 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00002735 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2736 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002737 return true;
2738}
2739
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002740bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002741 switch (E->getOpcode()) {
2742 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002743 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00002744 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00002745 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00002746 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2747 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002748 Result.changeSign();
2749 return true;
2750 }
2751}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002752
Eli Friedman24c01542008-08-22 00:06:13 +00002753bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002754 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002755 VisitIgnoredValue(E->getLHS());
2756 return Visit(E->getRHS());
Eli Friedman141fbf32009-11-16 04:25:37 +00002757 }
2758
Richard Smith472d4952011-10-28 23:26:52 +00002759 // We can't evaluate pointer-to-member operations or assignments.
2760 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlssona5df61a2010-10-31 01:21:47 +00002761 return false;
2762
Eli Friedman24c01542008-08-22 00:06:13 +00002763 // FIXME: Diagnostics? I really don't understand how the warnings
2764 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002765 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002766 if (!EvaluateFloat(E->getLHS(), Result, Info))
2767 return false;
2768 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2769 return false;
2770
2771 switch (E->getOpcode()) {
2772 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002773 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002774 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2775 return true;
John McCalle3027922010-08-25 11:45:40 +00002776 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002777 Result.add(RHS, APFloat::rmNearestTiesToEven);
2778 return true;
John McCalle3027922010-08-25 11:45:40 +00002779 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002780 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2781 return true;
John McCalle3027922010-08-25 11:45:40 +00002782 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002783 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2784 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002785 }
2786}
2787
2788bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2789 Result = E->getValue();
2790 return true;
2791}
2792
Peter Collingbournee9200682011-05-13 03:29:01 +00002793bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2794 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002795
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002796 switch (E->getCastKind()) {
2797 default:
Richard Smith11562c52011-10-28 17:51:58 +00002798 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002799
2800 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002801 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002802 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002803 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002804 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002805 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002806 return true;
2807 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002808
2809 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002810 if (!Visit(SubExpr))
2811 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002812 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2813 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002814 return true;
2815 }
John McCalld7646252010-11-14 08:17:51 +00002816
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002817 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002818 ComplexValue V;
2819 if (!EvaluateComplex(SubExpr, V, Info))
2820 return false;
2821 Result = V.getComplexFloatReal();
2822 return true;
2823 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002824 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002825
2826 return false;
2827}
2828
Eli Friedman24c01542008-08-22 00:06:13 +00002829//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002830// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002831//===----------------------------------------------------------------------===//
2832
2833namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002834class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002835 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002836 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002837
Anders Carlsson537969c2008-11-16 20:27:53 +00002838public:
John McCall93d91dc2010-05-07 17:22:02 +00002839 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002840 : ExprEvaluatorBaseTy(info), Result(Result) {}
2841
Richard Smith0b0a0b62011-10-29 20:57:55 +00002842 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002843 Result.setFrom(V);
2844 return true;
2845 }
2846 bool Error(const Expr *E) {
2847 return false;
2848 }
Mike Stump11289f42009-09-09 15:08:12 +00002849
Anders Carlsson537969c2008-11-16 20:27:53 +00002850 //===--------------------------------------------------------------------===//
2851 // Visitor Methods
2852 //===--------------------------------------------------------------------===//
2853
Peter Collingbournee9200682011-05-13 03:29:01 +00002854 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002855
Peter Collingbournee9200682011-05-13 03:29:01 +00002856 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002857
John McCall93d91dc2010-05-07 17:22:02 +00002858 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002859 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002860 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002861};
2862} // end anonymous namespace
2863
John McCall93d91dc2010-05-07 17:22:02 +00002864static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2865 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002866 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002867 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002868}
2869
Peter Collingbournee9200682011-05-13 03:29:01 +00002870bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2871 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002872
2873 if (SubExpr->getType()->isRealFloatingType()) {
2874 Result.makeComplexFloat();
2875 APFloat &Imag = Result.FloatImag;
2876 if (!EvaluateFloat(SubExpr, Imag, Info))
2877 return false;
2878
2879 Result.FloatReal = APFloat(Imag.getSemantics());
2880 return true;
2881 } else {
2882 assert(SubExpr->getType()->isIntegerType() &&
2883 "Unexpected imaginary literal.");
2884
2885 Result.makeComplexInt();
2886 APSInt &Imag = Result.IntImag;
2887 if (!EvaluateInteger(SubExpr, Imag, Info))
2888 return false;
2889
2890 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2891 return true;
2892 }
2893}
2894
Peter Collingbournee9200682011-05-13 03:29:01 +00002895bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002896
John McCallfcef3cf2010-12-14 17:51:41 +00002897 switch (E->getCastKind()) {
2898 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002899 case CK_BaseToDerived:
2900 case CK_DerivedToBase:
2901 case CK_UncheckedDerivedToBase:
2902 case CK_Dynamic:
2903 case CK_ToUnion:
2904 case CK_ArrayToPointerDecay:
2905 case CK_FunctionToPointerDecay:
2906 case CK_NullToPointer:
2907 case CK_NullToMemberPointer:
2908 case CK_BaseToDerivedMemberPointer:
2909 case CK_DerivedToBaseMemberPointer:
2910 case CK_MemberPointerToBoolean:
2911 case CK_ConstructorConversion:
2912 case CK_IntegralToPointer:
2913 case CK_PointerToIntegral:
2914 case CK_PointerToBoolean:
2915 case CK_ToVoid:
2916 case CK_VectorSplat:
2917 case CK_IntegralCast:
2918 case CK_IntegralToBoolean:
2919 case CK_IntegralToFloating:
2920 case CK_FloatingToIntegral:
2921 case CK_FloatingToBoolean:
2922 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002923 case CK_CPointerToObjCPointerCast:
2924 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002925 case CK_AnyPointerToBlockPointerCast:
2926 case CK_ObjCObjectLValueCast:
2927 case CK_FloatingComplexToReal:
2928 case CK_FloatingComplexToBoolean:
2929 case CK_IntegralComplexToReal:
2930 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002931 case CK_ARCProduceObject:
2932 case CK_ARCConsumeObject:
2933 case CK_ARCReclaimReturnedObject:
2934 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002935 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002936
John McCallfcef3cf2010-12-14 17:51:41 +00002937 case CK_LValueToRValue:
2938 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002939 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00002940
2941 case CK_Dependent:
2942 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002943 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002944 case CK_UserDefinedConversion:
2945 return false;
2946
2947 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002948 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002949 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002950 return false;
2951
John McCallfcef3cf2010-12-14 17:51:41 +00002952 Result.makeComplexFloat();
2953 Result.FloatImag = APFloat(Real.getSemantics());
2954 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002955 }
2956
John McCallfcef3cf2010-12-14 17:51:41 +00002957 case CK_FloatingComplexCast: {
2958 if (!Visit(E->getSubExpr()))
2959 return false;
2960
2961 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2962 QualType From
2963 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2964
2965 Result.FloatReal
2966 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2967 Result.FloatImag
2968 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2969 return true;
2970 }
2971
2972 case CK_FloatingComplexToIntegralComplex: {
2973 if (!Visit(E->getSubExpr()))
2974 return false;
2975
2976 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2977 QualType From
2978 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2979 Result.makeComplexInt();
2980 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2981 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2982 return true;
2983 }
2984
2985 case CK_IntegralRealToComplex: {
2986 APSInt &Real = Result.IntReal;
2987 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2988 return false;
2989
2990 Result.makeComplexInt();
2991 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2992 return true;
2993 }
2994
2995 case CK_IntegralComplexCast: {
2996 if (!Visit(E->getSubExpr()))
2997 return false;
2998
2999 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3000 QualType From
3001 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3002
3003 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
3004 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
3005 return true;
3006 }
3007
3008 case CK_IntegralComplexToFloatingComplex: {
3009 if (!Visit(E->getSubExpr()))
3010 return false;
3011
3012 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3013 QualType From
3014 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3015 Result.makeComplexFloat();
3016 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
3017 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
3018 return true;
3019 }
3020 }
3021
3022 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003023 return false;
3024}
3025
John McCall93d91dc2010-05-07 17:22:02 +00003026bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003027 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003028 VisitIgnoredValue(E->getLHS());
3029 return Visit(E->getRHS());
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003030 }
John McCall93d91dc2010-05-07 17:22:02 +00003031 if (!Visit(E->getLHS()))
3032 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003033
John McCall93d91dc2010-05-07 17:22:02 +00003034 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003035 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00003036 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003037
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003038 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
3039 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003040 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00003041 default: return false;
John McCalle3027922010-08-25 11:45:40 +00003042 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003043 if (Result.isComplexFloat()) {
3044 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
3045 APFloat::rmNearestTiesToEven);
3046 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
3047 APFloat::rmNearestTiesToEven);
3048 } else {
3049 Result.getComplexIntReal() += RHS.getComplexIntReal();
3050 Result.getComplexIntImag() += RHS.getComplexIntImag();
3051 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003052 break;
John McCalle3027922010-08-25 11:45:40 +00003053 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003054 if (Result.isComplexFloat()) {
3055 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
3056 APFloat::rmNearestTiesToEven);
3057 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
3058 APFloat::rmNearestTiesToEven);
3059 } else {
3060 Result.getComplexIntReal() -= RHS.getComplexIntReal();
3061 Result.getComplexIntImag() -= RHS.getComplexIntImag();
3062 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003063 break;
John McCalle3027922010-08-25 11:45:40 +00003064 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003065 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00003066 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003067 APFloat &LHS_r = LHS.getComplexFloatReal();
3068 APFloat &LHS_i = LHS.getComplexFloatImag();
3069 APFloat &RHS_r = RHS.getComplexFloatReal();
3070 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00003071
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003072 APFloat Tmp = LHS_r;
3073 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3074 Result.getComplexFloatReal() = Tmp;
3075 Tmp = LHS_i;
3076 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3077 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
3078
3079 Tmp = LHS_r;
3080 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3081 Result.getComplexFloatImag() = Tmp;
3082 Tmp = LHS_i;
3083 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3084 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
3085 } else {
John McCall93d91dc2010-05-07 17:22:02 +00003086 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00003087 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003088 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
3089 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00003090 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003091 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
3092 LHS.getComplexIntImag() * RHS.getComplexIntReal());
3093 }
3094 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003095 case BO_Div:
3096 if (Result.isComplexFloat()) {
3097 ComplexValue LHS = Result;
3098 APFloat &LHS_r = LHS.getComplexFloatReal();
3099 APFloat &LHS_i = LHS.getComplexFloatImag();
3100 APFloat &RHS_r = RHS.getComplexFloatReal();
3101 APFloat &RHS_i = RHS.getComplexFloatImag();
3102 APFloat &Res_r = Result.getComplexFloatReal();
3103 APFloat &Res_i = Result.getComplexFloatImag();
3104
3105 APFloat Den = RHS_r;
3106 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3107 APFloat Tmp = RHS_i;
3108 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3109 Den.add(Tmp, APFloat::rmNearestTiesToEven);
3110
3111 Res_r = LHS_r;
3112 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3113 Tmp = LHS_i;
3114 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3115 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
3116 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
3117
3118 Res_i = LHS_i;
3119 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3120 Tmp = LHS_r;
3121 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3122 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
3123 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
3124 } else {
3125 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
3126 // FIXME: what about diagnostics?
3127 return false;
3128 }
3129 ComplexValue LHS = Result;
3130 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
3131 RHS.getComplexIntImag() * RHS.getComplexIntImag();
3132 Result.getComplexIntReal() =
3133 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
3134 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
3135 Result.getComplexIntImag() =
3136 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
3137 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
3138 }
3139 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003140 }
3141
John McCall93d91dc2010-05-07 17:22:02 +00003142 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003143}
3144
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003145bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
3146 // Get the operand value into 'Result'.
3147 if (!Visit(E->getSubExpr()))
3148 return false;
3149
3150 switch (E->getOpcode()) {
3151 default:
3152 // FIXME: what about diagnostics?
3153 return false;
3154 case UO_Extension:
3155 return true;
3156 case UO_Plus:
3157 // The result is always just the subexpr.
3158 return true;
3159 case UO_Minus:
3160 if (Result.isComplexFloat()) {
3161 Result.getComplexFloatReal().changeSign();
3162 Result.getComplexFloatImag().changeSign();
3163 }
3164 else {
3165 Result.getComplexIntReal() = -Result.getComplexIntReal();
3166 Result.getComplexIntImag() = -Result.getComplexIntImag();
3167 }
3168 return true;
3169 case UO_Not:
3170 if (Result.isComplexFloat())
3171 Result.getComplexFloatImag().changeSign();
3172 else
3173 Result.getComplexIntImag() = -Result.getComplexIntImag();
3174 return true;
3175 }
3176}
3177
Anders Carlsson537969c2008-11-16 20:27:53 +00003178//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00003179// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00003180//===----------------------------------------------------------------------===//
3181
Richard Smith0b0a0b62011-10-29 20:57:55 +00003182static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003183 // In C, function designators are not lvalues, but we evaluate them as if they
3184 // are.
3185 if (E->isGLValue() || E->getType()->isFunctionType()) {
3186 LValue LV;
3187 if (!EvaluateLValue(E, LV, Info))
3188 return false;
3189 LV.moveInto(Result);
3190 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003191 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003192 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003193 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003194 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003195 return false;
John McCall45d55e42010-05-07 21:00:08 +00003196 } else if (E->getType()->hasPointerRepresentation()) {
3197 LValue LV;
3198 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003199 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003200 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00003201 } else if (E->getType()->isRealFloatingType()) {
3202 llvm::APFloat F(0.0);
3203 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003204 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003205 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00003206 } else if (E->getType()->isAnyComplexType()) {
3207 ComplexValue C;
3208 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003209 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003210 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00003211 } else if (E->getType()->isMemberPointerType()) {
3212 // FIXME: Implement evaluation of pointer-to-member types.
3213 return false;
3214 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
3215 // FIXME: Implement evaluation of array rvalues.
3216 return false;
3217 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
3218 // FIXME: Implement evaluation of record rvalues.
3219 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003220 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00003221 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003222
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00003223 return true;
3224}
3225
Richard Smithed5165f2011-11-04 05:33:44 +00003226/// EvaluateConstantExpression - Evaluate an expression as a constant expression
3227/// in-place in an APValue. In some cases, the in-place evaluation is essential,
3228/// since later initializers for an object can indirectly refer to subobjects
3229/// which were initialized earlier.
3230static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
3231 const Expr *E) {
3232 if (E->isRValue() && E->getType()->isLiteralType()) {
3233 // Evaluate arrays and record types in-place, so that later initializers can
3234 // refer to earlier-initialized members of the object.
3235 if (E->getType()->isArrayType())
3236 // FIXME: Implement evaluation of array rvalues.
3237 return false;
3238 else if (E->getType()->isRecordType())
3239 // FIXME: Implement evaluation of record rvalues.
3240 return false;
3241 }
3242
3243 // For any other type, in-place evaluation is unimportant.
3244 CCValue CoreConstResult;
3245 return Evaluate(CoreConstResult, Info, E) &&
3246 CheckConstantExpression(CoreConstResult, Result);
3247}
3248
Richard Smith11562c52011-10-28 17:51:58 +00003249
Richard Smith7b553f12011-10-29 00:50:52 +00003250/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00003251/// any crazy technique (that has nothing to do with language standards) that
3252/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00003253/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3254/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00003255bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
John McCallc07a0c72011-02-17 10:25:35 +00003256 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00003257
Richard Smith0b0a0b62011-10-29 20:57:55 +00003258 CCValue Value;
3259 if (!::Evaluate(Value, Info, this))
Richard Smith11562c52011-10-28 17:51:58 +00003260 return false;
3261
3262 if (isGLValue()) {
3263 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003264 LV.setFrom(Value);
3265 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3266 return false;
Richard Smith11562c52011-10-28 17:51:58 +00003267 }
3268
Richard Smith0b0a0b62011-10-29 20:57:55 +00003269 // Check this core constant expression is a constant expression, and if so,
Richard Smithed5165f2011-11-04 05:33:44 +00003270 // convert it to one.
3271 return CheckConstantExpression(Value, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00003272}
3273
Jay Foad39c79802011-01-12 09:06:06 +00003274bool Expr::EvaluateAsBooleanCondition(bool &Result,
3275 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003276 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00003277 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00003278 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00003279 Result);
John McCall1be1c632010-01-05 23:42:56 +00003280}
3281
Richard Smithcaf33902011-10-10 18:28:20 +00003282bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003283 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003284 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smith11562c52011-10-28 17:51:58 +00003285 !ExprResult.Val.isInt()) {
3286 return false;
3287 }
3288 Result = ExprResult.Val.getInt();
3289 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00003290}
3291
Jay Foad39c79802011-01-12 09:06:06 +00003292bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00003293 EvalInfo Info(Ctx, Result);
3294
John McCall45d55e42010-05-07 21:00:08 +00003295 LValue LV;
Richard Smith11562c52011-10-28 17:51:58 +00003296 if (EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003297 IsGlobalLValue(LV.Base)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003298 Result.Val = APValue(LV.Base, LV.Offset);
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003299 return true;
3300 }
3301 return false;
3302}
3303
Jay Foad39c79802011-01-12 09:06:06 +00003304bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
3305 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003306 EvalInfo Info(Ctx, Result);
3307
3308 LValue LV;
Richard Smithfec09922011-11-01 16:57:24 +00003309 if (EvaluateLValue(this, LV, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003310 Result.Val = APValue(LV.Base, LV.Offset);
John McCall45d55e42010-05-07 21:00:08 +00003311 return true;
3312 }
3313 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00003314}
3315
Richard Smith7b553f12011-10-29 00:50:52 +00003316/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3317/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00003318bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00003319 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00003320 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00003321}
Anders Carlsson59689ed2008-11-22 21:04:56 +00003322
Jay Foad39c79802011-01-12 09:06:06 +00003323bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00003324 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003325}
3326
Richard Smithcaf33902011-10-10 18:28:20 +00003327APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003328 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003329 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00003330 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00003331 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003332 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00003333
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003334 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00003335}
John McCall864e3962010-05-07 05:32:02 +00003336
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003337 bool Expr::EvalResult::isGlobalLValue() const {
3338 assert(Val.isLValue());
3339 return IsGlobalLValue(Val.getLValueBase());
3340 }
3341
3342
John McCall864e3962010-05-07 05:32:02 +00003343/// isIntegerConstantExpr - this recursive routine will test if an expression is
3344/// an integer constant expression.
3345
3346/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
3347/// comma, etc
3348///
3349/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
3350/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
3351/// cast+dereference.
3352
3353// CheckICE - This function does the fundamental ICE checking: the returned
3354// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
3355// Note that to reduce code duplication, this helper does no evaluation
3356// itself; the caller checks whether the expression is evaluatable, and
3357// in the rare cases where CheckICE actually cares about the evaluated
3358// value, it calls into Evalute.
3359//
3360// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00003361// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00003362// 1: This expression is not an ICE, but if it isn't evaluated, it's
3363// a legal subexpression for an ICE. This return value is used to handle
3364// the comma operator in C99 mode.
3365// 2: This expression is not an ICE, and is not a legal subexpression for one.
3366
Dan Gohman28ade552010-07-26 21:25:24 +00003367namespace {
3368
John McCall864e3962010-05-07 05:32:02 +00003369struct ICEDiag {
3370 unsigned Val;
3371 SourceLocation Loc;
3372
3373 public:
3374 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
3375 ICEDiag() : Val(0) {}
3376};
3377
Dan Gohman28ade552010-07-26 21:25:24 +00003378}
3379
3380static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00003381
3382static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
3383 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003384 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003385 !EVResult.Val.isInt()) {
3386 return ICEDiag(2, E->getLocStart());
3387 }
3388 return NoDiag();
3389}
3390
3391static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
3392 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00003393 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00003394 return ICEDiag(2, E->getLocStart());
3395 }
3396
3397 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00003398#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00003399#define STMT(Node, Base) case Expr::Node##Class:
3400#define EXPR(Node, Base)
3401#include "clang/AST/StmtNodes.inc"
3402 case Expr::PredefinedExprClass:
3403 case Expr::FloatingLiteralClass:
3404 case Expr::ImaginaryLiteralClass:
3405 case Expr::StringLiteralClass:
3406 case Expr::ArraySubscriptExprClass:
3407 case Expr::MemberExprClass:
3408 case Expr::CompoundAssignOperatorClass:
3409 case Expr::CompoundLiteralExprClass:
3410 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00003411 case Expr::DesignatedInitExprClass:
3412 case Expr::ImplicitValueInitExprClass:
3413 case Expr::ParenListExprClass:
3414 case Expr::VAArgExprClass:
3415 case Expr::AddrLabelExprClass:
3416 case Expr::StmtExprClass:
3417 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00003418 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00003419 case Expr::CXXDynamicCastExprClass:
3420 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00003421 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00003422 case Expr::CXXNullPtrLiteralExprClass:
3423 case Expr::CXXThisExprClass:
3424 case Expr::CXXThrowExprClass:
3425 case Expr::CXXNewExprClass:
3426 case Expr::CXXDeleteExprClass:
3427 case Expr::CXXPseudoDestructorExprClass:
3428 case Expr::UnresolvedLookupExprClass:
3429 case Expr::DependentScopeDeclRefExprClass:
3430 case Expr::CXXConstructExprClass:
3431 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00003432 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00003433 case Expr::CXXTemporaryObjectExprClass:
3434 case Expr::CXXUnresolvedConstructExprClass:
3435 case Expr::CXXDependentScopeMemberExprClass:
3436 case Expr::UnresolvedMemberExprClass:
3437 case Expr::ObjCStringLiteralClass:
3438 case Expr::ObjCEncodeExprClass:
3439 case Expr::ObjCMessageExprClass:
3440 case Expr::ObjCSelectorExprClass:
3441 case Expr::ObjCProtocolExprClass:
3442 case Expr::ObjCIvarRefExprClass:
3443 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00003444 case Expr::ObjCIsaExprClass:
3445 case Expr::ShuffleVectorExprClass:
3446 case Expr::BlockExprClass:
3447 case Expr::BlockDeclRefExprClass:
3448 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00003449 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00003450 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00003451 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00003452 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00003453 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00003454 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00003455 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003456 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00003457 return ICEDiag(2, E->getLocStart());
3458
Sebastian Redl12757ab2011-09-24 17:48:14 +00003459 case Expr::InitListExprClass:
3460 if (Ctx.getLangOptions().CPlusPlus0x) {
3461 const InitListExpr *ILE = cast<InitListExpr>(E);
3462 if (ILE->getNumInits() == 0)
3463 return NoDiag();
3464 if (ILE->getNumInits() == 1)
3465 return CheckICE(ILE->getInit(0), Ctx);
3466 // Fall through for more than 1 expression.
3467 }
3468 return ICEDiag(2, E->getLocStart());
3469
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003470 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00003471 case Expr::GNUNullExprClass:
3472 // GCC considers the GNU __null value to be an integral constant expression.
3473 return NoDiag();
3474
John McCall7c454bb2011-07-15 05:09:51 +00003475 case Expr::SubstNonTypeTemplateParmExprClass:
3476 return
3477 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
3478
John McCall864e3962010-05-07 05:32:02 +00003479 case Expr::ParenExprClass:
3480 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00003481 case Expr::GenericSelectionExprClass:
3482 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003483 case Expr::IntegerLiteralClass:
3484 case Expr::CharacterLiteralClass:
3485 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00003486 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00003487 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003488 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00003489 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00003490 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003491 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00003492 return NoDiag();
3493 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00003494 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00003495 // C99 6.6/3 allows function calls within unevaluated subexpressions of
3496 // constant expressions, but they can never be ICEs because an ICE cannot
3497 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00003498 const CallExpr *CE = cast<CallExpr>(E);
3499 if (CE->isBuiltinCall(Ctx))
3500 return CheckEvalInICE(E, Ctx);
3501 return ICEDiag(2, E->getLocStart());
3502 }
3503 case Expr::DeclRefExprClass:
3504 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
3505 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00003506 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00003507 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3508
3509 // Parameter variables are never constants. Without this check,
3510 // getAnyInitializer() can find a default argument, which leads
3511 // to chaos.
3512 if (isa<ParmVarDecl>(D))
3513 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3514
3515 // C++ 7.1.5.1p2
3516 // A variable of non-volatile const-qualified integral or enumeration
3517 // type initialized by an ICE can be used in ICEs.
3518 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCall864e3962010-05-07 05:32:02 +00003519 // Look for a declaration of this variable that has an initializer.
3520 const VarDecl *ID = 0;
3521 const Expr *Init = Dcl->getAnyInitializer(ID);
3522 if (Init) {
3523 if (ID->isInitKnownICE()) {
3524 // We have already checked whether this subexpression is an
3525 // integral constant expression.
3526 if (ID->isInitICE())
3527 return NoDiag();
3528 else
3529 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3530 }
3531
3532 // It's an ICE whether or not the definition we found is
3533 // out-of-line. See DR 721 and the discussion in Clang PR
3534 // 6206 for details.
3535
3536 if (Dcl->isCheckingICE()) {
3537 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3538 }
3539
3540 Dcl->setCheckingICE();
3541 ICEDiag Result = CheckICE(Init, Ctx);
3542 // Cache the result of the ICE test.
3543 Dcl->setInitKnownICE(Result.Val == 0);
3544 return Result;
3545 }
3546 }
3547 }
3548 return ICEDiag(2, E->getLocStart());
3549 case Expr::UnaryOperatorClass: {
3550 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3551 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003552 case UO_PostInc:
3553 case UO_PostDec:
3554 case UO_PreInc:
3555 case UO_PreDec:
3556 case UO_AddrOf:
3557 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00003558 // C99 6.6/3 allows increment and decrement within unevaluated
3559 // subexpressions of constant expressions, but they can never be ICEs
3560 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003561 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00003562 case UO_Extension:
3563 case UO_LNot:
3564 case UO_Plus:
3565 case UO_Minus:
3566 case UO_Not:
3567 case UO_Real:
3568 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003569 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003570 }
3571
3572 // OffsetOf falls through here.
3573 }
3574 case Expr::OffsetOfExprClass: {
3575 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00003576 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00003577 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00003578 // compliance: we should warn earlier for offsetof expressions with
3579 // array subscripts that aren't ICEs, and if the array subscripts
3580 // are ICEs, the value of the offsetof must be an integer constant.
3581 return CheckEvalInICE(E, Ctx);
3582 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003583 case Expr::UnaryExprOrTypeTraitExprClass: {
3584 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3585 if ((Exp->getKind() == UETT_SizeOf) &&
3586 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003587 return ICEDiag(2, E->getLocStart());
3588 return NoDiag();
3589 }
3590 case Expr::BinaryOperatorClass: {
3591 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3592 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003593 case BO_PtrMemD:
3594 case BO_PtrMemI:
3595 case BO_Assign:
3596 case BO_MulAssign:
3597 case BO_DivAssign:
3598 case BO_RemAssign:
3599 case BO_AddAssign:
3600 case BO_SubAssign:
3601 case BO_ShlAssign:
3602 case BO_ShrAssign:
3603 case BO_AndAssign:
3604 case BO_XorAssign:
3605 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00003606 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3607 // constant expressions, but they can never be ICEs because an ICE cannot
3608 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003609 return ICEDiag(2, E->getLocStart());
3610
John McCalle3027922010-08-25 11:45:40 +00003611 case BO_Mul:
3612 case BO_Div:
3613 case BO_Rem:
3614 case BO_Add:
3615 case BO_Sub:
3616 case BO_Shl:
3617 case BO_Shr:
3618 case BO_LT:
3619 case BO_GT:
3620 case BO_LE:
3621 case BO_GE:
3622 case BO_EQ:
3623 case BO_NE:
3624 case BO_And:
3625 case BO_Xor:
3626 case BO_Or:
3627 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003628 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3629 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003630 if (Exp->getOpcode() == BO_Div ||
3631 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00003632 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00003633 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003634 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003635 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003636 if (REval == 0)
3637 return ICEDiag(1, E->getLocStart());
3638 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003639 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003640 if (LEval.isMinSignedValue())
3641 return ICEDiag(1, E->getLocStart());
3642 }
3643 }
3644 }
John McCalle3027922010-08-25 11:45:40 +00003645 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003646 if (Ctx.getLangOptions().C99) {
3647 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3648 // if it isn't evaluated.
3649 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3650 return ICEDiag(1, E->getLocStart());
3651 } else {
3652 // In both C89 and C++, commas in ICEs are illegal.
3653 return ICEDiag(2, E->getLocStart());
3654 }
3655 }
3656 if (LHSResult.Val >= RHSResult.Val)
3657 return LHSResult;
3658 return RHSResult;
3659 }
John McCalle3027922010-08-25 11:45:40 +00003660 case BO_LAnd:
3661 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003662 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003663
3664 // C++0x [expr.const]p2:
3665 // [...] subexpressions of logical AND (5.14), logical OR
3666 // (5.15), and condi- tional (5.16) operations that are not
3667 // evaluated are not considered.
3668 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3669 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003670 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003671 return LHSResult;
3672
3673 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003674 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003675 return LHSResult;
3676 }
3677
John McCall864e3962010-05-07 05:32:02 +00003678 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3679 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3680 // Rare case where the RHS has a comma "side-effect"; we need
3681 // to actually check the condition to see whether the side
3682 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003683 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003684 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003685 return RHSResult;
3686 return NoDiag();
3687 }
3688
3689 if (LHSResult.Val >= RHSResult.Val)
3690 return LHSResult;
3691 return RHSResult;
3692 }
3693 }
3694 }
3695 case Expr::ImplicitCastExprClass:
3696 case Expr::CStyleCastExprClass:
3697 case Expr::CXXFunctionalCastExprClass:
3698 case Expr::CXXStaticCastExprClass:
3699 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00003700 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003701 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003702 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00003703 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00003704 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3705 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00003706 switch (cast<CastExpr>(E)->getCastKind()) {
3707 case CK_LValueToRValue:
3708 case CK_NoOp:
3709 case CK_IntegralToBoolean:
3710 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003711 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003712 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00003713 return ICEDiag(2, E->getLocStart());
3714 }
John McCall864e3962010-05-07 05:32:02 +00003715 }
John McCallc07a0c72011-02-17 10:25:35 +00003716 case Expr::BinaryConditionalOperatorClass: {
3717 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3718 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3719 if (CommonResult.Val == 2) return CommonResult;
3720 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3721 if (FalseResult.Val == 2) return FalseResult;
3722 if (CommonResult.Val == 1) return CommonResult;
3723 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003724 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003725 return FalseResult;
3726 }
John McCall864e3962010-05-07 05:32:02 +00003727 case Expr::ConditionalOperatorClass: {
3728 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3729 // If the condition (ignoring parens) is a __builtin_constant_p call,
3730 // then only the true side is actually considered in an integer constant
3731 // expression, and it is fully evaluated. This is an important GNU
3732 // extension. See GCC PR38377 for discussion.
3733 if (const CallExpr *CallCE
3734 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3735 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3736 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003737 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003738 !EVResult.Val.isInt()) {
3739 return ICEDiag(2, E->getLocStart());
3740 }
3741 return NoDiag();
3742 }
3743 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003744 if (CondResult.Val == 2)
3745 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003746
3747 // C++0x [expr.const]p2:
3748 // subexpressions of [...] conditional (5.16) operations that
3749 // are not evaluated are not considered
3750 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003751 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003752 : false;
3753 ICEDiag TrueResult = NoDiag();
3754 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3755 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3756 ICEDiag FalseResult = NoDiag();
3757 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3758 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3759
John McCall864e3962010-05-07 05:32:02 +00003760 if (TrueResult.Val == 2)
3761 return TrueResult;
3762 if (FalseResult.Val == 2)
3763 return FalseResult;
3764 if (CondResult.Val == 1)
3765 return CondResult;
3766 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3767 return NoDiag();
3768 // Rare case where the diagnostics depend on which side is evaluated
3769 // Note that if we get here, CondResult is 0, and at least one of
3770 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003771 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003772 return FalseResult;
3773 }
3774 return TrueResult;
3775 }
3776 case Expr::CXXDefaultArgExprClass:
3777 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3778 case Expr::ChooseExprClass: {
3779 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3780 }
3781 }
3782
3783 // Silence a GCC warning
3784 return ICEDiag(2, E->getLocStart());
3785}
3786
3787bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3788 SourceLocation *Loc, bool isEvaluated) const {
3789 ICEDiag d = CheckICE(this, Ctx);
3790 if (d.Val != 0) {
3791 if (Loc) *Loc = d.Loc;
3792 return false;
3793 }
Richard Smith11562c52011-10-28 17:51:58 +00003794 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00003795 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00003796 return true;
3797}