blob: dcdd9c3179c9716fa7075ef96c57df5048a8ad63 [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);
John McCall45d55e42010-05-07 21:00:08 +0000305static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
306static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000307static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000308static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000309 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000310static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000311static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000312
313//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000314// Misc utilities
315//===----------------------------------------------------------------------===//
316
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000317static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000318 if (!E) return true;
319
320 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
321 if (isa<FunctionDecl>(DRE->getDecl()))
322 return true;
323 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
324 return VD->hasGlobalStorage();
325 return false;
326 }
327
328 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
329 return CLE->isFileScope();
330
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000331 if (isa<MemberExpr>(E) || isa<MaterializeTemporaryExpr>(E))
Richard Smith11562c52011-10-28 17:51:58 +0000332 return false;
333
John McCall95007602010-05-10 23:27:23 +0000334 return true;
335}
336
Richard Smith0b0a0b62011-10-29 20:57:55 +0000337/// Check that this core constant expression value is a valid value for a
338/// constant expression.
339static bool CheckConstantExpression(const CCValue &Value) {
340 return !Value.isLValue() || IsGlobalLValue(Value.getLValueBase());
341}
342
Richard Smith83c68212011-10-31 05:11:32 +0000343const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
344 if (!LVal.Base)
345 return 0;
346
347 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVal.Base))
348 return DRE->getDecl();
349
350 // FIXME: Static data members accessed via a MemberExpr are represented as
351 // that MemberExpr. We should use the Decl directly instead.
352 if (const MemberExpr *ME = dyn_cast<MemberExpr>(LVal.Base)) {
353 assert(!isa<FieldDecl>(ME->getMemberDecl()) && "shouldn't see fields here");
354 return ME->getMemberDecl();
355 }
356
357 return 0;
358}
359
360static bool IsLiteralLValue(const LValue &Value) {
361 return Value.Base &&
362 !isa<DeclRefExpr>(Value.Base) &&
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000363 !isa<MemberExpr>(Value.Base) &&
364 !isa<MaterializeTemporaryExpr>(Value.Base);
Richard Smith83c68212011-10-31 05:11:32 +0000365}
366
Richard Smithcecf1842011-11-01 21:06:14 +0000367static bool IsWeakDecl(const ValueDecl *Decl) {
Richard Smith83c68212011-10-31 05:11:32 +0000368 return Decl->hasAttr<WeakAttr>() ||
369 Decl->hasAttr<WeakRefAttr>() ||
370 Decl->isWeakImported();
371}
372
Richard Smithcecf1842011-11-01 21:06:14 +0000373static bool IsWeakLValue(const LValue &Value) {
374 const ValueDecl *Decl = GetLValueBaseDecl(Value);
375 return Decl && IsWeakDecl(Decl);
376}
377
Richard Smith11562c52011-10-28 17:51:58 +0000378static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCall45d55e42010-05-07 21:00:08 +0000379 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000380
John McCalleb3e4f32010-05-07 21:34:32 +0000381 // A null base expression indicates a null pointer. These are always
382 // evaluatable, and they are false unless the offset is zero.
383 if (!Base) {
384 Result = !Value.Offset.isZero();
385 return true;
386 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000387
John McCall95007602010-05-10 23:27:23 +0000388 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000389 // FIXME: C++11 requires such conversions. Remove this check.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000390 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000391
John McCalleb3e4f32010-05-07 21:34:32 +0000392 // We have a non-null base expression. These are generally known to
393 // be true, but if it'a decl-ref to a weak symbol it can be null at
394 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000395 Result = true;
Richard Smith83c68212011-10-31 05:11:32 +0000396 return !IsWeakLValue(Value);
Eli Friedman334046a2009-06-14 02:17:33 +0000397}
398
Richard Smith0b0a0b62011-10-29 20:57:55 +0000399static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000400 switch (Val.getKind()) {
401 case APValue::Uninitialized:
402 return false;
403 case APValue::Int:
404 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000405 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000406 case APValue::Float:
407 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000408 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000409 case APValue::ComplexInt:
410 Result = Val.getComplexIntReal().getBoolValue() ||
411 Val.getComplexIntImag().getBoolValue();
412 return true;
413 case APValue::ComplexFloat:
414 Result = !Val.getComplexFloatReal().isZero() ||
415 !Val.getComplexFloatImag().isZero();
416 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000417 case APValue::LValue: {
418 LValue PointerResult;
419 PointerResult.setFrom(Val);
420 return EvalPointerValueAsBool(PointerResult, Result);
421 }
Richard Smith11562c52011-10-28 17:51:58 +0000422 case APValue::Vector:
423 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000424 }
425
Richard Smith11562c52011-10-28 17:51:58 +0000426 llvm_unreachable("unknown APValue kind");
427}
428
429static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
430 EvalInfo &Info) {
431 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000432 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000433 if (!Evaluate(Val, Info, E))
434 return false;
435 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000436}
437
Mike Stump11289f42009-09-09 15:08:12 +0000438static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000439 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000440 unsigned DestWidth = Ctx.getIntWidth(DestType);
441 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000442 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000443
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000444 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000445 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000446 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000447 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
448 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000449}
450
Mike Stump11289f42009-09-09 15:08:12 +0000451static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000452 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000453 bool ignored;
454 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000455 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000456 APFloat::rmNearestTiesToEven, &ignored);
457 return Result;
458}
459
Mike Stump11289f42009-09-09 15:08:12 +0000460static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000461 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000462 unsigned DestWidth = Ctx.getIntWidth(DestType);
463 APSInt Result = Value;
464 // Figure out if this is a truncate, extend or noop cast.
465 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000466 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000467 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000468 return Result;
469}
470
Mike Stump11289f42009-09-09 15:08:12 +0000471static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000472 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000473
474 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
475 Result.convertFromAPInt(Value, Value.isSigned(),
476 APFloat::rmNearestTiesToEven);
477 return Result;
478}
479
Richard Smith27908702011-10-24 17:54:18 +0000480/// Try to evaluate the initializer for a variable declaration.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000481static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +0000482 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000483 // If this is a parameter to an active constexpr function call, perform
484 // argument substitution.
485 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithfec09922011-11-01 16:57:24 +0000486 if (!Frame || !Frame->Arguments)
487 return false;
488 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
489 return true;
Richard Smith254a73d2011-10-28 22:34:42 +0000490 }
Richard Smith27908702011-10-24 17:54:18 +0000491
Richard Smithcecf1842011-11-01 21:06:14 +0000492 // Never evaluate the initializer of a weak variable. We can't be sure that
493 // this is the definition which will be used.
494 if (IsWeakDecl(VD))
495 return false;
496
Richard Smith27908702011-10-24 17:54:18 +0000497 const Expr *Init = VD->getAnyInitializer();
498 if (!Init)
Richard Smith0b0a0b62011-10-29 20:57:55 +0000499 return false;
Richard Smith27908702011-10-24 17:54:18 +0000500
Richard Smith0b0a0b62011-10-29 20:57:55 +0000501 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smithfec09922011-11-01 16:57:24 +0000502 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000503 return !Result.isUninit();
504 }
Richard Smith27908702011-10-24 17:54:18 +0000505
506 if (VD->isEvaluatingValue())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000507 return false;
Richard Smith27908702011-10-24 17:54:18 +0000508
509 VD->setEvaluatingValue();
510
Richard Smith0b0a0b62011-10-29 20:57:55 +0000511 Expr::EvalStatus EStatus;
512 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith11562c52011-10-28 17:51:58 +0000513 // FIXME: The caller will need to know whether the value was a constant
514 // expression. If not, we should propagate up a diagnostic.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000515 if (!Evaluate(Result, InitInfo, Init) || !CheckConstantExpression(Result)) {
Richard Smith27908702011-10-24 17:54:18 +0000516 VD->setEvaluatedValue(APValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000517 return false;
518 }
Richard Smith27908702011-10-24 17:54:18 +0000519
Richard Smith0b0a0b62011-10-29 20:57:55 +0000520 VD->setEvaluatedValue(Result);
521 return true;
Richard Smith27908702011-10-24 17:54:18 +0000522}
523
Richard Smith11562c52011-10-28 17:51:58 +0000524static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000525 Qualifiers Quals = T.getQualifiers();
526 return Quals.hasConst() && !Quals.hasVolatile();
527}
528
Richard Smith11562c52011-10-28 17:51:58 +0000529bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000530 const LValue &LVal, CCValue &RVal) {
Richard Smith11562c52011-10-28 17:51:58 +0000531 const Expr *Base = LVal.Base;
Richard Smithfec09922011-11-01 16:57:24 +0000532 CallStackFrame *Frame = LVal.Frame;
Richard Smith11562c52011-10-28 17:51:58 +0000533
534 // FIXME: Indirection through a null pointer deserves a diagnostic.
535 if (!Base)
536 return false;
537
Richard Smith8b3497e2011-10-31 01:37:14 +0000538 if (const ValueDecl *D = GetLValueBaseDecl(LVal)) {
Richard Smith11562c52011-10-28 17:51:58 +0000539 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
540 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +0000541 // expressions are constant expressions too. Inside constexpr functions,
542 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +0000543 // In C, such things can also be folded, although they are not ICEs.
544 //
Richard Smith254a73d2011-10-28 22:34:42 +0000545 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
546 // interpretation of C++11 suggests that volatile parameters are OK if
547 // they're never read (there's no prohibition against constructing volatile
548 // objects in constant expressions), but lvalue-to-rvalue conversions on
549 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +0000550 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith96e0c102011-11-04 02:25:55 +0000551 QualType VT = VD->getType();
552 if (!VD)
553 return false;
554 if (!isa<ParmVarDecl>(VD)) {
555 if (!IsConstNonVolatile(VT))
556 return false;
557 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType())
558 return false;
559 }
560 if (!EvaluateVarDeclInit(Info, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +0000561 return false;
562
Richard Smith0b0a0b62011-10-29 20:57:55 +0000563 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smith96e0c102011-11-04 02:25:55 +0000564 // If the lvalue refers to a subobject or has been cast to some other
565 // type, don't use it.
566 return LVal.Offset.isZero() &&
567 Info.Ctx.hasSameUnqualifiedType(Type, VT);
Richard Smith11562c52011-10-28 17:51:58 +0000568
569 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
570 // conversion. This happens when the declaration and the lvalue should be
571 // considered synonymous, for instance when initializing an array of char
572 // from a string literal. Continue as if the initializer lvalue was the
573 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +0000574 assert(RVal.getLValueOffset().isZero() &&
575 "offset for lvalue init of non-reference");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000576 Base = RVal.getLValueBase();
Richard Smithfec09922011-11-01 16:57:24 +0000577 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +0000578 }
579
Richard Smith96e0c102011-11-04 02:25:55 +0000580 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
581 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
582 const SubobjectDesignator &Designator = LVal.Designator;
583 if (Designator.Invalid || Designator.Entries.size() != 1)
584 return false;
585
586 assert(Type->isIntegerType() && "string element not integer type");
587 uint64_t Index = Designator.Entries[0].Index;
588 if (Index > S->getLength())
589 return false;
590 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
591 Type->isUnsignedIntegerType());
592 if (Index < S->getLength())
593 Value = S->getCodeUnit(Index);
594 RVal = CCValue(Value);
595 return true;
596 }
597
598 // FIXME: Support accessing subobjects of objects of literal types. A simple
599 // byte offset is insufficient for C++11 semantics: we need to know how the
600 // reference was formed (which union member was named, for instance).
601
602 // Beyond this point, we don't support accessing subobjects.
603 if (!LVal.Offset.isZero() ||
604 !Info.Ctx.hasSameUnqualifiedType(Type, Base->getType()))
605 return false;
606
Richard Smithfec09922011-11-01 16:57:24 +0000607 // If this is a temporary expression with a nontrivial initializer, grab the
608 // value from the relevant stack frame.
609 if (Frame) {
610 RVal = Frame->Temporaries[Base];
611 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000612 }
Richard Smith11562c52011-10-28 17:51:58 +0000613
614 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
615 // initializer until now for such expressions. Such an expression can't be
616 // an ICE in C, so this only matters for fold.
617 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
618 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
619 return Evaluate(RVal, Info, CLE->getInitializer());
620 }
621
622 return false;
623}
624
Mike Stump876387b2009-10-27 22:09:17 +0000625namespace {
Richard Smith254a73d2011-10-28 22:34:42 +0000626enum EvalStmtResult {
627 /// Evaluation failed.
628 ESR_Failed,
629 /// Hit a 'return' statement.
630 ESR_Returned,
631 /// Evaluation succeeded.
632 ESR_Succeeded
633};
634}
635
636// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000637static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +0000638 const Stmt *S) {
639 switch (S->getStmtClass()) {
640 default:
641 return ESR_Failed;
642
643 case Stmt::NullStmtClass:
644 case Stmt::DeclStmtClass:
645 return ESR_Succeeded;
646
647 case Stmt::ReturnStmtClass:
648 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
649 return ESR_Returned;
650 return ESR_Failed;
651
652 case Stmt::CompoundStmtClass: {
653 const CompoundStmt *CS = cast<CompoundStmt>(S);
654 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
655 BE = CS->body_end(); BI != BE; ++BI) {
656 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
657 if (ESR != ESR_Succeeded)
658 return ESR;
659 }
660 return ESR_Succeeded;
661 }
662 }
663}
664
665/// Evaluate a function call.
666static bool HandleFunctionCall(ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000667 EvalInfo &Info, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000668 // FIXME: Implement a proper call limit, along with a command-line flag.
669 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
670 return false;
671
Richard Smith0b0a0b62011-10-29 20:57:55 +0000672 SmallVector<CCValue, 16> ArgValues(Args.size());
Richard Smith254a73d2011-10-28 22:34:42 +0000673 // FIXME: Deal with default arguments and 'this'.
674 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
675 I != E; ++I)
676 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
677 return false;
678
679 CallStackFrame Frame(Info, ArgValues.data());
680 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
681}
682
683namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000684class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000685 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000686 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000687public:
688
Richard Smith725810a2011-10-16 21:26:27 +0000689 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000690
691 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000692 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000693 return true;
694 }
695
Peter Collingbournee9200682011-05-13 03:29:01 +0000696 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
697 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000698 return Visit(E->getResultExpr());
699 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000700 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000701 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000702 return true;
703 return false;
704 }
John McCall31168b02011-06-15 23:02:42 +0000705 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000706 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000707 return true;
708 return false;
709 }
710 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000711 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000712 return true;
713 return false;
714 }
715
Mike Stump876387b2009-10-27 22:09:17 +0000716 // We don't want to evaluate BlockExprs multiple times, as they generate
717 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000718 bool VisitBlockExpr(const BlockExpr *E) { return true; }
719 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
720 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000721 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000722 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
723 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
724 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
725 bool VisitStringLiteral(const StringLiteral *E) { return false; }
726 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
727 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000728 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000729 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000730 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000731 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000732 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000733 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
734 bool VisitBinAssign(const BinaryOperator *E) { return true; }
735 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
736 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000737 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000738 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
739 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
740 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
741 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
742 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000743 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000744 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000745 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000746 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000747 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000748
749 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000750 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000751 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
752 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000753 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000754 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000755 return false;
756 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000757
Peter Collingbournee9200682011-05-13 03:29:01 +0000758 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000759};
760
John McCallc07a0c72011-02-17 10:25:35 +0000761class OpaqueValueEvaluation {
762 EvalInfo &info;
763 OpaqueValueExpr *opaqueValue;
764
765public:
766 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
767 Expr *value)
768 : info(info), opaqueValue(opaqueValue) {
769
770 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000771 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000772 this->opaqueValue = 0;
773 return;
774 }
John McCallc07a0c72011-02-17 10:25:35 +0000775 }
776
777 bool hasError() const { return opaqueValue == 0; }
778
779 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000780 // FIXME: This will not work for recursive constexpr functions using opaque
781 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000782 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
783 }
784};
785
Mike Stump876387b2009-10-27 22:09:17 +0000786} // end anonymous namespace
787
Eli Friedman9a156e52008-11-12 09:44:48 +0000788//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000789// Generic Evaluation
790//===----------------------------------------------------------------------===//
791namespace {
792
793template <class Derived, typename RetTy=void>
794class ExprEvaluatorBase
795 : public ConstStmtVisitor<Derived, RetTy> {
796private:
Richard Smith0b0a0b62011-10-29 20:57:55 +0000797 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000798 return static_cast<Derived*>(this)->Success(V, E);
799 }
800 RetTy DerivedError(const Expr *E) {
801 return static_cast<Derived*>(this)->Error(E);
802 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000803 RetTy DerivedValueInitialization(const Expr *E) {
804 return static_cast<Derived*>(this)->ValueInitialization(E);
805 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000806
807protected:
808 EvalInfo &Info;
809 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
810 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
811
Richard Smith4ce706a2011-10-11 21:43:33 +0000812 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
813
Richard Smithfec09922011-11-01 16:57:24 +0000814 bool MakeTemporary(const Expr *Key, const Expr *Value, LValue &Result) {
815 if (!Evaluate(Info.CurrentCall->Temporaries[Key], Info, Value))
816 return false;
Richard Smith96e0c102011-11-04 02:25:55 +0000817 Result.setExpr(Key, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +0000818 return true;
819 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000820public:
821 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
822
823 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000824 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000825 }
826 RetTy VisitExpr(const Expr *E) {
827 return DerivedError(E);
828 }
829
830 RetTy VisitParenExpr(const ParenExpr *E)
831 { return StmtVisitorTy::Visit(E->getSubExpr()); }
832 RetTy VisitUnaryExtension(const UnaryOperator *E)
833 { return StmtVisitorTy::Visit(E->getSubExpr()); }
834 RetTy VisitUnaryPlus(const UnaryOperator *E)
835 { return StmtVisitorTy::Visit(E->getSubExpr()); }
836 RetTy VisitChooseExpr(const ChooseExpr *E)
837 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
838 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
839 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000840 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
841 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000842
843 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
844 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
845 if (opaque.hasError())
846 return DerivedError(E);
847
848 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +0000849 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000850 return DerivedError(E);
851
852 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
853 }
854
855 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
856 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +0000857 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000858 return DerivedError(E);
859
Richard Smith11562c52011-10-28 17:51:58 +0000860 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +0000861 return StmtVisitorTy::Visit(EvalExpr);
862 }
863
864 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000865 const CCValue *Value = Info.getOpaqueValue(E);
866 if (!Value)
Peter Collingbournee9200682011-05-13 03:29:01 +0000867 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
868 : DerivedError(E));
Richard Smith0b0a0b62011-10-29 20:57:55 +0000869 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000870 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000871
Richard Smith254a73d2011-10-28 22:34:42 +0000872 RetTy VisitCallExpr(const CallExpr *E) {
873 const Expr *Callee = E->getCallee();
874 QualType CalleeType = Callee->getType();
875
876 // FIXME: Handle the case where Callee is a (parenthesized) MemberExpr for a
877 // non-static member function.
878 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember))
879 return DerivedError(E);
880
881 if (!CalleeType->isFunctionType() && !CalleeType->isFunctionPointerType())
882 return DerivedError(E);
883
Richard Smith0b0a0b62011-10-29 20:57:55 +0000884 CCValue Call;
Richard Smith254a73d2011-10-28 22:34:42 +0000885 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
886 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
887 return DerivedError(Callee);
888
889 const FunctionDecl *FD = 0;
890 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Call.getLValueBase()))
891 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
892 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Call.getLValueBase()))
893 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
894 if (!FD)
895 return DerivedError(Callee);
896
897 // Don't call function pointers which have been cast to some other type.
898 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
899 return DerivedError(E);
900
901 const FunctionDecl *Definition;
902 Stmt *Body = FD->getBody(Definition);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000903 CCValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +0000904 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
905
906 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
Richard Smithfec09922011-11-01 16:57:24 +0000907 HandleFunctionCall(Args, Body, Info, Result) &&
908 CheckConstantExpression(Result))
Richard Smith254a73d2011-10-28 22:34:42 +0000909 return DerivedSuccess(Result, E);
910
911 return DerivedError(E);
912 }
913
Richard Smith11562c52011-10-28 17:51:58 +0000914 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
915 return StmtVisitorTy::Visit(E->getInitializer());
916 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000917 RetTy VisitInitListExpr(const InitListExpr *E) {
918 if (Info.getLangOpts().CPlusPlus0x) {
919 if (E->getNumInits() == 0)
920 return DerivedValueInitialization(E);
921 if (E->getNumInits() == 1)
922 return StmtVisitorTy::Visit(E->getInit(0));
923 }
924 return DerivedError(E);
925 }
926 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
927 return DerivedValueInitialization(E);
928 }
929 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
930 return DerivedValueInitialization(E);
931 }
932
Richard Smith11562c52011-10-28 17:51:58 +0000933 RetTy VisitCastExpr(const CastExpr *E) {
934 switch (E->getCastKind()) {
935 default:
936 break;
937
938 case CK_NoOp:
939 return StmtVisitorTy::Visit(E->getSubExpr());
940
941 case CK_LValueToRValue: {
942 LValue LVal;
943 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000944 CCValue RVal;
Richard Smith11562c52011-10-28 17:51:58 +0000945 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
946 return DerivedSuccess(RVal, E);
947 }
948 break;
949 }
950 }
951
952 return DerivedError(E);
953 }
954
Richard Smith4a678122011-10-24 18:44:57 +0000955 /// Visit a value which is evaluated, but whose value is ignored.
956 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000957 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +0000958 if (!Evaluate(Scratch, Info, E))
959 Info.EvalStatus.HasSideEffects = true;
960 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000961};
962
963}
964
965//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000966// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +0000967//
968// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
969// function designators (in C), decl references to void objects (in C), and
970// temporaries (if building with -Wno-address-of-temporary).
971//
972// LValue evaluation produces values comprising a base expression of one of the
973// following types:
974// * DeclRefExpr
975// * MemberExpr for a static member
976// * CompoundLiteralExpr in C
977// * StringLiteral
978// * PredefinedExpr
979// * ObjCEncodeExpr
980// * AddrLabelExpr
981// * BlockExpr
982// * CallExpr for a MakeStringConstant builtin
Richard Smithfec09922011-11-01 16:57:24 +0000983// plus an offset in bytes. It can also produce lvalues referring to locals. In
984// that case, the Frame will point to a stack frame, and the Expr is used as a
985// key to find the relevant temporary's value.
Eli Friedman9a156e52008-11-12 09:44:48 +0000986//===----------------------------------------------------------------------===//
987namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000988class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000989 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000990 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000991 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000992
Peter Collingbournee9200682011-05-13 03:29:01 +0000993 bool Success(const Expr *E) {
Richard Smith96e0c102011-11-04 02:25:55 +0000994 Result.setExpr(E);
John McCall45d55e42010-05-07 21:00:08 +0000995 return true;
996 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000997public:
Mike Stump11289f42009-09-09 15:08:12 +0000998
John McCall45d55e42010-05-07 21:00:08 +0000999 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +00001000 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +00001001
Richard Smith0b0a0b62011-10-29 20:57:55 +00001002 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001003 Result.setFrom(V);
1004 return true;
1005 }
1006 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00001007 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001008 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001009
Richard Smith11562c52011-10-28 17:51:58 +00001010 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
1011
Peter Collingbournee9200682011-05-13 03:29:01 +00001012 bool VisitDeclRefExpr(const DeclRefExpr *E);
1013 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001014 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001015 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1016 bool VisitMemberExpr(const MemberExpr *E);
1017 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
1018 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
1019 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
1020 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001021
Peter Collingbournee9200682011-05-13 03:29:01 +00001022 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00001023 switch (E->getCastKind()) {
1024 default:
Richard Smith11562c52011-10-28 17:51:58 +00001025 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001026
Eli Friedmance3e02a2011-10-11 00:13:24 +00001027 case CK_LValueBitCast:
Richard Smith96e0c102011-11-04 02:25:55 +00001028 if (!Visit(E->getSubExpr()))
1029 return false;
1030 Result.Designator.setInvalid();
1031 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00001032
Richard Smith11562c52011-10-28 17:51:58 +00001033 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
1034 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlssonde55f642009-10-03 16:30:22 +00001035 }
1036 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00001037
Eli Friedman449fe542009-03-23 04:56:01 +00001038 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00001039
Eli Friedman9a156e52008-11-12 09:44:48 +00001040};
1041} // end anonymous namespace
1042
Richard Smith11562c52011-10-28 17:51:58 +00001043/// Evaluate an expression as an lvalue. This can be legitimately called on
1044/// expressions which are not glvalues, in a few cases:
1045/// * function designators in C,
1046/// * "extern void" objects,
1047/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00001048static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001049 assert((E->isGLValue() || E->getType()->isFunctionType() ||
1050 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
1051 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00001052 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001053}
1054
Peter Collingbournee9200682011-05-13 03:29:01 +00001055bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001056 if (isa<FunctionDecl>(E->getDecl()))
John McCall45d55e42010-05-07 21:00:08 +00001057 return Success(E);
Richard Smith11562c52011-10-28 17:51:58 +00001058 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
1059 return VisitVarDecl(E, VD);
1060 return Error(E);
1061}
Richard Smith733237d2011-10-24 23:14:33 +00001062
Richard Smith11562c52011-10-28 17:51:58 +00001063bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00001064 if (!VD->getType()->isReferenceType()) {
1065 if (isa<ParmVarDecl>(VD)) {
Richard Smith96e0c102011-11-04 02:25:55 +00001066 Result.setExpr(E, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00001067 return true;
1068 }
Richard Smith11562c52011-10-28 17:51:58 +00001069 return Success(E);
Richard Smithfec09922011-11-01 16:57:24 +00001070 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00001071
Richard Smith0b0a0b62011-10-29 20:57:55 +00001072 CCValue V;
Richard Smithfec09922011-11-01 16:57:24 +00001073 if (EvaluateVarDeclInit(Info, VD, Info.CurrentCall, V))
Richard Smith0b0a0b62011-10-29 20:57:55 +00001074 return Success(V, E);
Richard Smith11562c52011-10-28 17:51:58 +00001075
1076 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +00001077}
1078
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001079bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
1080 const MaterializeTemporaryExpr *E) {
Richard Smithfec09922011-11-01 16:57:24 +00001081 return MakeTemporary(E, E->GetTemporaryExpr(), Result);
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001082}
1083
Peter Collingbournee9200682011-05-13 03:29:01 +00001084bool
1085LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001086 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1087 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
1088 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00001089 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001090}
1091
Peter Collingbournee9200682011-05-13 03:29:01 +00001092bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001093 // Handle static data members.
1094 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
1095 VisitIgnoredValue(E->getBase());
1096 return VisitVarDecl(E, VD);
1097 }
1098
Richard Smith254a73d2011-10-28 22:34:42 +00001099 // Handle static member functions.
1100 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
1101 if (MD->isStatic()) {
1102 VisitIgnoredValue(E->getBase());
1103 return Success(E);
1104 }
1105 }
1106
Eli Friedman9a156e52008-11-12 09:44:48 +00001107 QualType Ty;
1108 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +00001109 if (!EvaluatePointer(E->getBase(), Result, Info))
1110 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001111 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +00001112 } else {
John McCall45d55e42010-05-07 21:00:08 +00001113 if (!Visit(E->getBase()))
1114 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001115 Ty = E->getBase()->getType();
1116 }
1117
Peter Collingbournee9200682011-05-13 03:29:01 +00001118 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +00001119 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001120
Peter Collingbournee9200682011-05-13 03:29:01 +00001121 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001122 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +00001123 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001124
1125 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +00001126 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001127
Eli Friedmana3c122d2011-07-07 01:54:01 +00001128 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001129 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Richard Smith96e0c102011-11-04 02:25:55 +00001130 Result.Designator.addDecl(FD);
John McCall45d55e42010-05-07 21:00:08 +00001131 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +00001132}
1133
Peter Collingbournee9200682011-05-13 03:29:01 +00001134bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001135 // FIXME: Deal with vectors as array subscript bases.
1136 if (E->getBase()->getType()->isVectorType())
1137 return false;
1138
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001139 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00001140 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001141
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001142 APSInt Index;
1143 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00001144 return false;
Richard Smith96e0c102011-11-04 02:25:55 +00001145 uint64_t IndexValue
1146 = Index.isSigned() ? static_cast<uint64_t>(Index.getSExtValue())
1147 : Index.getZExtValue();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001148
Ken Dyck40775002010-01-11 17:06:35 +00001149 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
Richard Smith96e0c102011-11-04 02:25:55 +00001150 Result.Offset += IndexValue * ElementSize;
1151 Result.Designator.adjustIndex(IndexValue);
John McCall45d55e42010-05-07 21:00:08 +00001152 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001153}
Eli Friedman9a156e52008-11-12 09:44:48 +00001154
Peter Collingbournee9200682011-05-13 03:29:01 +00001155bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00001156 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00001157}
1158
Eli Friedman9a156e52008-11-12 09:44:48 +00001159//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001160// Pointer Evaluation
1161//===----------------------------------------------------------------------===//
1162
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001163namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001164class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001165 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001166 LValue &Result;
1167
Peter Collingbournee9200682011-05-13 03:29:01 +00001168 bool Success(const Expr *E) {
Richard Smith96e0c102011-11-04 02:25:55 +00001169 Result.setExpr(E);
John McCall45d55e42010-05-07 21:00:08 +00001170 return true;
1171 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001172public:
Mike Stump11289f42009-09-09 15:08:12 +00001173
John McCall45d55e42010-05-07 21:00:08 +00001174 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001175 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001176
Richard Smith0b0a0b62011-10-29 20:57:55 +00001177 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001178 Result.setFrom(V);
1179 return true;
1180 }
1181 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +00001182 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001183 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001184 bool ValueInitialization(const Expr *E) {
1185 return Success((Expr*)0);
1186 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001187
John McCall45d55e42010-05-07 21:00:08 +00001188 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001189 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00001190 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001191 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00001192 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001193 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00001194 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001195 bool VisitCallExpr(const CallExpr *E);
1196 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00001197 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00001198 return Success(E);
1199 return false;
Mike Stumpa6703322009-02-19 22:01:56 +00001200 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001201 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +00001202 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +00001203
Eli Friedman449fe542009-03-23 04:56:01 +00001204 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001205};
Chris Lattner05706e882008-07-11 18:11:29 +00001206} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001207
John McCall45d55e42010-05-07 21:00:08 +00001208static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001209 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00001210 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00001211}
1212
John McCall45d55e42010-05-07 21:00:08 +00001213bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001214 if (E->getOpcode() != BO_Add &&
1215 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +00001216 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001217
Chris Lattner05706e882008-07-11 18:11:29 +00001218 const Expr *PExp = E->getLHS();
1219 const Expr *IExp = E->getRHS();
1220 if (IExp->getType()->isPointerType())
1221 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00001222
John McCall45d55e42010-05-07 21:00:08 +00001223 if (!EvaluatePointer(PExp, Result, Info))
1224 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001225
John McCall45d55e42010-05-07 21:00:08 +00001226 llvm::APSInt Offset;
1227 if (!EvaluateInteger(IExp, Offset, Info))
1228 return false;
1229 int64_t AdditionalOffset
1230 = Offset.isSigned() ? Offset.getSExtValue()
1231 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00001232 if (E->getOpcode() == BO_Sub)
1233 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00001234
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001235 // Compute the new offset in the appropriate width.
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001236 QualType PointeeType =
1237 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +00001238 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +00001239
Anders Carlssonef56fba2009-02-19 04:55:58 +00001240 // Explicitly handle GNU void* and function pointer arithmetic extensions.
1241 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +00001242 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +00001243 else
John McCall45d55e42010-05-07 21:00:08 +00001244 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +00001245
Richard Smith96e0c102011-11-04 02:25:55 +00001246 Result.Offset += AdditionalOffset * SizeOfPointee;
1247 Result.Designator.adjustIndex(AdditionalOffset);
John McCall45d55e42010-05-07 21:00:08 +00001248 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001249}
Eli Friedman9a156e52008-11-12 09:44:48 +00001250
John McCall45d55e42010-05-07 21:00:08 +00001251bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1252 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001253}
Mike Stump11289f42009-09-09 15:08:12 +00001254
Chris Lattner05706e882008-07-11 18:11:29 +00001255
Peter Collingbournee9200682011-05-13 03:29:01 +00001256bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1257 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00001258
Eli Friedman847a2bc2009-12-27 05:43:15 +00001259 switch (E->getCastKind()) {
1260 default:
1261 break;
1262
John McCalle3027922010-08-25 11:45:40 +00001263 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00001264 case CK_CPointerToObjCPointerCast:
1265 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001266 case CK_AnyPointerToBlockPointerCast:
Richard Smith96e0c102011-11-04 02:25:55 +00001267 if (!Visit(SubExpr))
1268 return false;
1269 Result.Designator.setInvalid();
1270 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00001271
Anders Carlsson18275092010-10-31 20:41:46 +00001272 case CK_DerivedToBase:
1273 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001274 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00001275 return false;
1276
1277 // Now figure out the necessary offset to add to the baseLV to get from
1278 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +00001279 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +00001280
1281 QualType Ty = E->getSubExpr()->getType();
1282 const CXXRecordDecl *DerivedDecl =
1283 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
1284
1285 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1286 PathE = E->path_end(); PathI != PathE; ++PathI) {
1287 const CXXBaseSpecifier *Base = *PathI;
1288
1289 // FIXME: If the base is virtual, we'd need to determine the type of the
1290 // most derived class and we don't support that right now.
1291 if (Base->isVirtual())
1292 return false;
1293
1294 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1295 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1296
Richard Smith0b0a0b62011-10-29 20:57:55 +00001297 Result.getLValueOffset() += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +00001298 DerivedDecl = BaseDecl;
1299 }
1300
Richard Smith96e0c102011-11-04 02:25:55 +00001301 // FIXME
1302 Result.Designator.setInvalid();
1303
Anders Carlsson18275092010-10-31 20:41:46 +00001304 return true;
1305 }
1306
Richard Smith0b0a0b62011-10-29 20:57:55 +00001307 case CK_NullToPointer:
1308 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00001309
John McCalle3027922010-08-25 11:45:40 +00001310 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001311 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00001312 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00001313 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00001314
John McCall45d55e42010-05-07 21:00:08 +00001315 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001316 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1317 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
John McCall45d55e42010-05-07 21:00:08 +00001318 Result.Base = 0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001319 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00001320 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00001321 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00001322 return true;
1323 } else {
1324 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001325 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00001326 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001327 }
1328 }
John McCalle3027922010-08-25 11:45:40 +00001329 case CK_ArrayToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00001330 // FIXME: Support array-to-pointer decay on array rvalues.
1331 if (!SubExpr->isGLValue())
1332 return Error(E);
Richard Smith96e0c102011-11-04 02:25:55 +00001333 if (!EvaluateLValue(SubExpr, Result, Info))
1334 return false;
1335 // The result is a pointer to the first element of the array.
1336 Result.Designator.addIndex(0);
1337 return true;
Richard Smithdd785442011-10-31 20:57:44 +00001338
John McCalle3027922010-08-25 11:45:40 +00001339 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00001340 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001341 }
1342
Richard Smith11562c52011-10-28 17:51:58 +00001343 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00001344}
Chris Lattner05706e882008-07-11 18:11:29 +00001345
Peter Collingbournee9200682011-05-13 03:29:01 +00001346bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +00001347 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +00001348 Builtin::BI__builtin___CFStringMakeConstantString ||
1349 E->isBuiltinCall(Info.Ctx) ==
1350 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +00001351 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00001352
Peter Collingbournee9200682011-05-13 03:29:01 +00001353 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001354}
Chris Lattner05706e882008-07-11 18:11:29 +00001355
1356//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001357// Vector Evaluation
1358//===----------------------------------------------------------------------===//
1359
1360namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001361 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00001362 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1363 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001364 public:
Mike Stump11289f42009-09-09 15:08:12 +00001365
Richard Smith2d406342011-10-22 21:10:00 +00001366 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1367 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001368
Richard Smith2d406342011-10-22 21:10:00 +00001369 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1370 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1371 // FIXME: remove this APValue copy.
1372 Result = APValue(V.data(), V.size());
1373 return true;
1374 }
1375 bool Success(const APValue &V, const Expr *E) {
1376 Result = V;
1377 return true;
1378 }
1379 bool Error(const Expr *E) { return false; }
1380 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00001381
Richard Smith2d406342011-10-22 21:10:00 +00001382 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00001383 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00001384 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00001385 bool VisitInitListExpr(const InitListExpr *E);
1386 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001387 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001388 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00001389 // shufflevector, ExtVectorElementExpr
1390 // (Note that these require implementing conversions
1391 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001392 };
1393} // end anonymous namespace
1394
1395static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001396 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00001397 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001398}
1399
Richard Smith2d406342011-10-22 21:10:00 +00001400bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1401 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001402 QualType EltTy = VTy->getElementType();
1403 unsigned NElts = VTy->getNumElements();
1404 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +00001405
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001406 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00001407 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001408
Eli Friedmanc757de22011-03-25 00:43:55 +00001409 switch (E->getCastKind()) {
1410 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00001411 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00001412 if (SETy->isIntegerType()) {
1413 APSInt IntResult;
1414 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001415 return Error(E);
1416 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00001417 } else if (SETy->isRealFloatingType()) {
1418 APFloat F(0.0);
1419 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001420 return Error(E);
1421 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00001422 } else {
Richard Smith2d406342011-10-22 21:10:00 +00001423 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001424 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001425
1426 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00001427 SmallVector<APValue, 4> Elts(NElts, Val);
1428 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00001429 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001430 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +00001431 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +00001432 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +00001433 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001434
Eli Friedmanc757de22011-03-25 00:43:55 +00001435 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +00001436 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +00001437
Eli Friedmanc757de22011-03-25 00:43:55 +00001438 APSInt Init;
1439 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001440 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001441
Eli Friedmanc757de22011-03-25 00:43:55 +00001442 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1443 "Vectors must be composed of ints or floats");
1444
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001445 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +00001446 for (unsigned i = 0; i != NElts; ++i) {
1447 APSInt Tmp = Init.extOrTrunc(EltWidth);
1448
1449 if (EltTy->isIntegerType())
1450 Elts.push_back(APValue(Tmp));
1451 else
1452 Elts.push_back(APValue(APFloat(Tmp)));
1453
1454 Init >>= EltWidth;
1455 }
Richard Smith2d406342011-10-22 21:10:00 +00001456 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001457 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001458 default:
Richard Smith11562c52011-10-28 17:51:58 +00001459 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001460 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001461}
1462
Richard Smith2d406342011-10-22 21:10:00 +00001463bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001464VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00001465 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001466 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00001467 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00001468
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001469 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001470 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001471
John McCall875679e2010-06-11 17:54:15 +00001472 // If a vector is initialized with a single element, that value
1473 // becomes every element of the vector, not just the first.
1474 // This is the behavior described in the IBM AltiVec documentation.
1475 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00001476
1477 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00001478 // vector (OpenCL 6.1.6).
1479 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00001480 return Visit(E->getInit(0));
1481
John McCall875679e2010-06-11 17:54:15 +00001482 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001483 if (EltTy->isIntegerType()) {
1484 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00001485 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001486 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001487 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001488 } else {
1489 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00001490 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001491 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001492 InitValue = APValue(f);
1493 }
1494 for (unsigned i = 0; i < NumElements; i++) {
1495 Elements.push_back(InitValue);
1496 }
1497 } else {
1498 for (unsigned i = 0; i < NumElements; i++) {
1499 if (EltTy->isIntegerType()) {
1500 llvm::APSInt sInt(32);
1501 if (i < NumInits) {
1502 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001503 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001504 } else {
1505 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1506 }
1507 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00001508 } else {
John McCall875679e2010-06-11 17:54:15 +00001509 llvm::APFloat f(0.0);
1510 if (i < NumInits) {
1511 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001512 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001513 } else {
1514 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1515 }
1516 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00001517 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001518 }
1519 }
Richard Smith2d406342011-10-22 21:10:00 +00001520 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001521}
1522
Richard Smith2d406342011-10-22 21:10:00 +00001523bool
1524VectorExprEvaluator::ValueInitialization(const Expr *E) {
1525 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00001526 QualType EltTy = VT->getElementType();
1527 APValue ZeroElement;
1528 if (EltTy->isIntegerType())
1529 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1530 else
1531 ZeroElement =
1532 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1533
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001534 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00001535 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001536}
1537
Richard Smith2d406342011-10-22 21:10:00 +00001538bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00001539 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00001540 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001541}
1542
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001543//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001544// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001545//
1546// As a GNU extension, we support casting pointers to sufficiently-wide integer
1547// types and back in constant folding. Integer values are thus represented
1548// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00001549//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001550
1551namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001552class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001553 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001554 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001555public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001556 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001557 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001558
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001559 bool Success(const llvm::APSInt &SI, const Expr *E) {
1560 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001561 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001562 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001563 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001564 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001565 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001566 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001567 return true;
1568 }
1569
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001570 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001571 assert(E->getType()->isIntegralOrEnumerationType() &&
1572 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001573 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001574 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001575 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001576 Result.getInt().setIsUnsigned(
1577 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001578 return true;
1579 }
1580
1581 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001582 assert(E->getType()->isIntegralOrEnumerationType() &&
1583 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001584 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001585 return true;
1586 }
1587
Ken Dyckdbc01912011-03-11 02:13:43 +00001588 bool Success(CharUnits Size, const Expr *E) {
1589 return Success(Size.getQuantity(), E);
1590 }
1591
1592
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001593 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001594 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001595 if (Info.EvalStatus.Diag == 0) {
1596 Info.EvalStatus.DiagLoc = L;
1597 Info.EvalStatus.Diag = D;
1598 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001599 }
Chris Lattner99415702008-07-12 00:14:42 +00001600 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001601 }
Mike Stump11289f42009-09-09 15:08:12 +00001602
Richard Smith0b0a0b62011-10-29 20:57:55 +00001603 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00001604 if (V.isLValue()) {
1605 Result = V;
1606 return true;
1607 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001608 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001609 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001610 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001611 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001612 }
Mike Stump11289f42009-09-09 15:08:12 +00001613
Richard Smith4ce706a2011-10-11 21:43:33 +00001614 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1615
Peter Collingbournee9200682011-05-13 03:29:01 +00001616 //===--------------------------------------------------------------------===//
1617 // Visitor Methods
1618 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001619
Chris Lattner7174bf32008-07-12 00:38:25 +00001620 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001621 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001622 }
1623 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001624 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001625 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001626
1627 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1628 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001629 if (CheckReferencedDecl(E, E->getDecl()))
1630 return true;
1631
1632 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001633 }
1634 bool VisitMemberExpr(const MemberExpr *E) {
1635 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00001636 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001637 return true;
1638 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001639
1640 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001641 }
1642
Peter Collingbournee9200682011-05-13 03:29:01 +00001643 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001644 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001645 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001646 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001647
Peter Collingbournee9200682011-05-13 03:29:01 +00001648 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001649 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001650
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001651 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001652 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001653 }
Mike Stump11289f42009-09-09 15:08:12 +00001654
Richard Smith4ce706a2011-10-11 21:43:33 +00001655 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001656 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001657 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001658 }
1659
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001660 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001661 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001662 }
1663
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001664 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1665 return Success(E->getValue(), E);
1666 }
1667
John Wiegley6242b6a2011-04-28 00:16:57 +00001668 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1669 return Success(E->getValue(), E);
1670 }
1671
John Wiegleyf9f65842011-04-25 06:54:41 +00001672 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1673 return Success(E->getValue(), E);
1674 }
1675
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001676 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001677 bool VisitUnaryImag(const UnaryOperator *E);
1678
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001679 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001680 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001681
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001682private:
Ken Dyck160146e2010-01-27 17:10:57 +00001683 CharUnits GetAlignOfExpr(const Expr *E);
1684 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001685 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001686 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001687 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001688};
Chris Lattner05706e882008-07-11 18:11:29 +00001689} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001690
Richard Smith11562c52011-10-28 17:51:58 +00001691/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1692/// produce either the integer value or a pointer.
1693///
1694/// GCC has a heinous extension which folds casts between pointer types and
1695/// pointer-sized integral types. We support this by allowing the evaluation of
1696/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1697/// Some simple arithmetic on such values is supported (they are treated much
1698/// like char*).
Richard Smith0b0a0b62011-10-29 20:57:55 +00001699static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
1700 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001701 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001702 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001703}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001704
Daniel Dunbarce399542009-02-20 18:22:23 +00001705static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001706 CCValue Val;
Daniel Dunbarce399542009-02-20 18:22:23 +00001707 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1708 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001709 Result = Val.getInt();
1710 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001711}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001712
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001713bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001714 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001715 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001716 // Check for signedness/width mismatches between E type and ECD value.
1717 bool SameSign = (ECD->getInitVal().isSigned()
1718 == E->getType()->isSignedIntegerOrEnumerationType());
1719 bool SameWidth = (ECD->getInitVal().getBitWidth()
1720 == Info.Ctx.getIntWidth(E->getType()));
1721 if (SameSign && SameWidth)
1722 return Success(ECD->getInitVal(), E);
1723 else {
1724 // Get rid of mismatch (otherwise Success assertions will fail)
1725 // by computing a new value matching the type of E.
1726 llvm::APSInt Val = ECD->getInitVal();
1727 if (!SameSign)
1728 Val.setIsSigned(!ECD->getInitVal().isSigned());
1729 if (!SameWidth)
1730 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1731 return Success(Val, E);
1732 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001733 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001734 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001735}
1736
Chris Lattner86ee2862008-10-06 06:40:35 +00001737/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1738/// as GCC.
1739static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1740 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001741 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001742 enum gcc_type_class {
1743 no_type_class = -1,
1744 void_type_class, integer_type_class, char_type_class,
1745 enumeral_type_class, boolean_type_class,
1746 pointer_type_class, reference_type_class, offset_type_class,
1747 real_type_class, complex_type_class,
1748 function_type_class, method_type_class,
1749 record_type_class, union_type_class,
1750 array_type_class, string_type_class,
1751 lang_type_class
1752 };
Mike Stump11289f42009-09-09 15:08:12 +00001753
1754 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001755 // ideal, however it is what gcc does.
1756 if (E->getNumArgs() == 0)
1757 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001758
Chris Lattner86ee2862008-10-06 06:40:35 +00001759 QualType ArgTy = E->getArg(0)->getType();
1760 if (ArgTy->isVoidType())
1761 return void_type_class;
1762 else if (ArgTy->isEnumeralType())
1763 return enumeral_type_class;
1764 else if (ArgTy->isBooleanType())
1765 return boolean_type_class;
1766 else if (ArgTy->isCharType())
1767 return string_type_class; // gcc doesn't appear to use char_type_class
1768 else if (ArgTy->isIntegerType())
1769 return integer_type_class;
1770 else if (ArgTy->isPointerType())
1771 return pointer_type_class;
1772 else if (ArgTy->isReferenceType())
1773 return reference_type_class;
1774 else if (ArgTy->isRealType())
1775 return real_type_class;
1776 else if (ArgTy->isComplexType())
1777 return complex_type_class;
1778 else if (ArgTy->isFunctionType())
1779 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001780 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001781 return record_type_class;
1782 else if (ArgTy->isUnionType())
1783 return union_type_class;
1784 else if (ArgTy->isArrayType())
1785 return array_type_class;
1786 else if (ArgTy->isUnionType())
1787 return union_type_class;
1788 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001789 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001790 return -1;
1791}
1792
John McCall95007602010-05-10 23:27:23 +00001793/// Retrieves the "underlying object type" of the given expression,
1794/// as used by __builtin_object_size.
1795QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1796 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1797 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1798 return VD->getType();
1799 } else if (isa<CompoundLiteralExpr>(E)) {
1800 return E->getType();
1801 }
1802
1803 return QualType();
1804}
1805
Peter Collingbournee9200682011-05-13 03:29:01 +00001806bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001807 // TODO: Perhaps we should let LLVM lower this?
1808 LValue Base;
1809 if (!EvaluatePointer(E->getArg(0), Base, Info))
1810 return false;
1811
1812 // If we can prove the base is null, lower to zero now.
1813 const Expr *LVBase = Base.getLValueBase();
1814 if (!LVBase) return Success(0, E);
1815
1816 QualType T = GetObjectType(LVBase);
1817 if (T.isNull() ||
1818 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001819 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001820 T->isVariablyModifiedType() ||
1821 T->isDependentType())
1822 return false;
1823
1824 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1825 CharUnits Offset = Base.getLValueOffset();
1826
1827 if (!Offset.isNegative() && Offset <= Size)
1828 Size -= Offset;
1829 else
1830 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001831 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001832}
1833
Peter Collingbournee9200682011-05-13 03:29:01 +00001834bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001835 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001836 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001837 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001838
1839 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001840 if (TryEvaluateBuiltinObjectSize(E))
1841 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001842
Eric Christopher99469702010-01-19 22:58:35 +00001843 // If evaluating the argument has side-effects we can't determine
1844 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001845 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001846 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001847 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001848 return Success(0, E);
1849 }
Mike Stump876387b2009-10-27 22:09:17 +00001850
Mike Stump722cedf2009-10-26 18:35:08 +00001851 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1852 }
1853
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001854 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001855 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001856
Anders Carlsson4c76e932008-11-24 04:21:33 +00001857 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001858 // __builtin_constant_p always has one operand: it returns true if that
1859 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001860 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001861
1862 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001863 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001864 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001865 return Success(Operand, E);
1866 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001867
1868 case Builtin::BI__builtin_expect:
1869 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001870
1871 case Builtin::BIstrlen:
1872 case Builtin::BI__builtin_strlen:
1873 // As an extension, we support strlen() and __builtin_strlen() as constant
1874 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001875 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001876 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1877 // The string literal may have embedded null characters. Find the first
1878 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001879 StringRef Str = S->getString();
1880 StringRef::size_type Pos = Str.find(0);
1881 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001882 Str = Str.substr(0, Pos);
1883
1884 return Success(Str.size(), E);
1885 }
1886
1887 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001888
1889 case Builtin::BI__atomic_is_lock_free: {
1890 APSInt SizeVal;
1891 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1892 return false;
1893
1894 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1895 // of two less than the maximum inline atomic width, we know it is
1896 // lock-free. If the size isn't a power of two, or greater than the
1897 // maximum alignment where we promote atomics, we know it is not lock-free
1898 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1899 // the answer can only be determined at runtime; for example, 16-byte
1900 // atomics have lock-free implementations on some, but not all,
1901 // x86-64 processors.
1902
1903 // Check power-of-two.
1904 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1905 if (!Size.isPowerOfTwo())
1906#if 0
1907 // FIXME: Suppress this folding until the ABI for the promotion width
1908 // settles.
1909 return Success(0, E);
1910#else
1911 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1912#endif
1913
1914#if 0
1915 // Check against promotion width.
1916 // FIXME: Suppress this folding until the ABI for the promotion width
1917 // settles.
1918 unsigned PromoteWidthBits =
1919 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1920 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1921 return Success(0, E);
1922#endif
1923
1924 // Check against inlining width.
1925 unsigned InlineWidthBits =
1926 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1927 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1928 return Success(1, E);
1929
1930 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1931 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001932 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001933}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001934
Richard Smith8b3497e2011-10-31 01:37:14 +00001935static bool HasSameBase(const LValue &A, const LValue &B) {
1936 if (!A.getLValueBase())
1937 return !B.getLValueBase();
1938 if (!B.getLValueBase())
1939 return false;
1940
1941 if (A.getLValueBase() != B.getLValueBase()) {
1942 const Decl *ADecl = GetLValueBaseDecl(A);
1943 if (!ADecl)
1944 return false;
1945 const Decl *BDecl = GetLValueBaseDecl(B);
1946 if (ADecl != BDecl)
1947 return false;
1948 }
1949
1950 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00001951 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00001952}
1953
Chris Lattnere13042c2008-07-11 19:10:17 +00001954bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001955 if (E->isAssignmentOp())
1956 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1957
John McCalle3027922010-08-25 11:45:40 +00001958 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00001959 VisitIgnoredValue(E->getLHS());
1960 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00001961 }
1962
1963 if (E->isLogicalOp()) {
1964 // These need to be handled specially because the operands aren't
1965 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001966 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001967
Richard Smith11562c52011-10-28 17:51:58 +00001968 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001969 // We were able to evaluate the LHS, see if we can get away with not
1970 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001971 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001972 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001973
Richard Smith11562c52011-10-28 17:51:58 +00001974 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001975 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001976 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001977 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001978 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001979 }
1980 } else {
Richard Smith11562c52011-10-28 17:51:58 +00001981 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001982 // We can't evaluate the LHS; however, sometimes the result
1983 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001984 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1985 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001986 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001987 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00001988 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001989
1990 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001991 }
1992 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001993 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001994
Eli Friedman5a332ea2008-11-13 06:09:17 +00001995 return false;
1996 }
1997
Anders Carlssonacc79812008-11-16 07:17:21 +00001998 QualType LHSTy = E->getLHS()->getType();
1999 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002000
2001 if (LHSTy->isAnyComplexType()) {
2002 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00002003 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002004
2005 if (!EvaluateComplex(E->getLHS(), LHS, Info))
2006 return false;
2007
2008 if (!EvaluateComplex(E->getRHS(), RHS, Info))
2009 return false;
2010
2011 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00002012 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002013 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00002014 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002015 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
2016
John McCalle3027922010-08-25 11:45:40 +00002017 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002018 return Success((CR_r == APFloat::cmpEqual &&
2019 CR_i == APFloat::cmpEqual), E);
2020 else {
John McCalle3027922010-08-25 11:45:40 +00002021 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002022 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00002023 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00002024 CR_r == APFloat::cmpLessThan ||
2025 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00002026 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00002027 CR_i == APFloat::cmpLessThan ||
2028 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002029 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002030 } else {
John McCalle3027922010-08-25 11:45:40 +00002031 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002032 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
2033 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
2034 else {
John McCalle3027922010-08-25 11:45:40 +00002035 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002036 "Invalid compex comparison.");
2037 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
2038 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
2039 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002040 }
2041 }
Mike Stump11289f42009-09-09 15:08:12 +00002042
Anders Carlssonacc79812008-11-16 07:17:21 +00002043 if (LHSTy->isRealFloatingType() &&
2044 RHSTy->isRealFloatingType()) {
2045 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00002046
Anders Carlssonacc79812008-11-16 07:17:21 +00002047 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2048 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002049
Anders Carlssonacc79812008-11-16 07:17:21 +00002050 if (!EvaluateFloat(E->getLHS(), LHS, Info))
2051 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002052
Anders Carlssonacc79812008-11-16 07:17:21 +00002053 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00002054
Anders Carlssonacc79812008-11-16 07:17:21 +00002055 switch (E->getOpcode()) {
2056 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002057 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00002058 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002059 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00002060 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002061 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00002062 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002063 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00002064 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00002065 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002066 E);
John McCalle3027922010-08-25 11:45:40 +00002067 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002068 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00002069 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00002070 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00002071 || CR == APFloat::cmpLessThan
2072 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00002073 }
Anders Carlssonacc79812008-11-16 07:17:21 +00002074 }
Mike Stump11289f42009-09-09 15:08:12 +00002075
Eli Friedmana38da572009-04-28 19:17:36 +00002076 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00002077 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00002078 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002079 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
2080 return false;
Eli Friedman64004332009-03-23 04:38:34 +00002081
John McCall45d55e42010-05-07 21:00:08 +00002082 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002083 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
2084 return false;
Eli Friedman64004332009-03-23 04:38:34 +00002085
Richard Smith8b3497e2011-10-31 01:37:14 +00002086 // Reject differing bases from the normal codepath; we special-case
2087 // comparisons to null.
2088 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00002089 // Inequalities and subtractions between unrelated pointers have
2090 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00002091 if (!E->isEqualityOp())
2092 return false;
Eli Friedmanc6be94b2011-10-31 22:28:05 +00002093 // A constant address may compare equal to the address of a symbol.
2094 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00002095 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00002096 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
2097 (!RHSValue.Base && !RHSValue.Offset.isZero()))
2098 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002099 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00002100 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00002101 // distinct. However, we do know that the address of a literal will be
2102 // non-null.
2103 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
2104 LHSValue.Base && RHSValue.Base)
Eli Friedman334046a2009-06-14 02:17:33 +00002105 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002106 // We can't tell whether weak symbols will end up pointing to the same
2107 // object.
2108 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Eli Friedman334046a2009-06-14 02:17:33 +00002109 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002110 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00002111 // (Note that clang defaults to -fmerge-all-constants, which can
2112 // lead to inconsistent results for comparisons involving the address
2113 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00002114 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00002115 }
Eli Friedman64004332009-03-23 04:38:34 +00002116
John McCalle3027922010-08-25 11:45:40 +00002117 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00002118 QualType Type = E->getLHS()->getType();
2119 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002120
Ken Dyck02990832010-01-15 12:37:54 +00002121 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00002122 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00002123 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00002124
Ken Dyck02990832010-01-15 12:37:54 +00002125 CharUnits Diff = LHSValue.getLValueOffset() -
2126 RHSValue.getLValueOffset();
2127 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002128 }
Richard Smith8b3497e2011-10-31 01:37:14 +00002129
2130 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
2131 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
2132 switch (E->getOpcode()) {
2133 default: llvm_unreachable("missing comparison operator");
2134 case BO_LT: return Success(LHSOffset < RHSOffset, E);
2135 case BO_GT: return Success(LHSOffset > RHSOffset, E);
2136 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
2137 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
2138 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
2139 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002140 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002141 }
2142 }
Douglas Gregorb90df602010-06-16 00:17:44 +00002143 if (!LHSTy->isIntegralOrEnumerationType() ||
2144 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002145 // We can't continue from here for non-integral types, and they
2146 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00002147 return false;
2148 }
2149
Anders Carlsson9c181652008-07-08 14:35:21 +00002150 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002151 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00002152 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00002153 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00002154
Richard Smith11562c52011-10-28 17:51:58 +00002155 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002156 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002157 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00002158
2159 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00002160 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00002161 CharUnits AdditionalOffset = CharUnits::fromQuantity(
2162 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00002163 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00002164 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00002165 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00002166 LHSVal.getLValueOffset() -= AdditionalOffset;
2167 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00002168 return true;
2169 }
2170
2171 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00002172 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00002173 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002174 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
2175 LHSVal.getInt().getZExtValue());
2176 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00002177 return true;
2178 }
2179
2180 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00002181 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00002182 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00002183
Richard Smith11562c52011-10-28 17:51:58 +00002184 APSInt &LHS = LHSVal.getInt();
2185 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00002186
Anders Carlsson9c181652008-07-08 14:35:21 +00002187 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002188 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002189 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00002190 case BO_Mul: return Success(LHS * RHS, E);
2191 case BO_Add: return Success(LHS + RHS, E);
2192 case BO_Sub: return Success(LHS - RHS, E);
2193 case BO_And: return Success(LHS & RHS, E);
2194 case BO_Xor: return Success(LHS ^ RHS, E);
2195 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002196 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00002197 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002198 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002199 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002200 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00002201 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002202 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002203 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002204 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00002205 // During constant-folding, a negative shift is an opposite shift.
2206 if (RHS.isSigned() && RHS.isNegative()) {
2207 RHS = -RHS;
2208 goto shift_right;
2209 }
2210
2211 shift_left:
2212 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00002213 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2214 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002215 }
John McCalle3027922010-08-25 11:45:40 +00002216 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00002217 // During constant-folding, a negative shift is an opposite shift.
2218 if (RHS.isSigned() && RHS.isNegative()) {
2219 RHS = -RHS;
2220 goto shift_left;
2221 }
2222
2223 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00002224 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00002225 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2226 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002227 }
Mike Stump11289f42009-09-09 15:08:12 +00002228
Richard Smith11562c52011-10-28 17:51:58 +00002229 case BO_LT: return Success(LHS < RHS, E);
2230 case BO_GT: return Success(LHS > RHS, E);
2231 case BO_LE: return Success(LHS <= RHS, E);
2232 case BO_GE: return Success(LHS >= RHS, E);
2233 case BO_EQ: return Success(LHS == RHS, E);
2234 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00002235 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002236}
2237
Ken Dyck160146e2010-01-27 17:10:57 +00002238CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002239 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2240 // the result is the size of the referenced type."
2241 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2242 // result shall be the alignment of the referenced type."
2243 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2244 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00002245
2246 // __alignof is defined to return the preferred alignment.
2247 return Info.Ctx.toCharUnitsFromBits(
2248 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00002249}
2250
Ken Dyck160146e2010-01-27 17:10:57 +00002251CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00002252 E = E->IgnoreParens();
2253
2254 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00002255 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00002256 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002257 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2258 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00002259
Chris Lattner68061312009-01-24 21:53:27 +00002260 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002261 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2262 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00002263
Chris Lattner24aeeab2009-01-24 21:09:06 +00002264 return GetAlignOfType(E->getType());
2265}
2266
2267
Peter Collingbournee190dee2011-03-11 19:24:49 +00002268/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2269/// a result as the expression's type.
2270bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2271 const UnaryExprOrTypeTraitExpr *E) {
2272 switch(E->getKind()) {
2273 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00002274 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00002275 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002276 else
Ken Dyckdbc01912011-03-11 02:13:43 +00002277 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002278 }
Eli Friedman64004332009-03-23 04:38:34 +00002279
Peter Collingbournee190dee2011-03-11 19:24:49 +00002280 case UETT_VecStep: {
2281 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00002282
Peter Collingbournee190dee2011-03-11 19:24:49 +00002283 if (Ty->isVectorType()) {
2284 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00002285
Peter Collingbournee190dee2011-03-11 19:24:49 +00002286 // The vec_step built-in functions that take a 3-component
2287 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2288 if (n == 3)
2289 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002290
Peter Collingbournee190dee2011-03-11 19:24:49 +00002291 return Success(n, E);
2292 } else
2293 return Success(1, E);
2294 }
2295
2296 case UETT_SizeOf: {
2297 QualType SrcTy = E->getTypeOfArgument();
2298 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2299 // the result is the size of the referenced type."
2300 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2301 // result shall be the alignment of the referenced type."
2302 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2303 SrcTy = Ref->getPointeeType();
2304
2305 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2306 // extension.
2307 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
2308 return Success(1, E);
2309
2310 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2311 if (!SrcTy->isConstantSizeType())
2312 return false;
2313
2314 // Get information about the size.
2315 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
2316 }
2317 }
2318
2319 llvm_unreachable("unknown expr/type trait");
2320 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002321}
2322
Peter Collingbournee9200682011-05-13 03:29:01 +00002323bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00002324 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00002325 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00002326 if (n == 0)
2327 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002328 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00002329 for (unsigned i = 0; i != n; ++i) {
2330 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
2331 switch (ON.getKind()) {
2332 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00002333 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00002334 APSInt IdxResult;
2335 if (!EvaluateInteger(Idx, IdxResult, Info))
2336 return false;
2337 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
2338 if (!AT)
2339 return false;
2340 CurrentType = AT->getElementType();
2341 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
2342 Result += IdxResult.getSExtValue() * ElementSize;
2343 break;
2344 }
2345
2346 case OffsetOfExpr::OffsetOfNode::Field: {
2347 FieldDecl *MemberDecl = ON.getField();
2348 const RecordType *RT = CurrentType->getAs<RecordType>();
2349 if (!RT)
2350 return false;
2351 RecordDecl *RD = RT->getDecl();
2352 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00002353 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00002354 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002355 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00002356 CurrentType = MemberDecl->getType().getNonReferenceType();
2357 break;
2358 }
2359
2360 case OffsetOfExpr::OffsetOfNode::Identifier:
2361 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00002362 return false;
2363
2364 case OffsetOfExpr::OffsetOfNode::Base: {
2365 CXXBaseSpecifier *BaseSpec = ON.getBase();
2366 if (BaseSpec->isVirtual())
2367 return false;
2368
2369 // Find the layout of the class whose base we are looking into.
2370 const RecordType *RT = CurrentType->getAs<RecordType>();
2371 if (!RT)
2372 return false;
2373 RecordDecl *RD = RT->getDecl();
2374 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
2375
2376 // Find the base class itself.
2377 CurrentType = BaseSpec->getType();
2378 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2379 if (!BaseRT)
2380 return false;
2381
2382 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00002383 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00002384 break;
2385 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002386 }
2387 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002388 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00002389}
2390
Chris Lattnere13042c2008-07-11 19:10:17 +00002391bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002392 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002393 // LNot's operand isn't necessarily an integer, so we handle it specially.
2394 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00002395 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00002396 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002397 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00002398 }
2399
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002400 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00002401 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002402 return false;
2403
Richard Smith11562c52011-10-28 17:51:58 +00002404 // Get the operand value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002405 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00002406 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00002407 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002408
Chris Lattnerf09ad162008-07-11 22:15:16 +00002409 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002410 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00002411 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2412 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002413 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00002414 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00002415 // FIXME: Should extension allow i-c-e extension expressions in its scope?
2416 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00002417 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002418 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00002419 // The result is just the value.
2420 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002421 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00002422 if (!Val.isInt()) return false;
2423 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00002424 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00002425 if (!Val.isInt()) return false;
2426 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00002427 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002428}
Mike Stump11289f42009-09-09 15:08:12 +00002429
Chris Lattner477c4be2008-07-12 01:15:53 +00002430/// HandleCast - This is used to evaluate implicit or explicit casts where the
2431/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00002432bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
2433 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002434 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00002435 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002436
Eli Friedmanc757de22011-03-25 00:43:55 +00002437 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00002438 case CK_BaseToDerived:
2439 case CK_DerivedToBase:
2440 case CK_UncheckedDerivedToBase:
2441 case CK_Dynamic:
2442 case CK_ToUnion:
2443 case CK_ArrayToPointerDecay:
2444 case CK_FunctionToPointerDecay:
2445 case CK_NullToPointer:
2446 case CK_NullToMemberPointer:
2447 case CK_BaseToDerivedMemberPointer:
2448 case CK_DerivedToBaseMemberPointer:
2449 case CK_ConstructorConversion:
2450 case CK_IntegralToPointer:
2451 case CK_ToVoid:
2452 case CK_VectorSplat:
2453 case CK_IntegralToFloating:
2454 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002455 case CK_CPointerToObjCPointerCast:
2456 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002457 case CK_AnyPointerToBlockPointerCast:
2458 case CK_ObjCObjectLValueCast:
2459 case CK_FloatingRealToComplex:
2460 case CK_FloatingComplexToReal:
2461 case CK_FloatingComplexCast:
2462 case CK_FloatingComplexToIntegralComplex:
2463 case CK_IntegralRealToComplex:
2464 case CK_IntegralComplexCast:
2465 case CK_IntegralComplexToFloatingComplex:
2466 llvm_unreachable("invalid cast kind for integral value");
2467
Eli Friedman9faf2f92011-03-25 19:07:11 +00002468 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002469 case CK_Dependent:
2470 case CK_GetObjCProperty:
2471 case CK_LValueBitCast:
2472 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00002473 case CK_ARCProduceObject:
2474 case CK_ARCConsumeObject:
2475 case CK_ARCReclaimReturnedObject:
2476 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00002477 return false;
2478
2479 case CK_LValueToRValue:
2480 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002481 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002482
2483 case CK_MemberPointerToBoolean:
2484 case CK_PointerToBoolean:
2485 case CK_IntegralToBoolean:
2486 case CK_FloatingToBoolean:
2487 case CK_FloatingComplexToBoolean:
2488 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002489 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002490 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002491 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002492 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002493 }
2494
Eli Friedmanc757de22011-03-25 00:43:55 +00002495 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00002496 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00002497 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002498
Eli Friedman742421e2009-02-20 01:15:07 +00002499 if (!Result.isInt()) {
2500 // Only allow casts of lvalues if they are lossless.
2501 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2502 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002503
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002504 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002505 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00002506 }
Mike Stump11289f42009-09-09 15:08:12 +00002507
Eli Friedmanc757de22011-03-25 00:43:55 +00002508 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00002509 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00002510 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00002511 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002512
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002513 if (LV.getLValueBase()) {
2514 // Only allow based lvalue casts if they are lossless.
2515 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2516 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002517
John McCall45d55e42010-05-07 21:00:08 +00002518 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002519 return true;
2520 }
2521
Ken Dyck02990832010-01-15 12:37:54 +00002522 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2523 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002524 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002525 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002526
Eli Friedmanc757de22011-03-25 00:43:55 +00002527 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00002528 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002529 if (!EvaluateComplex(SubExpr, C, Info))
2530 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00002531 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002532 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00002533
Eli Friedmanc757de22011-03-25 00:43:55 +00002534 case CK_FloatingToIntegral: {
2535 APFloat F(0.0);
2536 if (!EvaluateFloat(SubExpr, F, Info))
2537 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00002538
Eli Friedmanc757de22011-03-25 00:43:55 +00002539 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2540 }
2541 }
Mike Stump11289f42009-09-09 15:08:12 +00002542
Eli Friedmanc757de22011-03-25 00:43:55 +00002543 llvm_unreachable("unknown cast resulting in integral value");
2544 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002545}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002546
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002547bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2548 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002549 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002550 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2551 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2552 return Success(LV.getComplexIntReal(), E);
2553 }
2554
2555 return Visit(E->getSubExpr());
2556}
2557
Eli Friedman4e7a2412009-02-27 04:45:43 +00002558bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002559 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
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.getComplexIntImag(), E);
2564 }
2565
Richard Smith4a678122011-10-24 18:44:57 +00002566 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00002567 return Success(0, E);
2568}
2569
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002570bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2571 return Success(E->getPackLength(), E);
2572}
2573
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002574bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2575 return Success(E->getValue(), E);
2576}
2577
Chris Lattner05706e882008-07-11 18:11:29 +00002578//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002579// Float Evaluation
2580//===----------------------------------------------------------------------===//
2581
2582namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002583class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002584 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002585 APFloat &Result;
2586public:
2587 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002588 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002589
Richard Smith0b0a0b62011-10-29 20:57:55 +00002590 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002591 Result = V.getFloat();
2592 return true;
2593 }
2594 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002595 return false;
2596 }
2597
Richard Smith4ce706a2011-10-11 21:43:33 +00002598 bool ValueInitialization(const Expr *E) {
2599 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2600 return true;
2601 }
2602
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002603 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002604
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002605 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002606 bool VisitBinaryOperator(const BinaryOperator *E);
2607 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002608 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002609
John McCallb1fb0d32010-05-07 22:08:54 +00002610 bool VisitUnaryReal(const UnaryOperator *E);
2611 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002612
John McCallb1fb0d32010-05-07 22:08:54 +00002613 // FIXME: Missing: array subscript of vector, member of vector,
2614 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002615};
2616} // end anonymous namespace
2617
2618static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002619 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002620 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002621}
2622
Jay Foad39c79802011-01-12 09:06:06 +00002623static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002624 QualType ResultTy,
2625 const Expr *Arg,
2626 bool SNaN,
2627 llvm::APFloat &Result) {
2628 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2629 if (!S) return false;
2630
2631 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2632
2633 llvm::APInt fill;
2634
2635 // Treat empty strings as if they were zero.
2636 if (S->getString().empty())
2637 fill = llvm::APInt(32, 0);
2638 else if (S->getString().getAsInteger(0, fill))
2639 return false;
2640
2641 if (SNaN)
2642 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2643 else
2644 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2645 return true;
2646}
2647
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002648bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002649 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002650 default:
2651 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2652
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002653 case Builtin::BI__builtin_huge_val:
2654 case Builtin::BI__builtin_huge_valf:
2655 case Builtin::BI__builtin_huge_vall:
2656 case Builtin::BI__builtin_inf:
2657 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002658 case Builtin::BI__builtin_infl: {
2659 const llvm::fltSemantics &Sem =
2660 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002661 Result = llvm::APFloat::getInf(Sem);
2662 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002663 }
Mike Stump11289f42009-09-09 15:08:12 +00002664
John McCall16291492010-02-28 13:00:19 +00002665 case Builtin::BI__builtin_nans:
2666 case Builtin::BI__builtin_nansf:
2667 case Builtin::BI__builtin_nansl:
2668 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2669 true, Result);
2670
Chris Lattner0b7282e2008-10-06 06:31:58 +00002671 case Builtin::BI__builtin_nan:
2672 case Builtin::BI__builtin_nanf:
2673 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002674 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002675 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002676 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2677 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002678
2679 case Builtin::BI__builtin_fabs:
2680 case Builtin::BI__builtin_fabsf:
2681 case Builtin::BI__builtin_fabsl:
2682 if (!EvaluateFloat(E->getArg(0), Result, Info))
2683 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002684
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002685 if (Result.isNegative())
2686 Result.changeSign();
2687 return true;
2688
Mike Stump11289f42009-09-09 15:08:12 +00002689 case Builtin::BI__builtin_copysign:
2690 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002691 case Builtin::BI__builtin_copysignl: {
2692 APFloat RHS(0.);
2693 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2694 !EvaluateFloat(E->getArg(1), RHS, Info))
2695 return false;
2696 Result.copySign(RHS);
2697 return true;
2698 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002699 }
2700}
2701
John McCallb1fb0d32010-05-07 22:08:54 +00002702bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002703 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2704 ComplexValue CV;
2705 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2706 return false;
2707 Result = CV.FloatReal;
2708 return true;
2709 }
2710
2711 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002712}
2713
2714bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002715 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2716 ComplexValue CV;
2717 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2718 return false;
2719 Result = CV.FloatImag;
2720 return true;
2721 }
2722
Richard Smith4a678122011-10-24 18:44:57 +00002723 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00002724 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2725 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002726 return true;
2727}
2728
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002729bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002730 switch (E->getOpcode()) {
2731 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002732 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00002733 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00002734 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00002735 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2736 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002737 Result.changeSign();
2738 return true;
2739 }
2740}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002741
Eli Friedman24c01542008-08-22 00:06:13 +00002742bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002743 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002744 VisitIgnoredValue(E->getLHS());
2745 return Visit(E->getRHS());
Eli Friedman141fbf32009-11-16 04:25:37 +00002746 }
2747
Richard Smith472d4952011-10-28 23:26:52 +00002748 // We can't evaluate pointer-to-member operations or assignments.
2749 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlssona5df61a2010-10-31 01:21:47 +00002750 return false;
2751
Eli Friedman24c01542008-08-22 00:06:13 +00002752 // FIXME: Diagnostics? I really don't understand how the warnings
2753 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002754 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002755 if (!EvaluateFloat(E->getLHS(), Result, Info))
2756 return false;
2757 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2758 return false;
2759
2760 switch (E->getOpcode()) {
2761 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002762 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002763 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2764 return true;
John McCalle3027922010-08-25 11:45:40 +00002765 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002766 Result.add(RHS, APFloat::rmNearestTiesToEven);
2767 return true;
John McCalle3027922010-08-25 11:45:40 +00002768 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002769 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2770 return true;
John McCalle3027922010-08-25 11:45:40 +00002771 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002772 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2773 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002774 }
2775}
2776
2777bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2778 Result = E->getValue();
2779 return true;
2780}
2781
Peter Collingbournee9200682011-05-13 03:29:01 +00002782bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2783 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002784
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002785 switch (E->getCastKind()) {
2786 default:
Richard Smith11562c52011-10-28 17:51:58 +00002787 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002788
2789 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002790 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002791 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002792 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002793 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002794 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002795 return true;
2796 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002797
2798 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002799 if (!Visit(SubExpr))
2800 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002801 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2802 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002803 return true;
2804 }
John McCalld7646252010-11-14 08:17:51 +00002805
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002806 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002807 ComplexValue V;
2808 if (!EvaluateComplex(SubExpr, V, Info))
2809 return false;
2810 Result = V.getComplexFloatReal();
2811 return true;
2812 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002813 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002814
2815 return false;
2816}
2817
Eli Friedman24c01542008-08-22 00:06:13 +00002818//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002819// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002820//===----------------------------------------------------------------------===//
2821
2822namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002823class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002824 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002825 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002826
Anders Carlsson537969c2008-11-16 20:27:53 +00002827public:
John McCall93d91dc2010-05-07 17:22:02 +00002828 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002829 : ExprEvaluatorBaseTy(info), Result(Result) {}
2830
Richard Smith0b0a0b62011-10-29 20:57:55 +00002831 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002832 Result.setFrom(V);
2833 return true;
2834 }
2835 bool Error(const Expr *E) {
2836 return false;
2837 }
Mike Stump11289f42009-09-09 15:08:12 +00002838
Anders Carlsson537969c2008-11-16 20:27:53 +00002839 //===--------------------------------------------------------------------===//
2840 // Visitor Methods
2841 //===--------------------------------------------------------------------===//
2842
Peter Collingbournee9200682011-05-13 03:29:01 +00002843 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002844
Peter Collingbournee9200682011-05-13 03:29:01 +00002845 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002846
John McCall93d91dc2010-05-07 17:22:02 +00002847 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002848 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002849 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002850};
2851} // end anonymous namespace
2852
John McCall93d91dc2010-05-07 17:22:02 +00002853static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2854 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002855 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002856 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002857}
2858
Peter Collingbournee9200682011-05-13 03:29:01 +00002859bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2860 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002861
2862 if (SubExpr->getType()->isRealFloatingType()) {
2863 Result.makeComplexFloat();
2864 APFloat &Imag = Result.FloatImag;
2865 if (!EvaluateFloat(SubExpr, Imag, Info))
2866 return false;
2867
2868 Result.FloatReal = APFloat(Imag.getSemantics());
2869 return true;
2870 } else {
2871 assert(SubExpr->getType()->isIntegerType() &&
2872 "Unexpected imaginary literal.");
2873
2874 Result.makeComplexInt();
2875 APSInt &Imag = Result.IntImag;
2876 if (!EvaluateInteger(SubExpr, Imag, Info))
2877 return false;
2878
2879 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2880 return true;
2881 }
2882}
2883
Peter Collingbournee9200682011-05-13 03:29:01 +00002884bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002885
John McCallfcef3cf2010-12-14 17:51:41 +00002886 switch (E->getCastKind()) {
2887 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002888 case CK_BaseToDerived:
2889 case CK_DerivedToBase:
2890 case CK_UncheckedDerivedToBase:
2891 case CK_Dynamic:
2892 case CK_ToUnion:
2893 case CK_ArrayToPointerDecay:
2894 case CK_FunctionToPointerDecay:
2895 case CK_NullToPointer:
2896 case CK_NullToMemberPointer:
2897 case CK_BaseToDerivedMemberPointer:
2898 case CK_DerivedToBaseMemberPointer:
2899 case CK_MemberPointerToBoolean:
2900 case CK_ConstructorConversion:
2901 case CK_IntegralToPointer:
2902 case CK_PointerToIntegral:
2903 case CK_PointerToBoolean:
2904 case CK_ToVoid:
2905 case CK_VectorSplat:
2906 case CK_IntegralCast:
2907 case CK_IntegralToBoolean:
2908 case CK_IntegralToFloating:
2909 case CK_FloatingToIntegral:
2910 case CK_FloatingToBoolean:
2911 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002912 case CK_CPointerToObjCPointerCast:
2913 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002914 case CK_AnyPointerToBlockPointerCast:
2915 case CK_ObjCObjectLValueCast:
2916 case CK_FloatingComplexToReal:
2917 case CK_FloatingComplexToBoolean:
2918 case CK_IntegralComplexToReal:
2919 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002920 case CK_ARCProduceObject:
2921 case CK_ARCConsumeObject:
2922 case CK_ARCReclaimReturnedObject:
2923 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002924 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002925
John McCallfcef3cf2010-12-14 17:51:41 +00002926 case CK_LValueToRValue:
2927 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002928 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00002929
2930 case CK_Dependent:
2931 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002932 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002933 case CK_UserDefinedConversion:
2934 return false;
2935
2936 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002937 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002938 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002939 return false;
2940
John McCallfcef3cf2010-12-14 17:51:41 +00002941 Result.makeComplexFloat();
2942 Result.FloatImag = APFloat(Real.getSemantics());
2943 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002944 }
2945
John McCallfcef3cf2010-12-14 17:51:41 +00002946 case CK_FloatingComplexCast: {
2947 if (!Visit(E->getSubExpr()))
2948 return false;
2949
2950 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2951 QualType From
2952 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2953
2954 Result.FloatReal
2955 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2956 Result.FloatImag
2957 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2958 return true;
2959 }
2960
2961 case CK_FloatingComplexToIntegralComplex: {
2962 if (!Visit(E->getSubExpr()))
2963 return false;
2964
2965 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2966 QualType From
2967 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2968 Result.makeComplexInt();
2969 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2970 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2971 return true;
2972 }
2973
2974 case CK_IntegralRealToComplex: {
2975 APSInt &Real = Result.IntReal;
2976 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2977 return false;
2978
2979 Result.makeComplexInt();
2980 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2981 return true;
2982 }
2983
2984 case CK_IntegralComplexCast: {
2985 if (!Visit(E->getSubExpr()))
2986 return false;
2987
2988 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2989 QualType From
2990 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2991
2992 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2993 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2994 return true;
2995 }
2996
2997 case CK_IntegralComplexToFloatingComplex: {
2998 if (!Visit(E->getSubExpr()))
2999 return false;
3000
3001 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3002 QualType From
3003 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3004 Result.makeComplexFloat();
3005 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
3006 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
3007 return true;
3008 }
3009 }
3010
3011 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003012 return false;
3013}
3014
John McCall93d91dc2010-05-07 17:22:02 +00003015bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003016 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003017 VisitIgnoredValue(E->getLHS());
3018 return Visit(E->getRHS());
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003019 }
John McCall93d91dc2010-05-07 17:22:02 +00003020 if (!Visit(E->getLHS()))
3021 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003022
John McCall93d91dc2010-05-07 17:22:02 +00003023 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003024 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00003025 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003026
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003027 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
3028 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003029 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00003030 default: return false;
John McCalle3027922010-08-25 11:45:40 +00003031 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003032 if (Result.isComplexFloat()) {
3033 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
3034 APFloat::rmNearestTiesToEven);
3035 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
3036 APFloat::rmNearestTiesToEven);
3037 } else {
3038 Result.getComplexIntReal() += RHS.getComplexIntReal();
3039 Result.getComplexIntImag() += RHS.getComplexIntImag();
3040 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003041 break;
John McCalle3027922010-08-25 11:45:40 +00003042 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003043 if (Result.isComplexFloat()) {
3044 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
3045 APFloat::rmNearestTiesToEven);
3046 Result.getComplexFloatImag().subtract(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_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003054 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00003055 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003056 APFloat &LHS_r = LHS.getComplexFloatReal();
3057 APFloat &LHS_i = LHS.getComplexFloatImag();
3058 APFloat &RHS_r = RHS.getComplexFloatReal();
3059 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00003060
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003061 APFloat Tmp = LHS_r;
3062 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3063 Result.getComplexFloatReal() = Tmp;
3064 Tmp = LHS_i;
3065 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3066 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
3067
3068 Tmp = LHS_r;
3069 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3070 Result.getComplexFloatImag() = Tmp;
3071 Tmp = LHS_i;
3072 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3073 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
3074 } else {
John McCall93d91dc2010-05-07 17:22:02 +00003075 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00003076 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003077 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
3078 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00003079 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003080 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
3081 LHS.getComplexIntImag() * RHS.getComplexIntReal());
3082 }
3083 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003084 case BO_Div:
3085 if (Result.isComplexFloat()) {
3086 ComplexValue LHS = Result;
3087 APFloat &LHS_r = LHS.getComplexFloatReal();
3088 APFloat &LHS_i = LHS.getComplexFloatImag();
3089 APFloat &RHS_r = RHS.getComplexFloatReal();
3090 APFloat &RHS_i = RHS.getComplexFloatImag();
3091 APFloat &Res_r = Result.getComplexFloatReal();
3092 APFloat &Res_i = Result.getComplexFloatImag();
3093
3094 APFloat Den = RHS_r;
3095 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3096 APFloat Tmp = RHS_i;
3097 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3098 Den.add(Tmp, APFloat::rmNearestTiesToEven);
3099
3100 Res_r = LHS_r;
3101 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3102 Tmp = LHS_i;
3103 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3104 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
3105 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
3106
3107 Res_i = LHS_i;
3108 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3109 Tmp = LHS_r;
3110 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3111 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
3112 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
3113 } else {
3114 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
3115 // FIXME: what about diagnostics?
3116 return false;
3117 }
3118 ComplexValue LHS = Result;
3119 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
3120 RHS.getComplexIntImag() * RHS.getComplexIntImag();
3121 Result.getComplexIntReal() =
3122 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
3123 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
3124 Result.getComplexIntImag() =
3125 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
3126 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
3127 }
3128 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003129 }
3130
John McCall93d91dc2010-05-07 17:22:02 +00003131 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003132}
3133
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003134bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
3135 // Get the operand value into 'Result'.
3136 if (!Visit(E->getSubExpr()))
3137 return false;
3138
3139 switch (E->getOpcode()) {
3140 default:
3141 // FIXME: what about diagnostics?
3142 return false;
3143 case UO_Extension:
3144 return true;
3145 case UO_Plus:
3146 // The result is always just the subexpr.
3147 return true;
3148 case UO_Minus:
3149 if (Result.isComplexFloat()) {
3150 Result.getComplexFloatReal().changeSign();
3151 Result.getComplexFloatImag().changeSign();
3152 }
3153 else {
3154 Result.getComplexIntReal() = -Result.getComplexIntReal();
3155 Result.getComplexIntImag() = -Result.getComplexIntImag();
3156 }
3157 return true;
3158 case UO_Not:
3159 if (Result.isComplexFloat())
3160 Result.getComplexFloatImag().changeSign();
3161 else
3162 Result.getComplexIntImag() = -Result.getComplexIntImag();
3163 return true;
3164 }
3165}
3166
Anders Carlsson537969c2008-11-16 20:27:53 +00003167//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00003168// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00003169//===----------------------------------------------------------------------===//
3170
Richard Smith0b0a0b62011-10-29 20:57:55 +00003171static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003172 // In C, function designators are not lvalues, but we evaluate them as if they
3173 // are.
3174 if (E->isGLValue() || E->getType()->isFunctionType()) {
3175 LValue LV;
3176 if (!EvaluateLValue(E, LV, Info))
3177 return false;
3178 LV.moveInto(Result);
3179 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003180 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003181 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003182 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003183 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003184 return false;
John McCall45d55e42010-05-07 21:00:08 +00003185 } else if (E->getType()->hasPointerRepresentation()) {
3186 LValue LV;
3187 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003188 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003189 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00003190 } else if (E->getType()->isRealFloatingType()) {
3191 llvm::APFloat F(0.0);
3192 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003193 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003194 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00003195 } else if (E->getType()->isAnyComplexType()) {
3196 ComplexValue C;
3197 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003198 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003199 C.moveInto(Result);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003200 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00003201 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003202
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00003203 return true;
3204}
3205
Richard Smith11562c52011-10-28 17:51:58 +00003206
Richard Smith7b553f12011-10-29 00:50:52 +00003207/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00003208/// any crazy technique (that has nothing to do with language standards) that
3209/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00003210/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3211/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00003212bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
John McCallc07a0c72011-02-17 10:25:35 +00003213 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00003214
Richard Smith0b0a0b62011-10-29 20:57:55 +00003215 CCValue Value;
3216 if (!::Evaluate(Value, Info, this))
Richard Smith11562c52011-10-28 17:51:58 +00003217 return false;
3218
3219 if (isGLValue()) {
3220 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003221 LV.setFrom(Value);
3222 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3223 return false;
Richard Smith11562c52011-10-28 17:51:58 +00003224 }
3225
Richard Smith0b0a0b62011-10-29 20:57:55 +00003226 // Check this core constant expression is a constant expression, and if so,
3227 // slice it down to one.
3228 if (!CheckConstantExpression(Value))
3229 return false;
3230 Result.Val = Value;
3231 return true;
John McCallc07a0c72011-02-17 10:25:35 +00003232}
3233
Jay Foad39c79802011-01-12 09:06:06 +00003234bool Expr::EvaluateAsBooleanCondition(bool &Result,
3235 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003236 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00003237 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00003238 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00003239 Result);
John McCall1be1c632010-01-05 23:42:56 +00003240}
3241
Richard Smithcaf33902011-10-10 18:28:20 +00003242bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003243 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003244 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smith11562c52011-10-28 17:51:58 +00003245 !ExprResult.Val.isInt()) {
3246 return false;
3247 }
3248 Result = ExprResult.Val.getInt();
3249 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00003250}
3251
Jay Foad39c79802011-01-12 09:06:06 +00003252bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00003253 EvalInfo Info(Ctx, Result);
3254
John McCall45d55e42010-05-07 21:00:08 +00003255 LValue LV;
Richard Smith11562c52011-10-28 17:51:58 +00003256 if (EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003257 IsGlobalLValue(LV.Base)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003258 Result.Val = APValue(LV.Base, LV.Offset);
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003259 return true;
3260 }
3261 return false;
3262}
3263
Jay Foad39c79802011-01-12 09:06:06 +00003264bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
3265 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003266 EvalInfo Info(Ctx, Result);
3267
3268 LValue LV;
Richard Smithfec09922011-11-01 16:57:24 +00003269 if (EvaluateLValue(this, LV, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003270 Result.Val = APValue(LV.Base, LV.Offset);
John McCall45d55e42010-05-07 21:00:08 +00003271 return true;
3272 }
3273 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00003274}
3275
Richard Smith7b553f12011-10-29 00:50:52 +00003276/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3277/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00003278bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00003279 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00003280 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00003281}
Anders Carlsson59689ed2008-11-22 21:04:56 +00003282
Jay Foad39c79802011-01-12 09:06:06 +00003283bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00003284 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003285}
3286
Richard Smithcaf33902011-10-10 18:28:20 +00003287APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003288 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003289 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00003290 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00003291 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003292 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00003293
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003294 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00003295}
John McCall864e3962010-05-07 05:32:02 +00003296
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003297 bool Expr::EvalResult::isGlobalLValue() const {
3298 assert(Val.isLValue());
3299 return IsGlobalLValue(Val.getLValueBase());
3300 }
3301
3302
John McCall864e3962010-05-07 05:32:02 +00003303/// isIntegerConstantExpr - this recursive routine will test if an expression is
3304/// an integer constant expression.
3305
3306/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
3307/// comma, etc
3308///
3309/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
3310/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
3311/// cast+dereference.
3312
3313// CheckICE - This function does the fundamental ICE checking: the returned
3314// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
3315// Note that to reduce code duplication, this helper does no evaluation
3316// itself; the caller checks whether the expression is evaluatable, and
3317// in the rare cases where CheckICE actually cares about the evaluated
3318// value, it calls into Evalute.
3319//
3320// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00003321// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00003322// 1: This expression is not an ICE, but if it isn't evaluated, it's
3323// a legal subexpression for an ICE. This return value is used to handle
3324// the comma operator in C99 mode.
3325// 2: This expression is not an ICE, and is not a legal subexpression for one.
3326
Dan Gohman28ade552010-07-26 21:25:24 +00003327namespace {
3328
John McCall864e3962010-05-07 05:32:02 +00003329struct ICEDiag {
3330 unsigned Val;
3331 SourceLocation Loc;
3332
3333 public:
3334 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
3335 ICEDiag() : Val(0) {}
3336};
3337
Dan Gohman28ade552010-07-26 21:25:24 +00003338}
3339
3340static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00003341
3342static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
3343 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003344 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003345 !EVResult.Val.isInt()) {
3346 return ICEDiag(2, E->getLocStart());
3347 }
3348 return NoDiag();
3349}
3350
3351static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
3352 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00003353 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00003354 return ICEDiag(2, E->getLocStart());
3355 }
3356
3357 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00003358#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00003359#define STMT(Node, Base) case Expr::Node##Class:
3360#define EXPR(Node, Base)
3361#include "clang/AST/StmtNodes.inc"
3362 case Expr::PredefinedExprClass:
3363 case Expr::FloatingLiteralClass:
3364 case Expr::ImaginaryLiteralClass:
3365 case Expr::StringLiteralClass:
3366 case Expr::ArraySubscriptExprClass:
3367 case Expr::MemberExprClass:
3368 case Expr::CompoundAssignOperatorClass:
3369 case Expr::CompoundLiteralExprClass:
3370 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00003371 case Expr::DesignatedInitExprClass:
3372 case Expr::ImplicitValueInitExprClass:
3373 case Expr::ParenListExprClass:
3374 case Expr::VAArgExprClass:
3375 case Expr::AddrLabelExprClass:
3376 case Expr::StmtExprClass:
3377 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00003378 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00003379 case Expr::CXXDynamicCastExprClass:
3380 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00003381 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00003382 case Expr::CXXNullPtrLiteralExprClass:
3383 case Expr::CXXThisExprClass:
3384 case Expr::CXXThrowExprClass:
3385 case Expr::CXXNewExprClass:
3386 case Expr::CXXDeleteExprClass:
3387 case Expr::CXXPseudoDestructorExprClass:
3388 case Expr::UnresolvedLookupExprClass:
3389 case Expr::DependentScopeDeclRefExprClass:
3390 case Expr::CXXConstructExprClass:
3391 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00003392 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00003393 case Expr::CXXTemporaryObjectExprClass:
3394 case Expr::CXXUnresolvedConstructExprClass:
3395 case Expr::CXXDependentScopeMemberExprClass:
3396 case Expr::UnresolvedMemberExprClass:
3397 case Expr::ObjCStringLiteralClass:
3398 case Expr::ObjCEncodeExprClass:
3399 case Expr::ObjCMessageExprClass:
3400 case Expr::ObjCSelectorExprClass:
3401 case Expr::ObjCProtocolExprClass:
3402 case Expr::ObjCIvarRefExprClass:
3403 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00003404 case Expr::ObjCIsaExprClass:
3405 case Expr::ShuffleVectorExprClass:
3406 case Expr::BlockExprClass:
3407 case Expr::BlockDeclRefExprClass:
3408 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00003409 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00003410 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00003411 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00003412 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00003413 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00003414 case Expr::MaterializeTemporaryExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003415 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00003416 return ICEDiag(2, E->getLocStart());
3417
Sebastian Redl12757ab2011-09-24 17:48:14 +00003418 case Expr::InitListExprClass:
3419 if (Ctx.getLangOptions().CPlusPlus0x) {
3420 const InitListExpr *ILE = cast<InitListExpr>(E);
3421 if (ILE->getNumInits() == 0)
3422 return NoDiag();
3423 if (ILE->getNumInits() == 1)
3424 return CheckICE(ILE->getInit(0), Ctx);
3425 // Fall through for more than 1 expression.
3426 }
3427 return ICEDiag(2, E->getLocStart());
3428
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003429 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00003430 case Expr::GNUNullExprClass:
3431 // GCC considers the GNU __null value to be an integral constant expression.
3432 return NoDiag();
3433
John McCall7c454bb2011-07-15 05:09:51 +00003434 case Expr::SubstNonTypeTemplateParmExprClass:
3435 return
3436 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
3437
John McCall864e3962010-05-07 05:32:02 +00003438 case Expr::ParenExprClass:
3439 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00003440 case Expr::GenericSelectionExprClass:
3441 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003442 case Expr::IntegerLiteralClass:
3443 case Expr::CharacterLiteralClass:
3444 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00003445 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00003446 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003447 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00003448 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00003449 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003450 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00003451 return NoDiag();
3452 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00003453 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00003454 // C99 6.6/3 allows function calls within unevaluated subexpressions of
3455 // constant expressions, but they can never be ICEs because an ICE cannot
3456 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00003457 const CallExpr *CE = cast<CallExpr>(E);
3458 if (CE->isBuiltinCall(Ctx))
3459 return CheckEvalInICE(E, Ctx);
3460 return ICEDiag(2, E->getLocStart());
3461 }
3462 case Expr::DeclRefExprClass:
3463 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
3464 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00003465 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00003466 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3467
3468 // Parameter variables are never constants. Without this check,
3469 // getAnyInitializer() can find a default argument, which leads
3470 // to chaos.
3471 if (isa<ParmVarDecl>(D))
3472 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3473
3474 // C++ 7.1.5.1p2
3475 // A variable of non-volatile const-qualified integral or enumeration
3476 // type initialized by an ICE can be used in ICEs.
3477 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCall864e3962010-05-07 05:32:02 +00003478 // Look for a declaration of this variable that has an initializer.
3479 const VarDecl *ID = 0;
3480 const Expr *Init = Dcl->getAnyInitializer(ID);
3481 if (Init) {
3482 if (ID->isInitKnownICE()) {
3483 // We have already checked whether this subexpression is an
3484 // integral constant expression.
3485 if (ID->isInitICE())
3486 return NoDiag();
3487 else
3488 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3489 }
3490
3491 // It's an ICE whether or not the definition we found is
3492 // out-of-line. See DR 721 and the discussion in Clang PR
3493 // 6206 for details.
3494
3495 if (Dcl->isCheckingICE()) {
3496 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3497 }
3498
3499 Dcl->setCheckingICE();
3500 ICEDiag Result = CheckICE(Init, Ctx);
3501 // Cache the result of the ICE test.
3502 Dcl->setInitKnownICE(Result.Val == 0);
3503 return Result;
3504 }
3505 }
3506 }
3507 return ICEDiag(2, E->getLocStart());
3508 case Expr::UnaryOperatorClass: {
3509 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3510 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003511 case UO_PostInc:
3512 case UO_PostDec:
3513 case UO_PreInc:
3514 case UO_PreDec:
3515 case UO_AddrOf:
3516 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00003517 // C99 6.6/3 allows increment and decrement within unevaluated
3518 // subexpressions of constant expressions, but they can never be ICEs
3519 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003520 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00003521 case UO_Extension:
3522 case UO_LNot:
3523 case UO_Plus:
3524 case UO_Minus:
3525 case UO_Not:
3526 case UO_Real:
3527 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003528 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003529 }
3530
3531 // OffsetOf falls through here.
3532 }
3533 case Expr::OffsetOfExprClass: {
3534 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00003535 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00003536 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00003537 // compliance: we should warn earlier for offsetof expressions with
3538 // array subscripts that aren't ICEs, and if the array subscripts
3539 // are ICEs, the value of the offsetof must be an integer constant.
3540 return CheckEvalInICE(E, Ctx);
3541 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003542 case Expr::UnaryExprOrTypeTraitExprClass: {
3543 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3544 if ((Exp->getKind() == UETT_SizeOf) &&
3545 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003546 return ICEDiag(2, E->getLocStart());
3547 return NoDiag();
3548 }
3549 case Expr::BinaryOperatorClass: {
3550 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3551 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003552 case BO_PtrMemD:
3553 case BO_PtrMemI:
3554 case BO_Assign:
3555 case BO_MulAssign:
3556 case BO_DivAssign:
3557 case BO_RemAssign:
3558 case BO_AddAssign:
3559 case BO_SubAssign:
3560 case BO_ShlAssign:
3561 case BO_ShrAssign:
3562 case BO_AndAssign:
3563 case BO_XorAssign:
3564 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00003565 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3566 // constant expressions, but they can never be ICEs because an ICE cannot
3567 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003568 return ICEDiag(2, E->getLocStart());
3569
John McCalle3027922010-08-25 11:45:40 +00003570 case BO_Mul:
3571 case BO_Div:
3572 case BO_Rem:
3573 case BO_Add:
3574 case BO_Sub:
3575 case BO_Shl:
3576 case BO_Shr:
3577 case BO_LT:
3578 case BO_GT:
3579 case BO_LE:
3580 case BO_GE:
3581 case BO_EQ:
3582 case BO_NE:
3583 case BO_And:
3584 case BO_Xor:
3585 case BO_Or:
3586 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003587 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3588 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003589 if (Exp->getOpcode() == BO_Div ||
3590 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00003591 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00003592 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003593 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003594 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003595 if (REval == 0)
3596 return ICEDiag(1, E->getLocStart());
3597 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003598 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003599 if (LEval.isMinSignedValue())
3600 return ICEDiag(1, E->getLocStart());
3601 }
3602 }
3603 }
John McCalle3027922010-08-25 11:45:40 +00003604 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003605 if (Ctx.getLangOptions().C99) {
3606 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3607 // if it isn't evaluated.
3608 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3609 return ICEDiag(1, E->getLocStart());
3610 } else {
3611 // In both C89 and C++, commas in ICEs are illegal.
3612 return ICEDiag(2, E->getLocStart());
3613 }
3614 }
3615 if (LHSResult.Val >= RHSResult.Val)
3616 return LHSResult;
3617 return RHSResult;
3618 }
John McCalle3027922010-08-25 11:45:40 +00003619 case BO_LAnd:
3620 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003621 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003622
3623 // C++0x [expr.const]p2:
3624 // [...] subexpressions of logical AND (5.14), logical OR
3625 // (5.15), and condi- tional (5.16) operations that are not
3626 // evaluated are not considered.
3627 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3628 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003629 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003630 return LHSResult;
3631
3632 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003633 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003634 return LHSResult;
3635 }
3636
John McCall864e3962010-05-07 05:32:02 +00003637 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3638 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3639 // Rare case where the RHS has a comma "side-effect"; we need
3640 // to actually check the condition to see whether the side
3641 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003642 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003643 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003644 return RHSResult;
3645 return NoDiag();
3646 }
3647
3648 if (LHSResult.Val >= RHSResult.Val)
3649 return LHSResult;
3650 return RHSResult;
3651 }
3652 }
3653 }
3654 case Expr::ImplicitCastExprClass:
3655 case Expr::CStyleCastExprClass:
3656 case Expr::CXXFunctionalCastExprClass:
3657 case Expr::CXXStaticCastExprClass:
3658 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00003659 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003660 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003661 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00003662 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00003663 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3664 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00003665 switch (cast<CastExpr>(E)->getCastKind()) {
3666 case CK_LValueToRValue:
3667 case CK_NoOp:
3668 case CK_IntegralToBoolean:
3669 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003670 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003671 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00003672 return ICEDiag(2, E->getLocStart());
3673 }
John McCall864e3962010-05-07 05:32:02 +00003674 }
John McCallc07a0c72011-02-17 10:25:35 +00003675 case Expr::BinaryConditionalOperatorClass: {
3676 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3677 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3678 if (CommonResult.Val == 2) return CommonResult;
3679 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3680 if (FalseResult.Val == 2) return FalseResult;
3681 if (CommonResult.Val == 1) return CommonResult;
3682 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003683 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003684 return FalseResult;
3685 }
John McCall864e3962010-05-07 05:32:02 +00003686 case Expr::ConditionalOperatorClass: {
3687 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3688 // If the condition (ignoring parens) is a __builtin_constant_p call,
3689 // then only the true side is actually considered in an integer constant
3690 // expression, and it is fully evaluated. This is an important GNU
3691 // extension. See GCC PR38377 for discussion.
3692 if (const CallExpr *CallCE
3693 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3694 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3695 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003696 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003697 !EVResult.Val.isInt()) {
3698 return ICEDiag(2, E->getLocStart());
3699 }
3700 return NoDiag();
3701 }
3702 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003703 if (CondResult.Val == 2)
3704 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003705
3706 // C++0x [expr.const]p2:
3707 // subexpressions of [...] conditional (5.16) operations that
3708 // are not evaluated are not considered
3709 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003710 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003711 : false;
3712 ICEDiag TrueResult = NoDiag();
3713 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3714 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3715 ICEDiag FalseResult = NoDiag();
3716 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3717 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3718
John McCall864e3962010-05-07 05:32:02 +00003719 if (TrueResult.Val == 2)
3720 return TrueResult;
3721 if (FalseResult.Val == 2)
3722 return FalseResult;
3723 if (CondResult.Val == 1)
3724 return CondResult;
3725 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3726 return NoDiag();
3727 // Rare case where the diagnostics depend on which side is evaluated
3728 // Note that if we get here, CondResult is 0, and at least one of
3729 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003730 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003731 return FalseResult;
3732 }
3733 return TrueResult;
3734 }
3735 case Expr::CXXDefaultArgExprClass:
3736 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3737 case Expr::ChooseExprClass: {
3738 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3739 }
3740 }
3741
3742 // Silence a GCC warning
3743 return ICEDiag(2, E->getLocStart());
3744}
3745
3746bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3747 SourceLocation *Loc, bool isEvaluated) const {
3748 ICEDiag d = CheckICE(this, Ctx);
3749 if (d.Val != 0) {
3750 if (Loc) *Loc = d.Loc;
3751 return false;
3752 }
Richard Smith11562c52011-10-28 17:51:58 +00003753 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00003754 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00003755 return true;
3756}