blob: 75f32ab5d46f2d2b8c9d35f6144d6e532d3f267c [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-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 Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-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 McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Richard Smith180f4792011-11-10 06:34:14 +000046 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000049
Richard Smith180f4792011-11-10 06:34:14 +000050 /// Get an LValue path entry, which is known to not be an array index, as a
51 /// field declaration.
52 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
53 APValue::BaseOrMemberType Value;
54 Value.setFromOpaqueValue(E.BaseOrMember);
55 return dyn_cast<FieldDecl>(Value.getPointer());
56 }
57 /// Get an LValue path entry, which is known to not be an array index, as a
58 /// base class declaration.
59 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
60 APValue::BaseOrMemberType Value;
61 Value.setFromOpaqueValue(E.BaseOrMember);
62 return dyn_cast<CXXRecordDecl>(Value.getPointer());
63 }
64 /// Determine whether this LValue path entry for a base class names a virtual
65 /// base class.
66 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
67 APValue::BaseOrMemberType Value;
68 Value.setFromOpaqueValue(E.BaseOrMember);
69 return Value.getInt();
70 }
71
Richard Smith9a17a682011-11-07 05:07:52 +000072 /// Determine whether the described subobject is an array element.
73 static bool SubobjectIsArrayElement(QualType Base,
74 ArrayRef<APValue::LValuePathEntry> Path) {
75 bool IsArrayElement = false;
76 const Type *T = Base.getTypePtr();
77 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
78 IsArrayElement = T && T->isArrayType();
79 if (IsArrayElement)
80 T = T->getBaseElementTypeUnsafe();
Richard Smith180f4792011-11-10 06:34:14 +000081 else if (const FieldDecl *FD = getAsField(Path[I]))
Richard Smith9a17a682011-11-07 05:07:52 +000082 T = FD->getType().getTypePtr();
83 else
84 // Path[I] describes a base class.
85 T = 0;
86 }
87 return IsArrayElement;
88 }
89
Richard Smith0a3bdb62011-11-04 02:25:55 +000090 /// A path from a glvalue to a subobject of that glvalue.
91 struct SubobjectDesignator {
92 /// True if the subobject was named in a manner not supported by C++11. Such
93 /// lvalues can still be folded, but they are not core constant expressions
94 /// and we cannot perform lvalue-to-rvalue conversions on them.
95 bool Invalid : 1;
96
97 /// Whether this designates an array element.
98 bool ArrayElement : 1;
99
100 /// Whether this designates 'one past the end' of the current subobject.
101 bool OnePastTheEnd : 1;
102
Richard Smith9a17a682011-11-07 05:07:52 +0000103 typedef APValue::LValuePathEntry PathEntry;
104
Richard Smith0a3bdb62011-11-04 02:25:55 +0000105 /// The entries on the path from the glvalue to the designated subobject.
106 SmallVector<PathEntry, 8> Entries;
107
108 SubobjectDesignator() :
109 Invalid(false), ArrayElement(false), OnePastTheEnd(false) {}
110
Richard Smith9a17a682011-11-07 05:07:52 +0000111 SubobjectDesignator(const APValue &V) :
112 Invalid(!V.isLValue() || !V.hasLValuePath()), ArrayElement(false),
113 OnePastTheEnd(false) {
114 if (!Invalid) {
115 ArrayRef<PathEntry> VEntries = V.getLValuePath();
116 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
117 if (V.getLValueBase())
118 ArrayElement = SubobjectIsArrayElement(V.getLValueBase()->getType(),
119 V.getLValuePath());
120 else
121 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
122 }
123 }
124
Richard Smith0a3bdb62011-11-04 02:25:55 +0000125 void setInvalid() {
126 Invalid = true;
127 Entries.clear();
128 }
129 /// Update this designator to refer to the given element within this array.
130 void addIndex(uint64_t N) {
131 if (Invalid) return;
132 if (OnePastTheEnd) {
133 setInvalid();
134 return;
135 }
136 PathEntry Entry;
Richard Smith9a17a682011-11-07 05:07:52 +0000137 Entry.ArrayIndex = N;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000138 Entries.push_back(Entry);
139 ArrayElement = true;
140 }
141 /// Update this designator to refer to the given base or member of this
142 /// object.
Richard Smith180f4792011-11-10 06:34:14 +0000143 void addDecl(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000144 if (Invalid) return;
145 if (OnePastTheEnd) {
146 setInvalid();
147 return;
148 }
149 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000150 APValue::BaseOrMemberType Value(D, Virtual);
151 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000152 Entries.push_back(Entry);
153 ArrayElement = false;
154 }
155 /// Add N to the address of this subobject.
156 void adjustIndex(uint64_t N) {
157 if (Invalid) return;
158 if (ArrayElement) {
Richard Smithcc5d4f62011-11-07 09:22:26 +0000159 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith9a17a682011-11-07 05:07:52 +0000160 Entries.back().ArrayIndex += N;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000161 return;
162 }
163 if (OnePastTheEnd && N == (uint64_t)-1)
164 OnePastTheEnd = false;
165 else if (!OnePastTheEnd && N == 1)
166 OnePastTheEnd = true;
167 else if (N != 0)
168 setInvalid();
169 }
170 };
171
Richard Smith47a1eed2011-10-29 20:57:55 +0000172 /// A core constant value. This can be the value of any constant expression,
173 /// or a pointer or reference to a non-static object or function parameter.
174 class CCValue : public APValue {
175 typedef llvm::APSInt APSInt;
176 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000177 /// If the value is a reference or pointer into a parameter or temporary,
178 /// this is the corresponding call stack frame.
179 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000180 /// If the value is a reference or pointer, this is a description of how the
181 /// subobject was specified.
182 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000183 public:
Richard Smith177dce72011-11-01 16:57:24 +0000184 struct GlobalValue {};
185
Richard Smith47a1eed2011-10-29 20:57:55 +0000186 CCValue() {}
187 explicit CCValue(const APSInt &I) : APValue(I) {}
188 explicit CCValue(const APFloat &F) : APValue(F) {}
189 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
190 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
191 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000192 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000193 CCValue(const Expr *B, const CharUnits &O, CallStackFrame *F,
194 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000195 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smith177dce72011-11-01 16:57:24 +0000196 CCValue(const APValue &V, GlobalValue) :
Richard Smith9a17a682011-11-07 05:07:52 +0000197 APValue(V), CallFrame(0), Designator(V) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000198
Richard Smith177dce72011-11-01 16:57:24 +0000199 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000200 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000201 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000202 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000203 SubobjectDesignator &getLValueDesignator() {
204 assert(getKind() == LValue);
205 return Designator;
206 }
207 const SubobjectDesignator &getLValueDesignator() const {
208 return const_cast<CCValue*>(this)->getLValueDesignator();
209 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000210 };
211
Richard Smithd0dccea2011-10-28 22:34:42 +0000212 /// A stack frame in the constexpr call stack.
213 struct CallStackFrame {
214 EvalInfo &Info;
215
216 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000217 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000218
Richard Smith180f4792011-11-10 06:34:14 +0000219 /// This - The binding for the this pointer in this call, if any.
220 const LValue *This;
221
Richard Smithd0dccea2011-10-28 22:34:42 +0000222 /// ParmBindings - Parameter bindings for this function call, indexed by
223 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000224 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000225
Richard Smithbd552ef2011-10-31 05:52:43 +0000226 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
227 typedef MapTy::const_iterator temp_iterator;
228 /// Temporaries - Temporary lvalues materialized within this stack frame.
229 MapTy Temporaries;
230
Richard Smith180f4792011-11-10 06:34:14 +0000231 CallStackFrame(EvalInfo &Info, const LValue *This,
232 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000233 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000234 };
235
Richard Smithbd552ef2011-10-31 05:52:43 +0000236 struct EvalInfo {
237 const ASTContext &Ctx;
238
239 /// EvalStatus - Contains information about the evaluation.
240 Expr::EvalStatus &EvalStatus;
241
242 /// CurrentCall - The top of the constexpr call stack.
243 CallStackFrame *CurrentCall;
244
245 /// NumCalls - The number of calls we've evaluated so far.
246 unsigned NumCalls;
247
248 /// CallStackDepth - The number of calls in the call stack right now.
249 unsigned CallStackDepth;
250
251 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
252 /// OpaqueValues - Values used as the common expression in a
253 /// BinaryConditionalOperator.
254 MapTy OpaqueValues;
255
256 /// BottomFrame - The frame in which evaluation started. This must be
257 /// initialized last.
258 CallStackFrame BottomFrame;
259
Richard Smith180f4792011-11-10 06:34:14 +0000260 /// EvaluatingDecl - This is the declaration whose initializer is being
261 /// evaluated, if any.
262 const VarDecl *EvaluatingDecl;
263
264 /// EvaluatingDeclValue - This is the value being constructed for the
265 /// declaration whose initializer is being evaluated, if any.
266 APValue *EvaluatingDeclValue;
267
Richard Smithbd552ef2011-10-31 05:52:43 +0000268
269 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
270 : Ctx(C), EvalStatus(S), CurrentCall(0), NumCalls(0), CallStackDepth(0),
Richard Smith180f4792011-11-10 06:34:14 +0000271 BottomFrame(*this, 0, 0), EvaluatingDecl(0), EvaluatingDeclValue(0) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000272
Richard Smithbd552ef2011-10-31 05:52:43 +0000273 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
274 MapTy::const_iterator i = OpaqueValues.find(e);
275 if (i == OpaqueValues.end()) return 0;
276 return &i->second;
277 }
278
Richard Smith180f4792011-11-10 06:34:14 +0000279 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
280 EvaluatingDecl = VD;
281 EvaluatingDeclValue = &Value;
282 }
283
Richard Smithbd552ef2011-10-31 05:52:43 +0000284 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
285 };
286
Richard Smith180f4792011-11-10 06:34:14 +0000287 CallStackFrame::CallStackFrame(EvalInfo &Info, const LValue *This,
288 const CCValue *Arguments)
289 : Info(Info), Caller(Info.CurrentCall), This(This), Arguments(Arguments) {
Richard Smithbd552ef2011-10-31 05:52:43 +0000290 Info.CurrentCall = this;
291 ++Info.CallStackDepth;
292 }
293
294 CallStackFrame::~CallStackFrame() {
295 assert(Info.CurrentCall == this && "calls retired out of order");
296 --Info.CallStackDepth;
297 Info.CurrentCall = Caller;
298 }
299
John McCallf4cf1a12010-05-07 17:22:02 +0000300 struct ComplexValue {
301 private:
302 bool IsInt;
303
304 public:
305 APSInt IntReal, IntImag;
306 APFloat FloatReal, FloatImag;
307
308 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
309
310 void makeComplexFloat() { IsInt = false; }
311 bool isComplexFloat() const { return !IsInt; }
312 APFloat &getComplexFloatReal() { return FloatReal; }
313 APFloat &getComplexFloatImag() { return FloatImag; }
314
315 void makeComplexInt() { IsInt = true; }
316 bool isComplexInt() const { return IsInt; }
317 APSInt &getComplexIntReal() { return IntReal; }
318 APSInt &getComplexIntImag() { return IntImag; }
319
Richard Smith47a1eed2011-10-29 20:57:55 +0000320 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000321 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000322 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000323 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000324 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000325 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000326 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000327 assert(v.isComplexFloat() || v.isComplexInt());
328 if (v.isComplexFloat()) {
329 makeComplexFloat();
330 FloatReal = v.getComplexFloatReal();
331 FloatImag = v.getComplexFloatImag();
332 } else {
333 makeComplexInt();
334 IntReal = v.getComplexIntReal();
335 IntImag = v.getComplexIntImag();
336 }
337 }
John McCallf4cf1a12010-05-07 17:22:02 +0000338 };
John McCallefdb83e2010-05-07 21:00:08 +0000339
340 struct LValue {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000341 const Expr *Base;
John McCallefdb83e2010-05-07 21:00:08 +0000342 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000343 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000344 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000345
Richard Smith625b8072011-10-31 01:37:14 +0000346 const Expr *getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000347 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000348 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000349 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000350 SubobjectDesignator &getLValueDesignator() { return Designator; }
351 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000352
Richard Smith47a1eed2011-10-29 20:57:55 +0000353 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000354 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000355 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000356 void setFrom(const CCValue &V) {
357 assert(V.isLValue());
358 Base = V.getLValueBase();
359 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000360 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000361 Designator = V.getLValueDesignator();
362 }
363
364 void setExpr(const Expr *E, CallStackFrame *F = 0) {
365 Base = E;
366 Offset = CharUnits::Zero();
367 Frame = F;
368 Designator = SubobjectDesignator();
John McCall56ca35d2011-02-17 10:25:35 +0000369 }
John McCallefdb83e2010-05-07 21:00:08 +0000370 };
John McCallf4cf1a12010-05-07 17:22:02 +0000371}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000372
Richard Smith47a1eed2011-10-29 20:57:55 +0000373static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000374static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith180f4792011-11-10 06:34:14 +0000375 const LValue &This, const Expr *E);
John McCallefdb83e2010-05-07 21:00:08 +0000376static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
377static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000378static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000379static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000380 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000381static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000382static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000383
384//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000385// Misc utilities
386//===----------------------------------------------------------------------===//
387
Richard Smith180f4792011-11-10 06:34:14 +0000388/// Should this call expression be treated as a string literal?
389static bool IsStringLiteralCall(const CallExpr *E) {
390 unsigned Builtin = E->isBuiltinCall();
391 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
392 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
393}
394
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000395static bool IsGlobalLValue(const Expr* E) {
Richard Smith180f4792011-11-10 06:34:14 +0000396 // C++11 [expr.const]p3 An address constant expression is a prvalue core
397 // constant expression of pointer type that evaluates to...
398
399 // ... a null pointer value, or a prvalue core constant expression of type
400 // std::nullptr_t.
John McCall42c8f872010-05-10 23:27:23 +0000401 if (!E) return true;
402
Richard Smith180f4792011-11-10 06:34:14 +0000403 switch (E->getStmtClass()) {
404 default:
405 return false;
406 case Expr::DeclRefExprClass: {
407 const DeclRefExpr *DRE = cast<DeclRefExpr>(E);
408 // ... the address of an object with static storage duration,
John McCall42c8f872010-05-10 23:27:23 +0000409 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
410 return VD->hasGlobalStorage();
Richard Smith180f4792011-11-10 06:34:14 +0000411 // ... to the address of a function,
412 if (isa<FunctionDecl>(DRE->getDecl()))
413 return true;
John McCall42c8f872010-05-10 23:27:23 +0000414 return false;
415 }
Richard Smith180f4792011-11-10 06:34:14 +0000416 case Expr::CompoundLiteralExprClass:
417 return cast<CompoundLiteralExpr>(E)->isFileScope();
418 // A string literal has static storage duration.
419 case Expr::StringLiteralClass:
420 case Expr::PredefinedExprClass:
421 case Expr::ObjCStringLiteralClass:
422 case Expr::ObjCEncodeExprClass:
423 return true;
424 case Expr::CallExprClass:
425 return IsStringLiteralCall(cast<CallExpr>(E));
426 // For GCC compatibility, &&label has static storage duration.
427 case Expr::AddrLabelExprClass:
428 return true;
429 // A Block literal expression may be used as the initialization value for
430 // Block variables at global or local static scope.
431 case Expr::BlockExprClass:
432 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
433 }
John McCall42c8f872010-05-10 23:27:23 +0000434}
435
Richard Smith9a17a682011-11-07 05:07:52 +0000436/// Check that this reference or pointer core constant expression is a valid
437/// value for a constant expression. Type T should be either LValue or CCValue.
438template<typename T>
439static bool CheckLValueConstantExpression(const T &LVal, APValue &Value) {
440 if (!IsGlobalLValue(LVal.getLValueBase()))
441 return false;
442
443 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
444 // A constant expression must refer to an object or be a null pointer.
445 if (Designator.Invalid || Designator.OnePastTheEnd ||
446 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
447 // FIXME: Check for out-of-bounds array indices.
448 // FIXME: This is not a constant expression.
449 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
450 APValue::NoLValuePath());
451 return true;
452 }
453
Richard Smith180f4792011-11-10 06:34:14 +0000454 // FIXME: Null references are not constant expressions.
455
Richard Smith9a17a682011-11-07 05:07:52 +0000456 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
457 Designator.Entries);
458 return true;
459}
460
Richard Smith47a1eed2011-10-29 20:57:55 +0000461/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000462/// constant expression, and if it is, produce the corresponding constant value.
463static bool CheckConstantExpression(const CCValue &CCValue, APValue &Value) {
Richard Smith9a17a682011-11-07 05:07:52 +0000464 if (!CCValue.isLValue()) {
465 Value = CCValue;
466 return true;
467 }
468 return CheckLValueConstantExpression(CCValue, Value);
Richard Smith47a1eed2011-10-29 20:57:55 +0000469}
470
Richard Smith9e36b532011-10-31 05:11:32 +0000471const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
472 if (!LVal.Base)
473 return 0;
474
475 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVal.Base))
476 return DRE->getDecl();
477
478 // FIXME: Static data members accessed via a MemberExpr are represented as
479 // that MemberExpr. We should use the Decl directly instead.
480 if (const MemberExpr *ME = dyn_cast<MemberExpr>(LVal.Base)) {
481 assert(!isa<FieldDecl>(ME->getMemberDecl()) && "shouldn't see fields here");
482 return ME->getMemberDecl();
483 }
484
485 return 0;
486}
487
488static bool IsLiteralLValue(const LValue &Value) {
489 return Value.Base &&
490 !isa<DeclRefExpr>(Value.Base) &&
Richard Smithbd552ef2011-10-31 05:52:43 +0000491 !isa<MemberExpr>(Value.Base) &&
492 !isa<MaterializeTemporaryExpr>(Value.Base);
Richard Smith9e36b532011-10-31 05:11:32 +0000493}
494
Richard Smith65ac5982011-11-01 21:06:14 +0000495static bool IsWeakDecl(const ValueDecl *Decl) {
Richard Smith9e36b532011-10-31 05:11:32 +0000496 return Decl->hasAttr<WeakAttr>() ||
497 Decl->hasAttr<WeakRefAttr>() ||
498 Decl->isWeakImported();
499}
500
Richard Smith65ac5982011-11-01 21:06:14 +0000501static bool IsWeakLValue(const LValue &Value) {
502 const ValueDecl *Decl = GetLValueBaseDecl(Value);
503 return Decl && IsWeakDecl(Decl);
504}
505
Richard Smithc49bd112011-10-28 17:51:58 +0000506static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCallefdb83e2010-05-07 21:00:08 +0000507 const Expr* Base = Value.Base;
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000508
John McCall35542832010-05-07 21:34:32 +0000509 // A null base expression indicates a null pointer. These are always
510 // evaluatable, and they are false unless the offset is zero.
511 if (!Base) {
512 Result = !Value.Offset.isZero();
513 return true;
514 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000515
John McCall42c8f872010-05-10 23:27:23 +0000516 // Require the base expression to be a global l-value.
Richard Smith47a1eed2011-10-29 20:57:55 +0000517 // FIXME: C++11 requires such conversions. Remove this check.
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000518 if (!IsGlobalLValue(Base)) return false;
John McCall42c8f872010-05-10 23:27:23 +0000519
John McCall35542832010-05-07 21:34:32 +0000520 // We have a non-null base expression. These are generally known to
521 // be true, but if it'a decl-ref to a weak symbol it can be null at
522 // runtime.
John McCall35542832010-05-07 21:34:32 +0000523 Result = true;
Richard Smith9e36b532011-10-31 05:11:32 +0000524 return !IsWeakLValue(Value);
Eli Friedman5bc86102009-06-14 02:17:33 +0000525}
526
Richard Smith47a1eed2011-10-29 20:57:55 +0000527static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +0000528 switch (Val.getKind()) {
529 case APValue::Uninitialized:
530 return false;
531 case APValue::Int:
532 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +0000533 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000534 case APValue::Float:
535 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +0000536 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000537 case APValue::ComplexInt:
538 Result = Val.getComplexIntReal().getBoolValue() ||
539 Val.getComplexIntImag().getBoolValue();
540 return true;
541 case APValue::ComplexFloat:
542 Result = !Val.getComplexFloatReal().isZero() ||
543 !Val.getComplexFloatImag().isZero();
544 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +0000545 case APValue::LValue: {
546 LValue PointerResult;
547 PointerResult.setFrom(Val);
548 return EvalPointerValueAsBool(PointerResult, Result);
549 }
Richard Smithc49bd112011-10-28 17:51:58 +0000550 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +0000551 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +0000552 case APValue::Struct:
553 case APValue::Union:
Richard Smithc49bd112011-10-28 17:51:58 +0000554 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000555 }
556
Richard Smithc49bd112011-10-28 17:51:58 +0000557 llvm_unreachable("unknown APValue kind");
558}
559
560static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
561 EvalInfo &Info) {
562 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +0000563 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +0000564 if (!Evaluate(Val, Info, E))
565 return false;
566 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +0000567}
568
Mike Stump1eb44332009-09-09 15:08:12 +0000569static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000570 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000571 unsigned DestWidth = Ctx.getIntWidth(DestType);
572 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000573 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000575 // FIXME: Warning for overflow.
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000576 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000577 bool ignored;
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000578 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
579 return Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000580}
581
Mike Stump1eb44332009-09-09 15:08:12 +0000582static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000583 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000584 bool ignored;
585 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000586 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000587 APFloat::rmNearestTiesToEven, &ignored);
588 return Result;
589}
590
Mike Stump1eb44332009-09-09 15:08:12 +0000591static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000592 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000593 unsigned DestWidth = Ctx.getIntWidth(DestType);
594 APSInt Result = Value;
595 // Figure out if this is a truncate, extend or noop cast.
596 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000597 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000598 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000599 return Result;
600}
601
Mike Stump1eb44332009-09-09 15:08:12 +0000602static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000603 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000604
605 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
606 Result.convertFromAPInt(Value, Value.isSigned(),
607 APFloat::rmNearestTiesToEven);
608 return Result;
609}
610
Richard Smith180f4792011-11-10 06:34:14 +0000611/// If the given LValue refers to a base subobject of some object, find the most
612/// derived object and the corresponding complete record type. This is necessary
613/// in order to find the offset of a virtual base class.
614static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
615 const CXXRecordDecl *&MostDerivedType) {
616 SubobjectDesignator &D = Result.Designator;
617 if (D.Invalid || !Result.Base)
618 return false;
619
620 const Type *T = Result.Base->getType().getTypePtr();
621
622 // Find path prefix which leads to the most-derived subobject.
623 unsigned MostDerivedPathLength = 0;
624 MostDerivedType = T->getAsCXXRecordDecl();
625 bool MostDerivedIsArrayElement = false;
626
627 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
628 bool IsArray = T && T->isArrayType();
629 if (IsArray)
630 T = T->getBaseElementTypeUnsafe();
631 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
632 T = FD->getType().getTypePtr();
633 else
634 T = 0;
635
636 if (T) {
637 MostDerivedType = T->getAsCXXRecordDecl();
638 MostDerivedPathLength = I + 1;
639 MostDerivedIsArrayElement = IsArray;
640 }
641 }
642
643 if (!MostDerivedType)
644 return false;
645
646 // (B*)&d + 1 has no most-derived object.
647 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
648 return false;
649
650 // Remove the trailing base class path entries and their offsets.
651 const RecordDecl *RD = MostDerivedType;
652 for (unsigned I = MostDerivedPathLength, N = D.Entries.size(); I != N; ++I) {
653 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
654 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
655 if (isVirtualBaseClass(D.Entries[I])) {
656 assert(I == MostDerivedPathLength &&
657 "virtual base class must be immediately after most-derived class");
658 Result.Offset -= Layout.getVBaseClassOffset(Base);
659 } else
660 Result.Offset -= Layout.getBaseClassOffset(Base);
661 RD = Base;
662 }
663 D.Entries.resize(MostDerivedPathLength);
664 D.ArrayElement = MostDerivedIsArrayElement;
665 return true;
666}
667
668static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
669 const CXXRecordDecl *Derived,
670 const CXXRecordDecl *Base,
671 const ASTRecordLayout *RL = 0) {
672 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
673 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
674 Obj.Designator.addDecl(Base, /*Virtual*/ false);
675}
676
677static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
678 const CXXRecordDecl *DerivedDecl,
679 const CXXBaseSpecifier *Base) {
680 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
681
682 if (!Base->isVirtual()) {
683 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
684 return true;
685 }
686
687 // Extract most-derived object and corresponding type.
688 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
689 return false;
690
691 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
692 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
693 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
694 return true;
695}
696
697/// Update LVal to refer to the given field, which must be a member of the type
698/// currently described by LVal.
699static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
700 const FieldDecl *FD,
701 const ASTRecordLayout *RL = 0) {
702 if (!RL)
703 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
704
705 unsigned I = FD->getFieldIndex();
706 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
707 LVal.Designator.addDecl(FD);
708}
709
710/// Get the size of the given type in char units.
711static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
712 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
713 // extension.
714 if (Type->isVoidType() || Type->isFunctionType()) {
715 Size = CharUnits::One();
716 return true;
717 }
718
719 if (!Type->isConstantSizeType()) {
720 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
721 return false;
722 }
723
724 Size = Info.Ctx.getTypeSizeInChars(Type);
725 return true;
726}
727
728/// Update a pointer value to model pointer arithmetic.
729/// \param Info - Information about the ongoing evaluation.
730/// \param LVal - The pointer value to be updated.
731/// \param EltTy - The pointee type represented by LVal.
732/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
733static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
734 QualType EltTy, int64_t Adjustment) {
735 CharUnits SizeOfPointee;
736 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
737 return false;
738
739 // Compute the new offset in the appropriate width.
740 LVal.Offset += Adjustment * SizeOfPointee;
741 LVal.Designator.adjustIndex(Adjustment);
742 return true;
743}
744
Richard Smith03f96112011-10-24 17:54:18 +0000745/// Try to evaluate the initializer for a variable declaration.
Richard Smith180f4792011-11-10 06:34:14 +0000746static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +0000747 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +0000748 // If this is a parameter to an active constexpr function call, perform
749 // argument substitution.
750 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith177dce72011-11-01 16:57:24 +0000751 if (!Frame || !Frame->Arguments)
752 return false;
753 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
754 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +0000755 }
Richard Smith03f96112011-10-24 17:54:18 +0000756
Richard Smith180f4792011-11-10 06:34:14 +0000757 // If we're currently evaluating the initializer of this declaration, use that
758 // in-flight value.
759 if (Info.EvaluatingDecl == VD) {
760 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
761 return !Result.isUninit();
762 }
763
Richard Smith65ac5982011-11-01 21:06:14 +0000764 // Never evaluate the initializer of a weak variable. We can't be sure that
765 // this is the definition which will be used.
766 if (IsWeakDecl(VD))
767 return false;
768
Richard Smith03f96112011-10-24 17:54:18 +0000769 const Expr *Init = VD->getAnyInitializer();
Richard Smithdb1822c2011-11-08 01:31:09 +0000770 if (!Init || Init->isValueDependent())
Richard Smith47a1eed2011-10-29 20:57:55 +0000771 return false;
Richard Smith03f96112011-10-24 17:54:18 +0000772
Richard Smith47a1eed2011-10-29 20:57:55 +0000773 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smith177dce72011-11-01 16:57:24 +0000774 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +0000775 return !Result.isUninit();
776 }
Richard Smith03f96112011-10-24 17:54:18 +0000777
778 if (VD->isEvaluatingValue())
Richard Smith47a1eed2011-10-29 20:57:55 +0000779 return false;
Richard Smith03f96112011-10-24 17:54:18 +0000780
781 VD->setEvaluatingValue();
782
Richard Smith47a1eed2011-10-29 20:57:55 +0000783 Expr::EvalStatus EStatus;
784 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith180f4792011-11-10 06:34:14 +0000785 APValue EvalResult;
786 InitInfo.setEvaluatingDecl(VD, EvalResult);
787 LValue LVal;
788 LVal.setExpr(E);
Richard Smithc49bd112011-10-28 17:51:58 +0000789 // FIXME: The caller will need to know whether the value was a constant
790 // expression. If not, we should propagate up a diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +0000791 if (!EvaluateConstantExpression(EvalResult, InitInfo, LVal, Init)) {
Richard Smithcc5d4f62011-11-07 09:22:26 +0000792 // FIXME: If the evaluation failure was not permanent (for instance, if we
793 // hit a variable with no declaration yet, or a constexpr function with no
794 // definition yet), the standard is unclear as to how we should behave.
795 //
796 // Either the initializer should be evaluated when the variable is defined,
797 // or a failed evaluation of the initializer should be reattempted each time
798 // it is used.
Richard Smith03f96112011-10-24 17:54:18 +0000799 VD->setEvaluatedValue(APValue());
Richard Smith47a1eed2011-10-29 20:57:55 +0000800 return false;
801 }
Richard Smith03f96112011-10-24 17:54:18 +0000802
Richard Smith69c2c502011-11-04 05:33:44 +0000803 VD->setEvaluatedValue(EvalResult);
804 Result = CCValue(EvalResult, CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +0000805 return true;
Richard Smith03f96112011-10-24 17:54:18 +0000806}
807
Richard Smithc49bd112011-10-28 17:51:58 +0000808static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +0000809 Qualifiers Quals = T.getQualifiers();
810 return Quals.hasConst() && !Quals.hasVolatile();
811}
812
Richard Smith59efe262011-11-11 04:05:33 +0000813/// Get the base index of the given base class within an APValue representing
814/// the given derived class.
815static unsigned getBaseIndex(const CXXRecordDecl *Derived,
816 const CXXRecordDecl *Base) {
817 Base = Base->getCanonicalDecl();
818 unsigned Index = 0;
819 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
820 E = Derived->bases_end(); I != E; ++I, ++Index) {
821 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
822 return Index;
823 }
824
825 llvm_unreachable("base class missing from derived class's bases list");
826}
827
Richard Smithcc5d4f62011-11-07 09:22:26 +0000828/// Extract the designated sub-object of an rvalue.
829static bool ExtractSubobject(EvalInfo &Info, CCValue &Obj, QualType ObjType,
830 const SubobjectDesignator &Sub, QualType SubType) {
831 if (Sub.Invalid || Sub.OnePastTheEnd)
832 return false;
833 if (Sub.Entries.empty()) {
834 assert(Info.Ctx.hasSameUnqualifiedType(ObjType, SubType) &&
835 "Unexpected subobject type");
836 return true;
837 }
838
839 assert(!Obj.isLValue() && "extracting subobject of lvalue");
840 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +0000841 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +0000842 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +0000843 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +0000844 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +0000845 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
846 if (!CAT)
847 return false;
848 uint64_t Index = Sub.Entries[I].ArrayIndex;
849 if (CAT->getSize().ule(Index))
850 return false;
851 if (O->getArrayInitializedElts() > Index)
852 O = &O->getArrayInitializedElt(Index);
853 else
854 O = &O->getArrayFiller();
855 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +0000856 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
857 // Next subobject is a class, struct or union field.
858 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
859 if (RD->isUnion()) {
860 const FieldDecl *UnionField = O->getUnionField();
861 if (!UnionField ||
862 UnionField->getCanonicalDecl() != Field->getCanonicalDecl())
863 return false;
864 O = &O->getUnionValue();
865 } else
866 O = &O->getStructField(Field->getFieldIndex());
867 ObjType = Field->getType();
Richard Smithcc5d4f62011-11-07 09:22:26 +0000868 } else {
Richard Smith180f4792011-11-10 06:34:14 +0000869 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +0000870 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
871 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
872 O = &O->getStructBase(getBaseIndex(Derived, Base));
873 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +0000874 }
Richard Smith180f4792011-11-10 06:34:14 +0000875
876 if (O->isUninit())
877 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +0000878 }
879
880 assert(Info.Ctx.hasSameUnqualifiedType(ObjType, SubType) &&
881 "Unexpected subobject type");
882 Obj = CCValue(*O, CCValue::GlobalValue());
883 return true;
884}
885
Richard Smith180f4792011-11-10 06:34:14 +0000886/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
887/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
888/// for looking up the glvalue referred to by an entity of reference type.
889///
890/// \param Info - Information about the ongoing evaluation.
891/// \param Type - The type we expect this conversion to produce.
892/// \param LVal - The glvalue on which we are attempting to perform this action.
893/// \param RVal - The produced value will be placed here.
Richard Smithcc5d4f62011-11-07 09:22:26 +0000894static bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
895 const LValue &LVal, CCValue &RVal) {
Richard Smithc49bd112011-10-28 17:51:58 +0000896 const Expr *Base = LVal.Base;
Richard Smith177dce72011-11-01 16:57:24 +0000897 CallStackFrame *Frame = LVal.Frame;
Richard Smithc49bd112011-10-28 17:51:58 +0000898
899 // FIXME: Indirection through a null pointer deserves a diagnostic.
900 if (!Base)
901 return false;
902
Richard Smith625b8072011-10-31 01:37:14 +0000903 if (const ValueDecl *D = GetLValueBaseDecl(LVal)) {
Richard Smithc49bd112011-10-28 17:51:58 +0000904 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
905 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +0000906 // expressions are constant expressions too. Inside constexpr functions,
907 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +0000908 // In C, such things can also be folded, although they are not ICEs.
909 //
Richard Smithd0dccea2011-10-28 22:34:42 +0000910 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
911 // interpretation of C++11 suggests that volatile parameters are OK if
912 // they're never read (there's no prohibition against constructing volatile
913 // objects in constant expressions), but lvalue-to-rvalue conversions on
914 // them are not permitted.
Richard Smithc49bd112011-10-28 17:51:58 +0000915 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000916 QualType VT = VD->getType();
Richard Smithcd689922011-11-07 03:22:51 +0000917 if (!VD || VD->isInvalidDecl())
Richard Smith0a3bdb62011-11-04 02:25:55 +0000918 return false;
919 if (!isa<ParmVarDecl>(VD)) {
920 if (!IsConstNonVolatile(VT))
921 return false;
Richard Smithcd689922011-11-07 03:22:51 +0000922 // FIXME: Allow folding of values of any literal type in all languages.
923 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
924 !VD->isConstexpr())
Richard Smith0a3bdb62011-11-04 02:25:55 +0000925 return false;
926 }
Richard Smith180f4792011-11-10 06:34:14 +0000927 if (!EvaluateVarDeclInit(Info, LVal.Base, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +0000928 return false;
929
Richard Smith47a1eed2011-10-29 20:57:55 +0000930 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithcc5d4f62011-11-07 09:22:26 +0000931 return ExtractSubobject(Info, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +0000932
933 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
934 // conversion. This happens when the declaration and the lvalue should be
935 // considered synonymous, for instance when initializing an array of char
936 // from a string literal. Continue as if the initializer lvalue was the
937 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +0000938 assert(RVal.getLValueOffset().isZero() &&
939 "offset for lvalue init of non-reference");
Richard Smith47a1eed2011-10-29 20:57:55 +0000940 Base = RVal.getLValueBase();
Richard Smith177dce72011-11-01 16:57:24 +0000941 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +0000942 }
943
Richard Smith0a3bdb62011-11-04 02:25:55 +0000944 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
945 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
946 const SubobjectDesignator &Designator = LVal.Designator;
947 if (Designator.Invalid || Designator.Entries.size() != 1)
948 return false;
949
950 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +0000951 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000952 if (Index > S->getLength())
953 return false;
954 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
955 Type->isUnsignedIntegerType());
956 if (Index < S->getLength())
957 Value = S->getCodeUnit(Index);
958 RVal = CCValue(Value);
959 return true;
960 }
961
Richard Smithcc5d4f62011-11-07 09:22:26 +0000962 if (Frame) {
963 // If this is a temporary expression with a nontrivial initializer, grab the
964 // value from the relevant stack frame.
965 RVal = Frame->Temporaries[Base];
966 } else if (const CompoundLiteralExpr *CLE
967 = dyn_cast<CompoundLiteralExpr>(Base)) {
968 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
969 // initializer until now for such expressions. Such an expression can't be
970 // an ICE in C, so this only matters for fold.
971 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
972 if (!Evaluate(RVal, Info, CLE->getInitializer()))
973 return false;
974 } else
Richard Smith0a3bdb62011-11-04 02:25:55 +0000975 return false;
976
Richard Smithcc5d4f62011-11-07 09:22:26 +0000977 return ExtractSubobject(Info, RVal, Base->getType(), LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +0000978}
979
Richard Smith59efe262011-11-11 04:05:33 +0000980/// Build an lvalue for the object argument of a member function call.
981static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
982 LValue &This) {
983 if (Object->getType()->isPointerType())
984 return EvaluatePointer(Object, This, Info);
985
986 if (Object->isGLValue())
987 return EvaluateLValue(Object, This, Info);
988
989 // Implicitly promote a prvalue *this object to a glvalue.
990 This.setExpr(Object, Info.CurrentCall);
991 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[Object], Info,
992 This, Object);
993}
994
Mike Stumpc4c90452009-10-27 22:09:17 +0000995namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +0000996enum EvalStmtResult {
997 /// Evaluation failed.
998 ESR_Failed,
999 /// Hit a 'return' statement.
1000 ESR_Returned,
1001 /// Evaluation succeeded.
1002 ESR_Succeeded
1003};
1004}
1005
1006// Evaluate a statement.
Richard Smith47a1eed2011-10-29 20:57:55 +00001007static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001008 const Stmt *S) {
1009 switch (S->getStmtClass()) {
1010 default:
1011 return ESR_Failed;
1012
1013 case Stmt::NullStmtClass:
1014 case Stmt::DeclStmtClass:
1015 return ESR_Succeeded;
1016
1017 case Stmt::ReturnStmtClass:
1018 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
1019 return ESR_Returned;
1020 return ESR_Failed;
1021
1022 case Stmt::CompoundStmtClass: {
1023 const CompoundStmt *CS = cast<CompoundStmt>(S);
1024 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1025 BE = CS->body_end(); BI != BE; ++BI) {
1026 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1027 if (ESR != ESR_Succeeded)
1028 return ESR;
1029 }
1030 return ESR_Succeeded;
1031 }
1032 }
1033}
1034
Richard Smith180f4792011-11-10 06:34:14 +00001035namespace {
1036typedef SmallVector<CCValue, 16> ArgVector;
1037}
1038
1039/// EvaluateArgs - Evaluate the arguments to a function call.
1040static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1041 EvalInfo &Info) {
1042 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1043 I != E; ++I)
1044 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1045 return false;
1046 return true;
1047}
1048
Richard Smithd0dccea2011-10-28 22:34:42 +00001049/// Evaluate a function call.
Richard Smith59efe262011-11-11 04:05:33 +00001050static bool HandleFunctionCall(const LValue *This, ArrayRef<const Expr*> Args,
1051 const Stmt *Body, EvalInfo &Info,
1052 CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001053 // FIXME: Implement a proper call limit, along with a command-line flag.
1054 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
1055 return false;
1056
Richard Smith180f4792011-11-10 06:34:14 +00001057 ArgVector ArgValues(Args.size());
1058 if (!EvaluateArgs(Args, ArgValues, Info))
1059 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001060
Richard Smith180f4792011-11-10 06:34:14 +00001061 CallStackFrame Frame(Info, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001062 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1063}
1064
Richard Smith180f4792011-11-10 06:34:14 +00001065/// Evaluate a constructor call.
Richard Smith59efe262011-11-11 04:05:33 +00001066static bool HandleConstructorCall(const LValue &This,
1067 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001068 const CXXConstructorDecl *Definition,
Richard Smith59efe262011-11-11 04:05:33 +00001069 EvalInfo &Info,
Richard Smith180f4792011-11-10 06:34:14 +00001070 APValue &Result) {
1071 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
1072 return false;
1073
1074 ArgVector ArgValues(Args.size());
1075 if (!EvaluateArgs(Args, ArgValues, Info))
1076 return false;
1077
1078 CallStackFrame Frame(Info, &This, ArgValues.data());
1079
1080 // If it's a delegating constructor, just delegate.
1081 if (Definition->isDelegatingConstructor()) {
1082 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1083 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1084 }
1085
1086 // Reserve space for the struct members.
1087 const CXXRecordDecl *RD = Definition->getParent();
1088 if (!RD->isUnion())
1089 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1090 std::distance(RD->field_begin(), RD->field_end()));
1091
1092 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1093
1094 unsigned BasesSeen = 0;
1095#ifndef NDEBUG
1096 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1097#endif
1098 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1099 E = Definition->init_end(); I != E; ++I) {
1100 if ((*I)->isBaseInitializer()) {
1101 QualType BaseType((*I)->getBaseClass(), 0);
1102#ifndef NDEBUG
1103 // Non-virtual base classes are initialized in the order in the class
1104 // definition. We cannot have a virtual base class for a literal type.
1105 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1106 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1107 "base class initializers not in expected order");
1108 ++BaseIt;
1109#endif
1110 LValue Subobject = This;
1111 HandleLValueDirectBase(Info, Subobject, RD,
1112 BaseType->getAsCXXRecordDecl(), &Layout);
1113 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1114 Subobject, (*I)->getInit()))
1115 return false;
1116 } else if (FieldDecl *FD = (*I)->getMember()) {
1117 LValue Subobject = This;
1118 HandleLValueMember(Info, Subobject, FD, &Layout);
1119 if (RD->isUnion()) {
1120 Result = APValue(FD);
1121 if (!EvaluateConstantExpression(Result.getUnionValue(), Info,
1122 Subobject, (*I)->getInit()))
1123 return false;
1124 } else if (!EvaluateConstantExpression(
1125 Result.getStructField(FD->getFieldIndex()),
1126 Info, Subobject, (*I)->getInit()))
1127 return false;
1128 } else {
1129 // FIXME: handle indirect field initializers
1130 return false;
1131 }
1132 }
1133
1134 return true;
1135}
1136
Richard Smithd0dccea2011-10-28 22:34:42 +00001137namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001138class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001139 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00001140 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00001141public:
1142
Richard Smith1e12c592011-10-16 21:26:27 +00001143 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00001144
1145 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001146 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00001147 return true;
1148 }
1149
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001150 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1151 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001152 return Visit(E->getResultExpr());
1153 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001154 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001155 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001156 return true;
1157 return false;
1158 }
John McCallf85e1932011-06-15 23:02:42 +00001159 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001160 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001161 return true;
1162 return false;
1163 }
1164 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001165 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001166 return true;
1167 return false;
1168 }
1169
Mike Stumpc4c90452009-10-27 22:09:17 +00001170 // We don't want to evaluate BlockExprs multiple times, as they generate
1171 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001172 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1173 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1174 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00001175 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001176 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1177 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1178 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1179 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1180 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1181 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001182 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001183 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00001184 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001185 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00001186 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001187 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1188 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1189 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1190 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00001191 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001192 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1193 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1194 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1195 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1196 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001197 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001198 return true;
Mike Stump980ca222009-10-29 20:48:09 +00001199 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00001200 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001201 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00001202
1203 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001204 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00001205 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1206 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001207 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00001208 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00001209 return false;
1210 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00001211
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001212 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00001213};
1214
John McCall56ca35d2011-02-17 10:25:35 +00001215class OpaqueValueEvaluation {
1216 EvalInfo &info;
1217 OpaqueValueExpr *opaqueValue;
1218
1219public:
1220 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1221 Expr *value)
1222 : info(info), opaqueValue(opaqueValue) {
1223
1224 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00001225 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00001226 this->opaqueValue = 0;
1227 return;
1228 }
John McCall56ca35d2011-02-17 10:25:35 +00001229 }
1230
1231 bool hasError() const { return opaqueValue == 0; }
1232
1233 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00001234 // FIXME: This will not work for recursive constexpr functions using opaque
1235 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00001236 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1237 }
1238};
1239
Mike Stumpc4c90452009-10-27 22:09:17 +00001240} // end anonymous namespace
1241
Eli Friedman4efaa272008-11-12 09:44:48 +00001242//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001243// Generic Evaluation
1244//===----------------------------------------------------------------------===//
1245namespace {
1246
1247template <class Derived, typename RetTy=void>
1248class ExprEvaluatorBase
1249 : public ConstStmtVisitor<Derived, RetTy> {
1250private:
Richard Smith47a1eed2011-10-29 20:57:55 +00001251 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001252 return static_cast<Derived*>(this)->Success(V, E);
1253 }
1254 RetTy DerivedError(const Expr *E) {
1255 return static_cast<Derived*>(this)->Error(E);
1256 }
Richard Smithf10d9172011-10-11 21:43:33 +00001257 RetTy DerivedValueInitialization(const Expr *E) {
1258 return static_cast<Derived*>(this)->ValueInitialization(E);
1259 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001260
1261protected:
1262 EvalInfo &Info;
1263 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1264 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1265
Richard Smithf10d9172011-10-11 21:43:33 +00001266 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
1267
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001268public:
1269 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1270
1271 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001272 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001273 }
1274 RetTy VisitExpr(const Expr *E) {
1275 return DerivedError(E);
1276 }
1277
1278 RetTy VisitParenExpr(const ParenExpr *E)
1279 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1280 RetTy VisitUnaryExtension(const UnaryOperator *E)
1281 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1282 RetTy VisitUnaryPlus(const UnaryOperator *E)
1283 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1284 RetTy VisitChooseExpr(const ChooseExpr *E)
1285 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1286 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1287 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00001288 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1289 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00001290 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1291 { return StmtVisitorTy::Visit(E->getExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001292
1293 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1294 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1295 if (opaque.hasError())
1296 return DerivedError(E);
1297
1298 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00001299 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001300 return DerivedError(E);
1301
1302 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1303 }
1304
1305 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1306 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00001307 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001308 return DerivedError(E);
1309
Richard Smithc49bd112011-10-28 17:51:58 +00001310 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001311 return StmtVisitorTy::Visit(EvalExpr);
1312 }
1313
1314 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001315 const CCValue *Value = Info.getOpaqueValue(E);
1316 if (!Value)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001317 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
1318 : DerivedError(E));
Richard Smith47a1eed2011-10-29 20:57:55 +00001319 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001320 }
Richard Smithf10d9172011-10-11 21:43:33 +00001321
Richard Smithd0dccea2011-10-28 22:34:42 +00001322 RetTy VisitCallExpr(const CallExpr *E) {
1323 const Expr *Callee = E->getCallee();
1324 QualType CalleeType = Callee->getType();
1325
Richard Smithd0dccea2011-10-28 22:34:42 +00001326 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00001327 LValue *This = 0, ThisVal;
1328 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00001329
Richard Smith59efe262011-11-11 04:05:33 +00001330 // Extract function decl and 'this' pointer from the callee.
1331 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
1332 // Explicit bound member calls, such as x.f() or p->g();
1333 // FIXME: Handle a BinaryOperator callee ('.*' or '->*').
1334 const MemberExpr *ME = dyn_cast<MemberExpr>(Callee->IgnoreParens());
1335 if (!ME)
1336 return DerivedError(Callee);
1337 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
1338 return DerivedError(ME->getBase());
1339 This = &ThisVal;
1340 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
1341 if (!FD)
1342 return DerivedError(ME);
1343 } else if (CalleeType->isFunctionPointerType()) {
1344 CCValue Call;
1345 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
1346 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
1347 return DerivedError(Callee);
1348
1349 const Expr *Base = Call.getLValueBase();
1350
1351 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
1352 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
1353 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
1354 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
1355 if (!FD)
1356 return DerivedError(Callee);
1357
1358 // Overloaded operator calls to member functions are represented as normal
1359 // calls with '*this' as the first argument.
1360 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1361 if (MD && !MD->isStatic()) {
1362 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
1363 return false;
1364 This = &ThisVal;
1365 Args = Args.slice(1);
1366 }
1367
1368 // Don't call function pointers which have been cast to some other type.
1369 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
1370 return DerivedError(E);
1371 } else
Devang Patel6142ca72011-11-10 17:47:39 +00001372 return DerivedError(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00001373
1374 const FunctionDecl *Definition;
1375 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00001376 CCValue CCResult;
1377 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00001378
1379 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
Richard Smith59efe262011-11-11 04:05:33 +00001380 HandleFunctionCall(This, Args, Body, Info, CCResult) &&
Richard Smith69c2c502011-11-04 05:33:44 +00001381 CheckConstantExpression(CCResult, Result))
1382 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00001383
1384 return DerivedError(E);
1385 }
1386
Richard Smithc49bd112011-10-28 17:51:58 +00001387 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1388 return StmtVisitorTy::Visit(E->getInitializer());
1389 }
Richard Smithf10d9172011-10-11 21:43:33 +00001390 RetTy VisitInitListExpr(const InitListExpr *E) {
1391 if (Info.getLangOpts().CPlusPlus0x) {
1392 if (E->getNumInits() == 0)
1393 return DerivedValueInitialization(E);
1394 if (E->getNumInits() == 1)
1395 return StmtVisitorTy::Visit(E->getInit(0));
1396 }
1397 return DerivedError(E);
1398 }
1399 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1400 return DerivedValueInitialization(E);
1401 }
1402 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1403 return DerivedValueInitialization(E);
1404 }
1405
Richard Smith180f4792011-11-10 06:34:14 +00001406 /// A member expression where the object is a prvalue is itself a prvalue.
1407 RetTy VisitMemberExpr(const MemberExpr *E) {
1408 assert(!E->isArrow() && "missing call to bound member function?");
1409
1410 CCValue Val;
1411 if (!Evaluate(Val, Info, E->getBase()))
1412 return false;
1413
1414 QualType BaseTy = E->getBase()->getType();
1415
1416 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1417 if (!FD) return false;
1418 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
1419 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1420 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1421
1422 SubobjectDesignator Designator;
1423 Designator.addDecl(FD);
1424
1425 return ExtractSubobject(Info, Val, BaseTy, Designator, E->getType()) &&
1426 DerivedSuccess(Val, E);
1427 }
1428
Richard Smithc49bd112011-10-28 17:51:58 +00001429 RetTy VisitCastExpr(const CastExpr *E) {
1430 switch (E->getCastKind()) {
1431 default:
1432 break;
1433
1434 case CK_NoOp:
1435 return StmtVisitorTy::Visit(E->getSubExpr());
1436
1437 case CK_LValueToRValue: {
1438 LValue LVal;
1439 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001440 CCValue RVal;
Richard Smithc49bd112011-10-28 17:51:58 +00001441 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
1442 return DerivedSuccess(RVal, E);
1443 }
1444 break;
1445 }
1446 }
1447
1448 return DerivedError(E);
1449 }
1450
Richard Smith8327fad2011-10-24 18:44:57 +00001451 /// Visit a value which is evaluated, but whose value is ignored.
1452 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001453 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00001454 if (!Evaluate(Scratch, Info, E))
1455 Info.EvalStatus.HasSideEffects = true;
1456 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001457};
1458
1459}
1460
1461//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00001462// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00001463//
1464// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
1465// function designators (in C), decl references to void objects (in C), and
1466// temporaries (if building with -Wno-address-of-temporary).
1467//
1468// LValue evaluation produces values comprising a base expression of one of the
1469// following types:
1470// * DeclRefExpr
1471// * MemberExpr for a static member
1472// * CompoundLiteralExpr in C
1473// * StringLiteral
1474// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00001475// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00001476// * ObjCEncodeExpr
1477// * AddrLabelExpr
1478// * BlockExpr
1479// * CallExpr for a MakeStringConstant builtin
Richard Smith177dce72011-11-01 16:57:24 +00001480// plus an offset in bytes. It can also produce lvalues referring to locals. In
1481// that case, the Frame will point to a stack frame, and the Expr is used as a
1482// key to find the relevant temporary's value.
Eli Friedman4efaa272008-11-12 09:44:48 +00001483//===----------------------------------------------------------------------===//
1484namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001485class LValueExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001486 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00001487 LValue &Result;
Chandler Carruth01248392011-08-22 17:24:56 +00001488 const Decl *PrevDecl;
John McCallefdb83e2010-05-07 21:00:08 +00001489
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001490 bool Success(const Expr *E) {
Richard Smith0a3bdb62011-11-04 02:25:55 +00001491 Result.setExpr(E);
John McCallefdb83e2010-05-07 21:00:08 +00001492 return true;
1493 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001494public:
Mike Stump1eb44332009-09-09 15:08:12 +00001495
John McCallefdb83e2010-05-07 21:00:08 +00001496 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth01248392011-08-22 17:24:56 +00001497 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman4efaa272008-11-12 09:44:48 +00001498
Richard Smith47a1eed2011-10-29 20:57:55 +00001499 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001500 Result.setFrom(V);
1501 return true;
1502 }
1503 bool Error(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +00001504 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001505 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001506
Richard Smithc49bd112011-10-28 17:51:58 +00001507 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
1508
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001509 bool VisitDeclRefExpr(const DeclRefExpr *E);
1510 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00001511 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001512 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1513 bool VisitMemberExpr(const MemberExpr *E);
1514 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
1515 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
1516 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
1517 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00001518
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001519 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00001520 switch (E->getCastKind()) {
1521 default:
Richard Smithc49bd112011-10-28 17:51:58 +00001522 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00001523
Eli Friedmandb924222011-10-11 00:13:24 +00001524 case CK_LValueBitCast:
Richard Smith0a3bdb62011-11-04 02:25:55 +00001525 if (!Visit(E->getSubExpr()))
1526 return false;
1527 Result.Designator.setInvalid();
1528 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00001529
Richard Smith180f4792011-11-10 06:34:14 +00001530 case CK_DerivedToBase:
1531 case CK_UncheckedDerivedToBase: {
1532 if (!Visit(E->getSubExpr()))
1533 return false;
1534
1535 // Now figure out the necessary offset to add to the base LV to get from
1536 // the derived class to the base class.
1537 QualType Type = E->getSubExpr()->getType();
1538
1539 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1540 PathE = E->path_end(); PathI != PathE; ++PathI) {
1541 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
1542 return false;
1543 Type = (*PathI)->getType();
1544 }
1545
1546 return true;
1547 }
Anders Carlsson26bc2202009-10-03 16:30:22 +00001548 }
1549 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00001550
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001551 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001552
Eli Friedman4efaa272008-11-12 09:44:48 +00001553};
1554} // end anonymous namespace
1555
Richard Smithc49bd112011-10-28 17:51:58 +00001556/// Evaluate an expression as an lvalue. This can be legitimately called on
1557/// expressions which are not glvalues, in a few cases:
1558/// * function designators in C,
1559/// * "extern void" objects,
1560/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00001561static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00001562 assert((E->isGLValue() || E->getType()->isFunctionType() ||
1563 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
1564 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001565 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001566}
1567
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001568bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00001569 if (isa<FunctionDecl>(E->getDecl()))
John McCallefdb83e2010-05-07 21:00:08 +00001570 return Success(E);
Richard Smithc49bd112011-10-28 17:51:58 +00001571 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
1572 return VisitVarDecl(E, VD);
1573 return Error(E);
1574}
Richard Smith436c8892011-10-24 23:14:33 +00001575
Richard Smithc49bd112011-10-28 17:51:58 +00001576bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00001577 if (!VD->getType()->isReferenceType()) {
1578 if (isa<ParmVarDecl>(VD)) {
Richard Smith0a3bdb62011-11-04 02:25:55 +00001579 Result.setExpr(E, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00001580 return true;
1581 }
Richard Smithc49bd112011-10-28 17:51:58 +00001582 return Success(E);
Richard Smith177dce72011-11-01 16:57:24 +00001583 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00001584
Richard Smith47a1eed2011-10-29 20:57:55 +00001585 CCValue V;
Richard Smith180f4792011-11-10 06:34:14 +00001586 if (EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
Richard Smith47a1eed2011-10-29 20:57:55 +00001587 return Success(V, E);
Richard Smithc49bd112011-10-28 17:51:58 +00001588
1589 return Error(E);
Anders Carlsson35873c42008-11-24 04:41:22 +00001590}
1591
Richard Smithbd552ef2011-10-31 05:52:43 +00001592bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
1593 const MaterializeTemporaryExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00001594 Result.setExpr(E, Info.CurrentCall);
1595 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
1596 Result, E->GetTemporaryExpr());
Richard Smithbd552ef2011-10-31 05:52:43 +00001597}
1598
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001599bool
1600LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00001601 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1602 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
1603 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00001604 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001605}
1606
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001607bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00001608 // Handle static data members.
1609 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
1610 VisitIgnoredValue(E->getBase());
1611 return VisitVarDecl(E, VD);
1612 }
1613
Richard Smithd0dccea2011-10-28 22:34:42 +00001614 // Handle static member functions.
1615 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
1616 if (MD->isStatic()) {
1617 VisitIgnoredValue(E->getBase());
1618 return Success(E);
1619 }
1620 }
1621
Richard Smith180f4792011-11-10 06:34:14 +00001622 // Handle non-static data members.
1623 QualType BaseTy;
Eli Friedman4efaa272008-11-12 09:44:48 +00001624 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +00001625 if (!EvaluatePointer(E->getBase(), Result, Info))
1626 return false;
Richard Smith180f4792011-11-10 06:34:14 +00001627 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +00001628 } else {
John McCallefdb83e2010-05-07 21:00:08 +00001629 if (!Visit(E->getBase()))
1630 return false;
Richard Smith180f4792011-11-10 06:34:14 +00001631 BaseTy = E->getBase()->getType();
Eli Friedman4efaa272008-11-12 09:44:48 +00001632 }
1633
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001634 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smith180f4792011-11-10 06:34:14 +00001635 if (!FD) return false;
1636 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1637 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1638 (void)BaseTy;
Eli Friedman2be58612009-05-30 21:09:44 +00001639
Richard Smith180f4792011-11-10 06:34:14 +00001640 HandleLValueMember(Info, Result, FD);
Eli Friedman2be58612009-05-30 21:09:44 +00001641
Richard Smith180f4792011-11-10 06:34:14 +00001642 if (FD->getType()->isReferenceType()) {
1643 CCValue RefValue;
1644 if (!HandleLValueToRValueConversion(Info, FD->getType(), Result, RefValue))
1645 return false;
1646 return Success(RefValue, E);
1647 }
John McCallefdb83e2010-05-07 21:00:08 +00001648 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +00001649}
1650
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001651bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00001652 // FIXME: Deal with vectors as array subscript bases.
1653 if (E->getBase()->getType()->isVectorType())
1654 return false;
1655
Anders Carlsson3068d112008-11-16 19:01:22 +00001656 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00001657 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Anders Carlsson3068d112008-11-16 19:01:22 +00001659 APSInt Index;
1660 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00001661 return false;
Richard Smith180f4792011-11-10 06:34:14 +00001662 int64_t IndexValue
1663 = Index.isSigned() ? Index.getSExtValue()
1664 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00001665
Richard Smith180f4792011-11-10 06:34:14 +00001666 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00001667}
Eli Friedman4efaa272008-11-12 09:44:48 +00001668
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001669bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00001670 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00001671}
1672
Eli Friedman4efaa272008-11-12 09:44:48 +00001673//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001674// Pointer Evaluation
1675//===----------------------------------------------------------------------===//
1676
Anders Carlssonc754aa62008-07-08 05:13:58 +00001677namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001678class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001679 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00001680 LValue &Result;
1681
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001682 bool Success(const Expr *E) {
Richard Smith0a3bdb62011-11-04 02:25:55 +00001683 Result.setExpr(E);
John McCallefdb83e2010-05-07 21:00:08 +00001684 return true;
1685 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00001686public:
Mike Stump1eb44332009-09-09 15:08:12 +00001687
John McCallefdb83e2010-05-07 21:00:08 +00001688 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001689 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001690
Richard Smith47a1eed2011-10-29 20:57:55 +00001691 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001692 Result.setFrom(V);
1693 return true;
1694 }
1695 bool Error(const Stmt *S) {
John McCallefdb83e2010-05-07 21:00:08 +00001696 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +00001697 }
Richard Smithf10d9172011-10-11 21:43:33 +00001698 bool ValueInitialization(const Expr *E) {
1699 return Success((Expr*)0);
1700 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00001701
John McCallefdb83e2010-05-07 21:00:08 +00001702 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001703 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00001704 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001705 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00001706 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001707 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00001708 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001709 bool VisitCallExpr(const CallExpr *E);
1710 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00001711 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00001712 return Success(E);
1713 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +00001714 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001715 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smithf10d9172011-10-11 21:43:33 +00001716 { return ValueInitialization(E); }
Richard Smith180f4792011-11-10 06:34:14 +00001717 bool VisitCXXThisExpr(const CXXThisExpr *E) {
1718 if (!Info.CurrentCall->This)
1719 return false;
1720 Result = *Info.CurrentCall->This;
1721 return true;
1722 }
John McCall56ca35d2011-02-17 10:25:35 +00001723
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001724 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00001725};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001726} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001727
John McCallefdb83e2010-05-07 21:00:08 +00001728static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00001729 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001730 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001731}
1732
John McCallefdb83e2010-05-07 21:00:08 +00001733bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001734 if (E->getOpcode() != BO_Add &&
1735 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +00001736 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001737
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001738 const Expr *PExp = E->getLHS();
1739 const Expr *IExp = E->getRHS();
1740 if (IExp->getType()->isPointerType())
1741 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00001742
John McCallefdb83e2010-05-07 21:00:08 +00001743 if (!EvaluatePointer(PExp, Result, Info))
1744 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001745
John McCallefdb83e2010-05-07 21:00:08 +00001746 llvm::APSInt Offset;
1747 if (!EvaluateInteger(IExp, Offset, Info))
1748 return false;
1749 int64_t AdditionalOffset
1750 = Offset.isSigned() ? Offset.getSExtValue()
1751 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00001752 if (E->getOpcode() == BO_Sub)
1753 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001754
Richard Smith180f4792011-11-10 06:34:14 +00001755 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
1756 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001757}
Eli Friedman4efaa272008-11-12 09:44:48 +00001758
John McCallefdb83e2010-05-07 21:00:08 +00001759bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1760 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00001761}
Mike Stump1eb44332009-09-09 15:08:12 +00001762
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001763bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1764 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001765
Eli Friedman09a8a0e2009-12-27 05:43:15 +00001766 switch (E->getCastKind()) {
1767 default:
1768 break;
1769
John McCall2de56d12010-08-25 11:45:40 +00001770 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00001771 case CK_CPointerToObjCPointerCast:
1772 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00001773 case CK_AnyPointerToBlockPointerCast:
Richard Smith0a3bdb62011-11-04 02:25:55 +00001774 if (!Visit(SubExpr))
1775 return false;
1776 Result.Designator.setInvalid();
1777 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00001778
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001779 case CK_DerivedToBase:
1780 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00001781 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001782 return false;
1783
Richard Smith180f4792011-11-10 06:34:14 +00001784 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001785 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00001786 QualType Type =
1787 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001788
Richard Smith180f4792011-11-10 06:34:14 +00001789 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001790 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smith180f4792011-11-10 06:34:14 +00001791 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001792 return false;
Richard Smith180f4792011-11-10 06:34:14 +00001793 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001794 }
1795
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001796 return true;
1797 }
1798
Richard Smith47a1eed2011-10-29 20:57:55 +00001799 case CK_NullToPointer:
1800 return ValueInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00001801
John McCall2de56d12010-08-25 11:45:40 +00001802 case CK_IntegralToPointer: {
Richard Smith47a1eed2011-10-29 20:57:55 +00001803 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00001804 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00001805 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001806
John McCallefdb83e2010-05-07 21:00:08 +00001807 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001808 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1809 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
John McCallefdb83e2010-05-07 21:00:08 +00001810 Result.Base = 0;
Richard Smith47a1eed2011-10-29 20:57:55 +00001811 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00001812 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00001813 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00001814 return true;
1815 } else {
1816 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00001817 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00001818 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001819 }
1820 }
John McCall2de56d12010-08-25 11:45:40 +00001821 case CK_ArrayToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00001822 // FIXME: Support array-to-pointer decay on array rvalues.
1823 if (!SubExpr->isGLValue())
1824 return Error(E);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001825 if (!EvaluateLValue(SubExpr, Result, Info))
1826 return false;
1827 // The result is a pointer to the first element of the array.
1828 Result.Designator.addIndex(0);
1829 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00001830
John McCall2de56d12010-08-25 11:45:40 +00001831 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00001832 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00001833 }
1834
Richard Smithc49bd112011-10-28 17:51:58 +00001835 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001836}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001837
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001838bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00001839 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00001840 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00001841
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001842 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001843}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001844
1845//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00001846// Record Evaluation
1847//===----------------------------------------------------------------------===//
1848
1849namespace {
1850 class RecordExprEvaluator
1851 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
1852 const LValue &This;
1853 APValue &Result;
1854 public:
1855
1856 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
1857 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
1858
1859 bool Success(const CCValue &V, const Expr *E) {
1860 return CheckConstantExpression(V, Result);
1861 }
1862 bool Error(const Expr *E) { return false; }
1863
Richard Smith59efe262011-11-11 04:05:33 +00001864 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00001865 bool VisitInitListExpr(const InitListExpr *E);
1866 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
1867 };
1868}
1869
Richard Smith59efe262011-11-11 04:05:33 +00001870bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
1871 switch (E->getCastKind()) {
1872 default:
1873 return ExprEvaluatorBaseTy::VisitCastExpr(E);
1874
1875 case CK_ConstructorConversion:
1876 return Visit(E->getSubExpr());
1877
1878 case CK_DerivedToBase:
1879 case CK_UncheckedDerivedToBase: {
1880 CCValue DerivedObject;
1881 if (!Evaluate(DerivedObject, Info, E->getSubExpr()) ||
1882 !DerivedObject.isStruct())
1883 return false;
1884
1885 // Derived-to-base rvalue conversion: just slice off the derived part.
1886 APValue *Value = &DerivedObject;
1887 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
1888 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1889 PathE = E->path_end(); PathI != PathE; ++PathI) {
1890 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
1891 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
1892 Value = &Value->getStructBase(getBaseIndex(RD, Base));
1893 RD = Base;
1894 }
1895 Result = *Value;
1896 return true;
1897 }
1898 }
1899}
1900
Richard Smith180f4792011-11-10 06:34:14 +00001901bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
1902 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
1903 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1904
1905 if (RD->isUnion()) {
1906 Result = APValue(E->getInitializedFieldInUnion());
1907 if (!E->getNumInits())
1908 return true;
1909 LValue Subobject = This;
1910 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
1911 &Layout);
1912 return EvaluateConstantExpression(Result.getUnionValue(), Info,
1913 Subobject, E->getInit(0));
1914 }
1915
1916 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
1917 "initializer list for class with base classes");
1918 Result = APValue(APValue::UninitStruct(), 0,
1919 std::distance(RD->field_begin(), RD->field_end()));
1920 unsigned ElementNo = 0;
1921 for (RecordDecl::field_iterator Field = RD->field_begin(),
1922 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
1923 // Anonymous bit-fields are not considered members of the class for
1924 // purposes of aggregate initialization.
1925 if (Field->isUnnamedBitfield())
1926 continue;
1927
1928 LValue Subobject = This;
1929 HandleLValueMember(Info, Subobject, *Field, &Layout);
1930
1931 if (ElementNo < E->getNumInits()) {
1932 if (!EvaluateConstantExpression(
1933 Result.getStructField((*Field)->getFieldIndex()),
1934 Info, Subobject, E->getInit(ElementNo++)))
1935 return false;
1936 } else {
1937 // Perform an implicit value-initialization for members beyond the end of
1938 // the initializer list.
1939 ImplicitValueInitExpr VIE(Field->getType());
1940 if (!EvaluateConstantExpression(
1941 Result.getStructField((*Field)->getFieldIndex()),
1942 Info, Subobject, &VIE))
1943 return false;
1944 }
1945 }
1946
1947 return true;
1948}
1949
1950bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
1951 const CXXConstructorDecl *FD = E->getConstructor();
1952 const FunctionDecl *Definition = 0;
1953 FD->getBody(Definition);
1954
1955 if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl())
1956 return false;
1957
1958 // FIXME: Elide the copy/move construction wherever we can.
1959 if (E->isElidable())
1960 if (const MaterializeTemporaryExpr *ME
1961 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
1962 return Visit(ME->GetTemporaryExpr());
1963
1964 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith59efe262011-11-11 04:05:33 +00001965 return HandleConstructorCall(This, Args, cast<CXXConstructorDecl>(Definition),
1966 Info, Result);
Richard Smith180f4792011-11-10 06:34:14 +00001967}
1968
1969static bool EvaluateRecord(const Expr *E, const LValue &This,
1970 APValue &Result, EvalInfo &Info) {
1971 assert(E->isRValue() && E->getType()->isRecordType() &&
1972 E->getType()->isLiteralType() &&
1973 "can't evaluate expression as a record rvalue");
1974 return RecordExprEvaluator(Info, This, Result).Visit(E);
1975}
1976
1977//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00001978// Vector Evaluation
1979//===----------------------------------------------------------------------===//
1980
1981namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001982 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00001983 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1984 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00001985 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Richard Smith07fc6572011-10-22 21:10:00 +00001987 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1988 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Richard Smith07fc6572011-10-22 21:10:00 +00001990 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1991 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1992 // FIXME: remove this APValue copy.
1993 Result = APValue(V.data(), V.size());
1994 return true;
1995 }
Richard Smith69c2c502011-11-04 05:33:44 +00001996 bool Success(const CCValue &V, const Expr *E) {
1997 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00001998 Result = V;
1999 return true;
2000 }
2001 bool Error(const Expr *E) { return false; }
2002 bool ValueInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Richard Smith07fc6572011-10-22 21:10:00 +00002004 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00002005 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00002006 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00002007 bool VisitInitListExpr(const InitListExpr *E);
2008 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002009 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00002010 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00002011 // shufflevector, ExtVectorElementExpr
2012 // (Note that these require implementing conversions
2013 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +00002014 };
2015} // end anonymous namespace
2016
2017static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002018 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00002019 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00002020}
2021
Richard Smith07fc6572011-10-22 21:10:00 +00002022bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2023 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00002024 QualType EltTy = VTy->getElementType();
2025 unsigned NElts = VTy->getNumElements();
2026 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Nate Begeman59b5da62009-01-18 03:20:47 +00002028 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00002029 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00002030
Eli Friedman46a52322011-03-25 00:43:55 +00002031 switch (E->getCastKind()) {
2032 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00002033 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00002034 if (SETy->isIntegerType()) {
2035 APSInt IntResult;
2036 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002037 return Error(E);
2038 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00002039 } else if (SETy->isRealFloatingType()) {
2040 APFloat F(0.0);
2041 if (!EvaluateFloat(SE, F, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002042 return Error(E);
2043 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00002044 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00002045 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00002046 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00002047
2048 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00002049 SmallVector<APValue, 4> Elts(NElts, Val);
2050 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00002051 }
Eli Friedman46a52322011-03-25 00:43:55 +00002052 case CK_BitCast: {
Richard Smith07fc6572011-10-22 21:10:00 +00002053 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedman46a52322011-03-25 00:43:55 +00002054 if (SETy->isVectorType())
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002055 return Visit(SE);
Nate Begemanc0b8b192009-07-01 07:50:47 +00002056
Eli Friedman46a52322011-03-25 00:43:55 +00002057 if (!SETy->isIntegerType())
Richard Smith07fc6572011-10-22 21:10:00 +00002058 return Error(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Eli Friedman46a52322011-03-25 00:43:55 +00002060 APSInt Init;
2061 if (!EvaluateInteger(SE, Init, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002062 return Error(E);
Nate Begemanc0b8b192009-07-01 07:50:47 +00002063
Eli Friedman46a52322011-03-25 00:43:55 +00002064 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
2065 "Vectors must be composed of ints or floats");
2066
Chris Lattner5f9e2722011-07-23 10:55:15 +00002067 SmallVector<APValue, 4> Elts;
Eli Friedman46a52322011-03-25 00:43:55 +00002068 for (unsigned i = 0; i != NElts; ++i) {
2069 APSInt Tmp = Init.extOrTrunc(EltWidth);
2070
2071 if (EltTy->isIntegerType())
2072 Elts.push_back(APValue(Tmp));
2073 else
2074 Elts.push_back(APValue(APFloat(Tmp)));
2075
2076 Init >>= EltWidth;
2077 }
Richard Smith07fc6572011-10-22 21:10:00 +00002078 return Success(Elts, E);
Nate Begemanc0b8b192009-07-01 07:50:47 +00002079 }
Eli Friedman46a52322011-03-25 00:43:55 +00002080 default:
Richard Smithc49bd112011-10-28 17:51:58 +00002081 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00002082 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002083}
2084
Richard Smith07fc6572011-10-22 21:10:00 +00002085bool
Nate Begeman59b5da62009-01-18 03:20:47 +00002086VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00002087 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00002088 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00002089 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Nate Begeman59b5da62009-01-18 03:20:47 +00002091 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002092 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00002093
John McCalla7d6c222010-06-11 17:54:15 +00002094 // If a vector is initialized with a single element, that value
2095 // becomes every element of the vector, not just the first.
2096 // This is the behavior described in the IBM AltiVec documentation.
2097 if (NumInits == 1) {
Richard Smith07fc6572011-10-22 21:10:00 +00002098
2099 // Handle the case where the vector is initialized by another
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +00002100 // vector (OpenCL 6.1.6).
2101 if (E->getInit(0)->getType()->isVectorType())
Richard Smith07fc6572011-10-22 21:10:00 +00002102 return Visit(E->getInit(0));
2103
John McCalla7d6c222010-06-11 17:54:15 +00002104 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +00002105 if (EltTy->isIntegerType()) {
2106 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +00002107 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002108 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00002109 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +00002110 } else {
2111 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +00002112 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002113 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00002114 InitValue = APValue(f);
2115 }
2116 for (unsigned i = 0; i < NumElements; i++) {
2117 Elements.push_back(InitValue);
2118 }
2119 } else {
2120 for (unsigned i = 0; i < NumElements; i++) {
2121 if (EltTy->isIntegerType()) {
2122 llvm::APSInt sInt(32);
2123 if (i < NumInits) {
2124 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002125 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00002126 } else {
2127 sInt = Info.Ctx.MakeIntValue(0, EltTy);
2128 }
2129 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +00002130 } else {
John McCalla7d6c222010-06-11 17:54:15 +00002131 llvm::APFloat f(0.0);
2132 if (i < NumInits) {
2133 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002134 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00002135 } else {
2136 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
2137 }
2138 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +00002139 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002140 }
2141 }
Richard Smith07fc6572011-10-22 21:10:00 +00002142 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00002143}
2144
Richard Smith07fc6572011-10-22 21:10:00 +00002145bool
2146VectorExprEvaluator::ValueInitialization(const Expr *E) {
2147 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00002148 QualType EltTy = VT->getElementType();
2149 APValue ZeroElement;
2150 if (EltTy->isIntegerType())
2151 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
2152 else
2153 ZeroElement =
2154 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
2155
Chris Lattner5f9e2722011-07-23 10:55:15 +00002156 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00002157 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002158}
2159
Richard Smith07fc6572011-10-22 21:10:00 +00002160bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00002161 VisitIgnoredValue(E->getSubExpr());
Richard Smith07fc6572011-10-22 21:10:00 +00002162 return ValueInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002163}
2164
Nate Begeman59b5da62009-01-18 03:20:47 +00002165//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00002166// Array Evaluation
2167//===----------------------------------------------------------------------===//
2168
2169namespace {
2170 class ArrayExprEvaluator
2171 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00002172 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00002173 APValue &Result;
2174 public:
2175
Richard Smith180f4792011-11-10 06:34:14 +00002176 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
2177 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00002178
2179 bool Success(const APValue &V, const Expr *E) {
2180 assert(V.isArray() && "Expected array type");
2181 Result = V;
2182 return true;
2183 }
2184 bool Error(const Expr *E) { return false; }
2185
Richard Smith180f4792011-11-10 06:34:14 +00002186 bool ValueInitialization(const Expr *E) {
2187 const ConstantArrayType *CAT =
2188 Info.Ctx.getAsConstantArrayType(E->getType());
2189 if (!CAT)
2190 return false;
2191
2192 Result = APValue(APValue::UninitArray(), 0,
2193 CAT->getSize().getZExtValue());
2194 if (!Result.hasArrayFiller()) return true;
2195
2196 // Value-initialize all elements.
2197 LValue Subobject = This;
2198 Subobject.Designator.addIndex(0);
2199 ImplicitValueInitExpr VIE(CAT->getElementType());
2200 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
2201 Subobject, &VIE);
2202 }
2203
2204 // FIXME: We also get CXXConstructExpr, in cases like:
2205 // struct S { constexpr S(); }; constexpr S s[10];
Richard Smithcc5d4f62011-11-07 09:22:26 +00002206 bool VisitInitListExpr(const InitListExpr *E);
2207 };
2208} // end anonymous namespace
2209
Richard Smith180f4792011-11-10 06:34:14 +00002210static bool EvaluateArray(const Expr *E, const LValue &This,
2211 APValue &Result, EvalInfo &Info) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00002212 assert(E->isRValue() && E->getType()->isArrayType() &&
2213 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00002214 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00002215}
2216
2217bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2218 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2219 if (!CAT)
2220 return false;
2221
2222 Result = APValue(APValue::UninitArray(), E->getNumInits(),
2223 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00002224 LValue Subobject = This;
2225 Subobject.Designator.addIndex(0);
2226 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00002227 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00002228 I != End; ++I, ++Index) {
2229 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
2230 Info, Subobject, cast<Expr>(*I)))
Richard Smithcc5d4f62011-11-07 09:22:26 +00002231 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002232 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
2233 return false;
2234 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00002235
2236 if (!Result.hasArrayFiller()) return true;
2237 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00002238 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
2239 // but sometimes does:
2240 // struct S { constexpr S() : p(&p) {} void *p; };
2241 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00002242 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith180f4792011-11-10 06:34:14 +00002243 Subobject, E->getArrayFiller());
Richard Smithcc5d4f62011-11-07 09:22:26 +00002244}
2245
2246//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002247// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002248//
2249// As a GNU extension, we support casting pointers to sufficiently-wide integer
2250// types and back in constant folding. Integer values are thus represented
2251// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002252//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002253
2254namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002255class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002256 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00002257 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00002258public:
Richard Smith47a1eed2011-10-29 20:57:55 +00002259 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002260 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002261
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00002262 bool Success(const llvm::APSInt &SI, const Expr *E) {
2263 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002264 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00002265 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002266 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00002267 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002268 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00002269 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002270 return true;
2271 }
2272
Daniel Dunbar131eb432009-02-19 09:06:44 +00002273 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002274 assert(E->getType()->isIntegralOrEnumerationType() &&
2275 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002276 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002277 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00002278 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00002279 Result.getInt().setIsUnsigned(
2280 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00002281 return true;
2282 }
2283
2284 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002285 assert(E->getType()->isIntegralOrEnumerationType() &&
2286 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00002287 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00002288 return true;
2289 }
2290
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00002291 bool Success(CharUnits Size, const Expr *E) {
2292 return Success(Size.getQuantity(), E);
2293 }
2294
2295
Anders Carlsson82206e22008-11-30 18:14:57 +00002296 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00002297 // Take the first error.
Richard Smith1e12c592011-10-16 21:26:27 +00002298 if (Info.EvalStatus.Diag == 0) {
2299 Info.EvalStatus.DiagLoc = L;
2300 Info.EvalStatus.Diag = D;
2301 Info.EvalStatus.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +00002302 }
Chris Lattner54176fd2008-07-12 00:14:42 +00002303 return false;
Chris Lattner7a767782008-07-11 19:24:49 +00002304 }
Mike Stump1eb44332009-09-09 15:08:12 +00002305
Richard Smith47a1eed2011-10-29 20:57:55 +00002306 bool Success(const CCValue &V, const Expr *E) {
Richard Smith342f1f82011-10-29 22:55:55 +00002307 if (V.isLValue()) {
2308 Result = V;
2309 return true;
2310 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002311 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00002312 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002313 bool Error(const Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00002314 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +00002315 }
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Richard Smithf10d9172011-10-11 21:43:33 +00002317 bool ValueInitialization(const Expr *E) { return Success(0, E); }
2318
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002319 //===--------------------------------------------------------------------===//
2320 // Visitor Methods
2321 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00002322
Chris Lattner4c4867e2008-07-12 00:38:25 +00002323 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00002324 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00002325 }
2326 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00002327 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00002328 }
Eli Friedman04309752009-11-24 05:28:59 +00002329
2330 bool CheckReferencedDecl(const Expr *E, const Decl *D);
2331 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002332 if (CheckReferencedDecl(E, E->getDecl()))
2333 return true;
2334
2335 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00002336 }
2337 bool VisitMemberExpr(const MemberExpr *E) {
2338 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00002339 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00002340 return true;
2341 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002342
2343 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00002344 }
2345
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002346 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00002347 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002348 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00002349 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00002350
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002351 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002352 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00002353
Anders Carlsson3068d112008-11-16 19:01:22 +00002354 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00002355 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00002356 }
Mike Stump1eb44332009-09-09 15:08:12 +00002357
Richard Smithf10d9172011-10-11 21:43:33 +00002358 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00002359 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002360 return ValueInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00002361 }
2362
Sebastian Redl64b45f72009-01-05 20:52:13 +00002363 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002364 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002365 }
2366
Francois Pichet6ad6f282010-12-07 00:08:36 +00002367 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
2368 return Success(E->getValue(), E);
2369 }
2370
John Wiegley21ff2e52011-04-28 00:16:57 +00002371 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2372 return Success(E->getValue(), E);
2373 }
2374
John Wiegley55262202011-04-25 06:54:41 +00002375 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2376 return Success(E->getValue(), E);
2377 }
2378
Eli Friedman722c7172009-02-28 03:59:05 +00002379 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00002380 bool VisitUnaryImag(const UnaryOperator *E);
2381
Sebastian Redl295995c2010-09-10 20:55:47 +00002382 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00002383 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00002384
Chris Lattnerfcee0012008-07-11 21:24:13 +00002385private:
Ken Dyck8b752f12010-01-27 17:10:57 +00002386 CharUnits GetAlignOfExpr(const Expr *E);
2387 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00002388 static QualType GetObjectType(const Expr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002389 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00002390 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002391};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002392} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002393
Richard Smithc49bd112011-10-28 17:51:58 +00002394/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
2395/// produce either the integer value or a pointer.
2396///
2397/// GCC has a heinous extension which folds casts between pointer types and
2398/// pointer-sized integral types. We support this by allowing the evaluation of
2399/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
2400/// Some simple arithmetic on such values is supported (they are treated much
2401/// like char*).
Richard Smith47a1eed2011-10-29 20:57:55 +00002402static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
2403 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002404 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002405 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002406}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002407
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002408static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002409 CCValue Val;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002410 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
2411 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002412 Result = Val.getInt();
2413 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00002414}
Anders Carlsson650c92f2008-07-08 15:34:11 +00002415
Eli Friedman04309752009-11-24 05:28:59 +00002416bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00002417 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00002418 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00002419 // Check for signedness/width mismatches between E type and ECD value.
2420 bool SameSign = (ECD->getInitVal().isSigned()
2421 == E->getType()->isSignedIntegerOrEnumerationType());
2422 bool SameWidth = (ECD->getInitVal().getBitWidth()
2423 == Info.Ctx.getIntWidth(E->getType()));
2424 if (SameSign && SameWidth)
2425 return Success(ECD->getInitVal(), E);
2426 else {
2427 // Get rid of mismatch (otherwise Success assertions will fail)
2428 // by computing a new value matching the type of E.
2429 llvm::APSInt Val = ECD->getInitVal();
2430 if (!SameSign)
2431 Val.setIsSigned(!ECD->getInitVal().isSigned());
2432 if (!SameWidth)
2433 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
2434 return Success(Val, E);
2435 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00002436 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002437 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00002438}
2439
Chris Lattnera4d55d82008-10-06 06:40:35 +00002440/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
2441/// as GCC.
2442static int EvaluateBuiltinClassifyType(const CallExpr *E) {
2443 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002444 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00002445 enum gcc_type_class {
2446 no_type_class = -1,
2447 void_type_class, integer_type_class, char_type_class,
2448 enumeral_type_class, boolean_type_class,
2449 pointer_type_class, reference_type_class, offset_type_class,
2450 real_type_class, complex_type_class,
2451 function_type_class, method_type_class,
2452 record_type_class, union_type_class,
2453 array_type_class, string_type_class,
2454 lang_type_class
2455 };
Mike Stump1eb44332009-09-09 15:08:12 +00002456
2457 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00002458 // ideal, however it is what gcc does.
2459 if (E->getNumArgs() == 0)
2460 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00002461
Chris Lattnera4d55d82008-10-06 06:40:35 +00002462 QualType ArgTy = E->getArg(0)->getType();
2463 if (ArgTy->isVoidType())
2464 return void_type_class;
2465 else if (ArgTy->isEnumeralType())
2466 return enumeral_type_class;
2467 else if (ArgTy->isBooleanType())
2468 return boolean_type_class;
2469 else if (ArgTy->isCharType())
2470 return string_type_class; // gcc doesn't appear to use char_type_class
2471 else if (ArgTy->isIntegerType())
2472 return integer_type_class;
2473 else if (ArgTy->isPointerType())
2474 return pointer_type_class;
2475 else if (ArgTy->isReferenceType())
2476 return reference_type_class;
2477 else if (ArgTy->isRealType())
2478 return real_type_class;
2479 else if (ArgTy->isComplexType())
2480 return complex_type_class;
2481 else if (ArgTy->isFunctionType())
2482 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00002483 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00002484 return record_type_class;
2485 else if (ArgTy->isUnionType())
2486 return union_type_class;
2487 else if (ArgTy->isArrayType())
2488 return array_type_class;
2489 else if (ArgTy->isUnionType())
2490 return union_type_class;
2491 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00002492 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00002493 return -1;
2494}
2495
John McCall42c8f872010-05-10 23:27:23 +00002496/// Retrieves the "underlying object type" of the given expression,
2497/// as used by __builtin_object_size.
2498QualType IntExprEvaluator::GetObjectType(const Expr *E) {
2499 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2500 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2501 return VD->getType();
2502 } else if (isa<CompoundLiteralExpr>(E)) {
2503 return E->getType();
2504 }
2505
2506 return QualType();
2507}
2508
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002509bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00002510 // TODO: Perhaps we should let LLVM lower this?
2511 LValue Base;
2512 if (!EvaluatePointer(E->getArg(0), Base, Info))
2513 return false;
2514
2515 // If we can prove the base is null, lower to zero now.
2516 const Expr *LVBase = Base.getLValueBase();
2517 if (!LVBase) return Success(0, E);
2518
2519 QualType T = GetObjectType(LVBase);
2520 if (T.isNull() ||
2521 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00002522 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00002523 T->isVariablyModifiedType() ||
2524 T->isDependentType())
2525 return false;
2526
2527 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
2528 CharUnits Offset = Base.getLValueOffset();
2529
2530 if (!Offset.isNegative() && Offset <= Size)
2531 Size -= Offset;
2532 else
2533 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00002534 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00002535}
2536
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002537bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002538 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00002539 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002540 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00002541
2542 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00002543 if (TryEvaluateBuiltinObjectSize(E))
2544 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00002545
Eric Christopherb2aaf512010-01-19 22:58:35 +00002546 // If evaluating the argument has side-effects we can't determine
2547 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002548 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002549 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00002550 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00002551 return Success(0, E);
2552 }
Mike Stumpc4c90452009-10-27 22:09:17 +00002553
Mike Stump64eda9e2009-10-26 18:35:08 +00002554 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2555 }
2556
Chris Lattner019f4e82008-10-06 05:28:25 +00002557 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00002558 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00002559
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002560 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00002561 // __builtin_constant_p always has one operand: it returns true if that
2562 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00002563 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00002564
2565 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002566 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002567 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00002568 return Success(Operand, E);
2569 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00002570
2571 case Builtin::BI__builtin_expect:
2572 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00002573
2574 case Builtin::BIstrlen:
2575 case Builtin::BI__builtin_strlen:
2576 // As an extension, we support strlen() and __builtin_strlen() as constant
2577 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002578 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00002579 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
2580 // The string literal may have embedded null characters. Find the first
2581 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002582 StringRef Str = S->getString();
2583 StringRef::size_type Pos = Str.find(0);
2584 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00002585 Str = Str.substr(0, Pos);
2586
2587 return Success(Str.size(), E);
2588 }
2589
2590 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00002591
2592 case Builtin::BI__atomic_is_lock_free: {
2593 APSInt SizeVal;
2594 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
2595 return false;
2596
2597 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
2598 // of two less than the maximum inline atomic width, we know it is
2599 // lock-free. If the size isn't a power of two, or greater than the
2600 // maximum alignment where we promote atomics, we know it is not lock-free
2601 // (at least not in the sense of atomic_is_lock_free). Otherwise,
2602 // the answer can only be determined at runtime; for example, 16-byte
2603 // atomics have lock-free implementations on some, but not all,
2604 // x86-64 processors.
2605
2606 // Check power-of-two.
2607 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
2608 if (!Size.isPowerOfTwo())
2609#if 0
2610 // FIXME: Suppress this folding until the ABI for the promotion width
2611 // settles.
2612 return Success(0, E);
2613#else
2614 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2615#endif
2616
2617#if 0
2618 // Check against promotion width.
2619 // FIXME: Suppress this folding until the ABI for the promotion width
2620 // settles.
2621 unsigned PromoteWidthBits =
2622 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
2623 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
2624 return Success(0, E);
2625#endif
2626
2627 // Check against inlining width.
2628 unsigned InlineWidthBits =
2629 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
2630 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
2631 return Success(1, E);
2632
2633 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2634 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002635 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00002636}
Anders Carlsson650c92f2008-07-08 15:34:11 +00002637
Richard Smith625b8072011-10-31 01:37:14 +00002638static bool HasSameBase(const LValue &A, const LValue &B) {
2639 if (!A.getLValueBase())
2640 return !B.getLValueBase();
2641 if (!B.getLValueBase())
2642 return false;
2643
2644 if (A.getLValueBase() != B.getLValueBase()) {
2645 const Decl *ADecl = GetLValueBaseDecl(A);
2646 if (!ADecl)
2647 return false;
2648 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00002649 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00002650 return false;
2651 }
2652
2653 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00002654 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00002655}
2656
Chris Lattnerb542afe2008-07-11 19:10:17 +00002657bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002658 if (E->isAssignmentOp())
2659 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
2660
John McCall2de56d12010-08-25 11:45:40 +00002661 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00002662 VisitIgnoredValue(E->getLHS());
2663 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00002664 }
2665
2666 if (E->isLogicalOp()) {
2667 // These need to be handled specially because the operands aren't
2668 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00002669 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00002670
Richard Smithc49bd112011-10-28 17:51:58 +00002671 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00002672 // We were able to evaluate the LHS, see if we can get away with not
2673 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00002674 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002675 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002676
Richard Smithc49bd112011-10-28 17:51:58 +00002677 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00002678 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00002679 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002680 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00002681 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002682 }
2683 } else {
Richard Smithc49bd112011-10-28 17:51:58 +00002684 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002685 // We can't evaluate the LHS; however, sometimes the result
2686 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00002687 if (rhsResult == (E->getOpcode() == BO_LOr) ||
2688 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00002689 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00002690 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00002691 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00002692
2693 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002694 }
2695 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00002696 }
Eli Friedmana6afa762008-11-13 06:09:17 +00002697
Eli Friedmana6afa762008-11-13 06:09:17 +00002698 return false;
2699 }
2700
Anders Carlsson286f85e2008-11-16 07:17:21 +00002701 QualType LHSTy = E->getLHS()->getType();
2702 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00002703
2704 if (LHSTy->isAnyComplexType()) {
2705 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00002706 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00002707
2708 if (!EvaluateComplex(E->getLHS(), LHS, Info))
2709 return false;
2710
2711 if (!EvaluateComplex(E->getRHS(), RHS, Info))
2712 return false;
2713
2714 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002715 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00002716 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00002717 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00002718 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
2719
John McCall2de56d12010-08-25 11:45:40 +00002720 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00002721 return Success((CR_r == APFloat::cmpEqual &&
2722 CR_i == APFloat::cmpEqual), E);
2723 else {
John McCall2de56d12010-08-25 11:45:40 +00002724 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00002725 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00002726 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00002727 CR_r == APFloat::cmpLessThan ||
2728 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00002729 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00002730 CR_i == APFloat::cmpLessThan ||
2731 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00002732 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00002733 } else {
John McCall2de56d12010-08-25 11:45:40 +00002734 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00002735 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
2736 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
2737 else {
John McCall2de56d12010-08-25 11:45:40 +00002738 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00002739 "Invalid compex comparison.");
2740 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
2741 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
2742 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00002743 }
2744 }
Mike Stump1eb44332009-09-09 15:08:12 +00002745
Anders Carlsson286f85e2008-11-16 07:17:21 +00002746 if (LHSTy->isRealFloatingType() &&
2747 RHSTy->isRealFloatingType()) {
2748 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00002749
Anders Carlsson286f85e2008-11-16 07:17:21 +00002750 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2751 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002752
Anders Carlsson286f85e2008-11-16 07:17:21 +00002753 if (!EvaluateFloat(E->getLHS(), LHS, Info))
2754 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002755
Anders Carlsson286f85e2008-11-16 07:17:21 +00002756 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00002757
Anders Carlsson286f85e2008-11-16 07:17:21 +00002758 switch (E->getOpcode()) {
2759 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002760 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00002761 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00002762 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00002763 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00002764 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00002765 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00002766 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00002767 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00002768 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00002769 E);
John McCall2de56d12010-08-25 11:45:40 +00002770 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00002771 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00002772 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00002773 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00002774 || CR == APFloat::cmpLessThan
2775 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00002776 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00002777 }
Mike Stump1eb44332009-09-09 15:08:12 +00002778
Eli Friedmanad02d7d2009-04-28 19:17:36 +00002779 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00002780 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00002781 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00002782 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
2783 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00002784
John McCallefdb83e2010-05-07 21:00:08 +00002785 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00002786 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
2787 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00002788
Richard Smith625b8072011-10-31 01:37:14 +00002789 // Reject differing bases from the normal codepath; we special-case
2790 // comparisons to null.
2791 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith9e36b532011-10-31 05:11:32 +00002792 // Inequalities and subtractions between unrelated pointers have
2793 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00002794 if (!E->isEqualityOp())
2795 return false;
Eli Friedmanffbda402011-10-31 22:28:05 +00002796 // A constant address may compare equal to the address of a symbol.
2797 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00002798 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00002799 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
2800 (!RHSValue.Base && !RHSValue.Offset.isZero()))
2801 return false;
Richard Smith9e36b532011-10-31 05:11:32 +00002802 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00002803 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00002804 // distinct. However, we do know that the address of a literal will be
2805 // non-null.
2806 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
2807 LHSValue.Base && RHSValue.Base)
Eli Friedman5bc86102009-06-14 02:17:33 +00002808 return false;
Richard Smith9e36b532011-10-31 05:11:32 +00002809 // We can't tell whether weak symbols will end up pointing to the same
2810 // object.
2811 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Eli Friedman5bc86102009-06-14 02:17:33 +00002812 return false;
Richard Smith9e36b532011-10-31 05:11:32 +00002813 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00002814 // (Note that clang defaults to -fmerge-all-constants, which can
2815 // lead to inconsistent results for comparisons involving the address
2816 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00002817 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00002818 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00002819
Richard Smithcc5d4f62011-11-07 09:22:26 +00002820 // FIXME: Implement the C++11 restrictions:
2821 // - Pointer subtractions must be on elements of the same array.
2822 // - Pointer comparisons must be between members with the same access.
2823
John McCall2de56d12010-08-25 11:45:40 +00002824 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00002825 QualType Type = E->getLHS()->getType();
2826 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00002827
Richard Smith180f4792011-11-10 06:34:14 +00002828 CharUnits ElementSize;
2829 if (!HandleSizeof(Info, ElementType, ElementSize))
2830 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00002831
Richard Smith180f4792011-11-10 06:34:14 +00002832 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00002833 RHSValue.getLValueOffset();
2834 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00002835 }
Richard Smith625b8072011-10-31 01:37:14 +00002836
2837 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
2838 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
2839 switch (E->getOpcode()) {
2840 default: llvm_unreachable("missing comparison operator");
2841 case BO_LT: return Success(LHSOffset < RHSOffset, E);
2842 case BO_GT: return Success(LHSOffset > RHSOffset, E);
2843 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
2844 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
2845 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
2846 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00002847 }
Anders Carlsson3068d112008-11-16 19:01:22 +00002848 }
2849 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002850 if (!LHSTy->isIntegralOrEnumerationType() ||
2851 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00002852 // We can't continue from here for non-integral types, and they
2853 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00002854 return false;
2855 }
2856
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002857 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00002858 CCValue LHSVal;
Richard Smithc49bd112011-10-28 17:51:58 +00002859 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner54176fd2008-07-12 00:14:42 +00002860 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00002861
Richard Smithc49bd112011-10-28 17:51:58 +00002862 if (!Visit(E->getRHS()))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002863 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00002864 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00002865
2866 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00002867 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00002868 CharUnits AdditionalOffset = CharUnits::fromQuantity(
2869 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00002870 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00002871 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00002872 else
Richard Smith47a1eed2011-10-29 20:57:55 +00002873 LHSVal.getLValueOffset() -= AdditionalOffset;
2874 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00002875 return true;
2876 }
2877
2878 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00002879 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00002880 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002881 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
2882 LHSVal.getInt().getZExtValue());
2883 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00002884 return true;
2885 }
2886
2887 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00002888 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00002889 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00002890
Richard Smithc49bd112011-10-28 17:51:58 +00002891 APSInt &LHS = LHSVal.getInt();
2892 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00002893
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002894 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00002895 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00002896 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002897 case BO_Mul: return Success(LHS * RHS, E);
2898 case BO_Add: return Success(LHS + RHS, E);
2899 case BO_Sub: return Success(LHS - RHS, E);
2900 case BO_And: return Success(LHS & RHS, E);
2901 case BO_Xor: return Success(LHS ^ RHS, E);
2902 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00002903 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00002904 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00002905 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002906 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00002907 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00002908 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00002909 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002910 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00002911 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00002912 // During constant-folding, a negative shift is an opposite shift.
2913 if (RHS.isSigned() && RHS.isNegative()) {
2914 RHS = -RHS;
2915 goto shift_right;
2916 }
2917
2918 shift_left:
2919 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00002920 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2921 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002922 }
John McCall2de56d12010-08-25 11:45:40 +00002923 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00002924 // During constant-folding, a negative shift is an opposite shift.
2925 if (RHS.isSigned() && RHS.isNegative()) {
2926 RHS = -RHS;
2927 goto shift_left;
2928 }
2929
2930 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00002931 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00002932 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2933 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002934 }
Mike Stump1eb44332009-09-09 15:08:12 +00002935
Richard Smithc49bd112011-10-28 17:51:58 +00002936 case BO_LT: return Success(LHS < RHS, E);
2937 case BO_GT: return Success(LHS > RHS, E);
2938 case BO_LE: return Success(LHS <= RHS, E);
2939 case BO_GE: return Success(LHS >= RHS, E);
2940 case BO_EQ: return Success(LHS == RHS, E);
2941 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00002942 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002943}
2944
Ken Dyck8b752f12010-01-27 17:10:57 +00002945CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00002946 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2947 // the result is the size of the referenced type."
2948 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2949 // result shall be the alignment of the referenced type."
2950 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2951 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00002952
2953 // __alignof is defined to return the preferred alignment.
2954 return Info.Ctx.toCharUnitsFromBits(
2955 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00002956}
2957
Ken Dyck8b752f12010-01-27 17:10:57 +00002958CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00002959 E = E->IgnoreParens();
2960
2961 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00002962 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00002963 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00002964 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2965 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00002966
Chris Lattneraf707ab2009-01-24 21:53:27 +00002967 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00002968 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2969 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00002970
Chris Lattnere9feb472009-01-24 21:09:06 +00002971 return GetAlignOfType(E->getType());
2972}
2973
2974
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002975/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2976/// a result as the expression's type.
2977bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2978 const UnaryExprOrTypeTraitExpr *E) {
2979 switch(E->getKind()) {
2980 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00002981 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00002982 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00002983 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00002984 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00002985 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00002986
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002987 case UETT_VecStep: {
2988 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00002989
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002990 if (Ty->isVectorType()) {
2991 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00002992
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002993 // The vec_step built-in functions that take a 3-component
2994 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2995 if (n == 3)
2996 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00002997
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002998 return Success(n, E);
2999 } else
3000 return Success(1, E);
3001 }
3002
3003 case UETT_SizeOf: {
3004 QualType SrcTy = E->getTypeOfArgument();
3005 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3006 // the result is the size of the referenced type."
3007 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3008 // result shall be the alignment of the referenced type."
3009 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
3010 SrcTy = Ref->getPointeeType();
3011
Richard Smith180f4792011-11-10 06:34:14 +00003012 CharUnits Sizeof;
3013 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003014 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003015 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003016 }
3017 }
3018
3019 llvm_unreachable("unknown expr/type trait");
3020 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00003021}
3022
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003023bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003024 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003025 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003026 if (n == 0)
3027 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003028 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003029 for (unsigned i = 0; i != n; ++i) {
3030 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
3031 switch (ON.getKind()) {
3032 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003033 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003034 APSInt IdxResult;
3035 if (!EvaluateInteger(Idx, IdxResult, Info))
3036 return false;
3037 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
3038 if (!AT)
3039 return false;
3040 CurrentType = AT->getElementType();
3041 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
3042 Result += IdxResult.getSExtValue() * ElementSize;
3043 break;
3044 }
3045
3046 case OffsetOfExpr::OffsetOfNode::Field: {
3047 FieldDecl *MemberDecl = ON.getField();
3048 const RecordType *RT = CurrentType->getAs<RecordType>();
3049 if (!RT)
3050 return false;
3051 RecordDecl *RD = RT->getDecl();
3052 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00003053 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003054 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00003055 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003056 CurrentType = MemberDecl->getType().getNonReferenceType();
3057 break;
3058 }
3059
3060 case OffsetOfExpr::OffsetOfNode::Identifier:
3061 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003062 return false;
3063
3064 case OffsetOfExpr::OffsetOfNode::Base: {
3065 CXXBaseSpecifier *BaseSpec = ON.getBase();
3066 if (BaseSpec->isVirtual())
3067 return false;
3068
3069 // Find the layout of the class whose base we are looking into.
3070 const RecordType *RT = CurrentType->getAs<RecordType>();
3071 if (!RT)
3072 return false;
3073 RecordDecl *RD = RT->getDecl();
3074 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
3075
3076 // Find the base class itself.
3077 CurrentType = BaseSpec->getType();
3078 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
3079 if (!BaseRT)
3080 return false;
3081
3082 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00003083 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003084 break;
3085 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003086 }
3087 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003088 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003089}
3090
Chris Lattnerb542afe2008-07-11 19:10:17 +00003091bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003092 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00003093 // LNot's operand isn't necessarily an integer, so we handle it specially.
3094 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00003095 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00003096 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003097 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003098 }
3099
Daniel Dunbar4fff4812009-02-21 18:14:20 +00003100 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003101 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00003102 return false;
3103
Richard Smithc49bd112011-10-28 17:51:58 +00003104 // Get the operand value.
Richard Smith47a1eed2011-10-29 20:57:55 +00003105 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00003106 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00003107 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003108
Chris Lattner75a48812008-07-11 22:15:16 +00003109 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003110 default:
Chris Lattner75a48812008-07-11 22:15:16 +00003111 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
3112 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00003113 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00003114 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00003115 // FIXME: Should extension allow i-c-e extension expressions in its scope?
3116 // If so, we could clear the diagnostic ID.
Richard Smithc49bd112011-10-28 17:51:58 +00003117 return Success(Val, E);
John McCall2de56d12010-08-25 11:45:40 +00003118 case UO_Plus:
Richard Smithc49bd112011-10-28 17:51:58 +00003119 // The result is just the value.
3120 return Success(Val, E);
John McCall2de56d12010-08-25 11:45:40 +00003121 case UO_Minus:
Richard Smithc49bd112011-10-28 17:51:58 +00003122 if (!Val.isInt()) return false;
3123 return Success(-Val.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00003124 case UO_Not:
Richard Smithc49bd112011-10-28 17:51:58 +00003125 if (!Val.isInt()) return false;
3126 return Success(~Val.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003127 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003128}
Mike Stump1eb44332009-09-09 15:08:12 +00003129
Chris Lattner732b2232008-07-12 01:15:53 +00003130/// HandleCast - This is used to evaluate implicit or explicit casts where the
3131/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003132bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
3133 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00003134 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00003135 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00003136
Eli Friedman46a52322011-03-25 00:43:55 +00003137 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00003138 case CK_BaseToDerived:
3139 case CK_DerivedToBase:
3140 case CK_UncheckedDerivedToBase:
3141 case CK_Dynamic:
3142 case CK_ToUnion:
3143 case CK_ArrayToPointerDecay:
3144 case CK_FunctionToPointerDecay:
3145 case CK_NullToPointer:
3146 case CK_NullToMemberPointer:
3147 case CK_BaseToDerivedMemberPointer:
3148 case CK_DerivedToBaseMemberPointer:
3149 case CK_ConstructorConversion:
3150 case CK_IntegralToPointer:
3151 case CK_ToVoid:
3152 case CK_VectorSplat:
3153 case CK_IntegralToFloating:
3154 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003155 case CK_CPointerToObjCPointerCast:
3156 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00003157 case CK_AnyPointerToBlockPointerCast:
3158 case CK_ObjCObjectLValueCast:
3159 case CK_FloatingRealToComplex:
3160 case CK_FloatingComplexToReal:
3161 case CK_FloatingComplexCast:
3162 case CK_FloatingComplexToIntegralComplex:
3163 case CK_IntegralRealToComplex:
3164 case CK_IntegralComplexCast:
3165 case CK_IntegralComplexToFloatingComplex:
3166 llvm_unreachable("invalid cast kind for integral value");
3167
Eli Friedmane50c2972011-03-25 19:07:11 +00003168 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00003169 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00003170 case CK_LValueBitCast:
3171 case CK_UserDefinedConversion:
John McCall33e56f32011-09-10 06:18:15 +00003172 case CK_ARCProduceObject:
3173 case CK_ARCConsumeObject:
3174 case CK_ARCReclaimReturnedObject:
3175 case CK_ARCExtendBlockObject:
Eli Friedman46a52322011-03-25 00:43:55 +00003176 return false;
3177
3178 case CK_LValueToRValue:
3179 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00003180 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003181
3182 case CK_MemberPointerToBoolean:
3183 case CK_PointerToBoolean:
3184 case CK_IntegralToBoolean:
3185 case CK_FloatingToBoolean:
3186 case CK_FloatingComplexToBoolean:
3187 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00003188 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00003189 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00003190 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003191 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003192 }
3193
Eli Friedman46a52322011-03-25 00:43:55 +00003194 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00003195 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00003196 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00003197
Eli Friedmanbe265702009-02-20 01:15:07 +00003198 if (!Result.isInt()) {
3199 // Only allow casts of lvalues if they are lossless.
3200 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
3201 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003202
Daniel Dunbardd211642009-02-19 22:24:01 +00003203 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003204 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00003205 }
Mike Stump1eb44332009-09-09 15:08:12 +00003206
Eli Friedman46a52322011-03-25 00:43:55 +00003207 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00003208 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00003209 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00003210 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00003211
Daniel Dunbardd211642009-02-19 22:24:01 +00003212 if (LV.getLValueBase()) {
3213 // Only allow based lvalue casts if they are lossless.
3214 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
3215 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00003216
John McCallefdb83e2010-05-07 21:00:08 +00003217 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00003218 return true;
3219 }
3220
Ken Dycka7305832010-01-15 12:37:54 +00003221 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
3222 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00003223 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00003224 }
Eli Friedman4efaa272008-11-12 09:44:48 +00003225
Eli Friedman46a52322011-03-25 00:43:55 +00003226 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00003227 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00003228 if (!EvaluateComplex(SubExpr, C, Info))
3229 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00003230 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00003231 }
Eli Friedman2217c872009-02-22 11:46:18 +00003232
Eli Friedman46a52322011-03-25 00:43:55 +00003233 case CK_FloatingToIntegral: {
3234 APFloat F(0.0);
3235 if (!EvaluateFloat(SubExpr, F, Info))
3236 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00003237
Eli Friedman46a52322011-03-25 00:43:55 +00003238 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
3239 }
3240 }
Mike Stump1eb44332009-09-09 15:08:12 +00003241
Eli Friedman46a52322011-03-25 00:43:55 +00003242 llvm_unreachable("unknown cast resulting in integral value");
3243 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003244}
Anders Carlsson2bad1682008-07-08 14:30:00 +00003245
Eli Friedman722c7172009-02-28 03:59:05 +00003246bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3247 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00003248 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00003249 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
3250 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
3251 return Success(LV.getComplexIntReal(), E);
3252 }
3253
3254 return Visit(E->getSubExpr());
3255}
3256
Eli Friedman664a1042009-02-27 04:45:43 +00003257bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00003258 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00003259 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00003260 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
3261 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
3262 return Success(LV.getComplexIntImag(), E);
3263 }
3264
Richard Smith8327fad2011-10-24 18:44:57 +00003265 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00003266 return Success(0, E);
3267}
3268
Douglas Gregoree8aff02011-01-04 17:33:58 +00003269bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
3270 return Success(E->getPackLength(), E);
3271}
3272
Sebastian Redl295995c2010-09-10 20:55:47 +00003273bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
3274 return Success(E->getValue(), E);
3275}
3276
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003277//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003278// Float Evaluation
3279//===----------------------------------------------------------------------===//
3280
3281namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003282class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003283 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003284 APFloat &Result;
3285public:
3286 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003287 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003288
Richard Smith47a1eed2011-10-29 20:57:55 +00003289 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003290 Result = V.getFloat();
3291 return true;
3292 }
3293 bool Error(const Stmt *S) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003294 return false;
3295 }
3296
Richard Smithf10d9172011-10-11 21:43:33 +00003297 bool ValueInitialization(const Expr *E) {
3298 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
3299 return true;
3300 }
3301
Chris Lattner019f4e82008-10-06 05:28:25 +00003302 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003303
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003304 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003305 bool VisitBinaryOperator(const BinaryOperator *E);
3306 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003307 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00003308
John McCallabd3a852010-05-07 22:08:54 +00003309 bool VisitUnaryReal(const UnaryOperator *E);
3310 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003311
John McCallabd3a852010-05-07 22:08:54 +00003312 // FIXME: Missing: array subscript of vector, member of vector,
3313 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003314};
3315} // end anonymous namespace
3316
3317static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003318 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003319 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003320}
3321
Jay Foad4ba2a172011-01-12 09:06:06 +00003322static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00003323 QualType ResultTy,
3324 const Expr *Arg,
3325 bool SNaN,
3326 llvm::APFloat &Result) {
3327 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
3328 if (!S) return false;
3329
3330 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
3331
3332 llvm::APInt fill;
3333
3334 // Treat empty strings as if they were zero.
3335 if (S->getString().empty())
3336 fill = llvm::APInt(32, 0);
3337 else if (S->getString().getAsInteger(0, fill))
3338 return false;
3339
3340 if (SNaN)
3341 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
3342 else
3343 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
3344 return true;
3345}
3346
Chris Lattner019f4e82008-10-06 05:28:25 +00003347bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003348 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003349 default:
3350 return ExprEvaluatorBaseTy::VisitCallExpr(E);
3351
Chris Lattner019f4e82008-10-06 05:28:25 +00003352 case Builtin::BI__builtin_huge_val:
3353 case Builtin::BI__builtin_huge_valf:
3354 case Builtin::BI__builtin_huge_vall:
3355 case Builtin::BI__builtin_inf:
3356 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00003357 case Builtin::BI__builtin_infl: {
3358 const llvm::fltSemantics &Sem =
3359 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00003360 Result = llvm::APFloat::getInf(Sem);
3361 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00003362 }
Mike Stump1eb44332009-09-09 15:08:12 +00003363
John McCalldb7b72a2010-02-28 13:00:19 +00003364 case Builtin::BI__builtin_nans:
3365 case Builtin::BI__builtin_nansf:
3366 case Builtin::BI__builtin_nansl:
3367 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
3368 true, Result);
3369
Chris Lattner9e621712008-10-06 06:31:58 +00003370 case Builtin::BI__builtin_nan:
3371 case Builtin::BI__builtin_nanf:
3372 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00003373 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00003374 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00003375 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
3376 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003377
3378 case Builtin::BI__builtin_fabs:
3379 case Builtin::BI__builtin_fabsf:
3380 case Builtin::BI__builtin_fabsl:
3381 if (!EvaluateFloat(E->getArg(0), Result, Info))
3382 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003383
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003384 if (Result.isNegative())
3385 Result.changeSign();
3386 return true;
3387
Mike Stump1eb44332009-09-09 15:08:12 +00003388 case Builtin::BI__builtin_copysign:
3389 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003390 case Builtin::BI__builtin_copysignl: {
3391 APFloat RHS(0.);
3392 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
3393 !EvaluateFloat(E->getArg(1), RHS, Info))
3394 return false;
3395 Result.copySign(RHS);
3396 return true;
3397 }
Chris Lattner019f4e82008-10-06 05:28:25 +00003398 }
3399}
3400
John McCallabd3a852010-05-07 22:08:54 +00003401bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00003402 if (E->getSubExpr()->getType()->isAnyComplexType()) {
3403 ComplexValue CV;
3404 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
3405 return false;
3406 Result = CV.FloatReal;
3407 return true;
3408 }
3409
3410 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00003411}
3412
3413bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00003414 if (E->getSubExpr()->getType()->isAnyComplexType()) {
3415 ComplexValue CV;
3416 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
3417 return false;
3418 Result = CV.FloatImag;
3419 return true;
3420 }
3421
Richard Smith8327fad2011-10-24 18:44:57 +00003422 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00003423 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
3424 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00003425 return true;
3426}
3427
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003428bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003429 switch (E->getOpcode()) {
3430 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00003431 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00003432 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00003433 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00003434 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
3435 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003436 Result.changeSign();
3437 return true;
3438 }
3439}
Chris Lattner019f4e82008-10-06 05:28:25 +00003440
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003441bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003442 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00003443 VisitIgnoredValue(E->getLHS());
3444 return Visit(E->getRHS());
Eli Friedman7f92f032009-11-16 04:25:37 +00003445 }
3446
Richard Smithee591a92011-10-28 23:26:52 +00003447 // We can't evaluate pointer-to-member operations or assignments.
3448 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlsson96e93662010-10-31 01:21:47 +00003449 return false;
3450
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003451 // FIXME: Diagnostics? I really don't understand how the warnings
3452 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003453 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003454 if (!EvaluateFloat(E->getLHS(), Result, Info))
3455 return false;
3456 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3457 return false;
3458
3459 switch (E->getOpcode()) {
3460 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00003461 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003462 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
3463 return true;
John McCall2de56d12010-08-25 11:45:40 +00003464 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003465 Result.add(RHS, APFloat::rmNearestTiesToEven);
3466 return true;
John McCall2de56d12010-08-25 11:45:40 +00003467 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003468 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
3469 return true;
John McCall2de56d12010-08-25 11:45:40 +00003470 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003471 Result.divide(RHS, APFloat::rmNearestTiesToEven);
3472 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003473 }
3474}
3475
3476bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
3477 Result = E->getValue();
3478 return true;
3479}
3480
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003481bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
3482 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00003483
Eli Friedman2a523ee2011-03-25 00:54:52 +00003484 switch (E->getCastKind()) {
3485 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003486 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00003487
3488 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00003489 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003490 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00003491 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003492 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00003493 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00003494 return true;
3495 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00003496
3497 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00003498 if (!Visit(SubExpr))
3499 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00003500 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
3501 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00003502 return true;
3503 }
John McCallf3ea8cf2010-11-14 08:17:51 +00003504
Eli Friedman2a523ee2011-03-25 00:54:52 +00003505 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00003506 ComplexValue V;
3507 if (!EvaluateComplex(SubExpr, V, Info))
3508 return false;
3509 Result = V.getComplexFloatReal();
3510 return true;
3511 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00003512 }
Eli Friedman4efaa272008-11-12 09:44:48 +00003513
3514 return false;
3515}
3516
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003517//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003518// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00003519//===----------------------------------------------------------------------===//
3520
3521namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003522class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003523 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00003524 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00003525
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00003526public:
John McCallf4cf1a12010-05-07 17:22:02 +00003527 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003528 : ExprEvaluatorBaseTy(info), Result(Result) {}
3529
Richard Smith47a1eed2011-10-29 20:57:55 +00003530 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003531 Result.setFrom(V);
3532 return true;
3533 }
3534 bool Error(const Expr *E) {
3535 return false;
3536 }
Mike Stump1eb44332009-09-09 15:08:12 +00003537
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00003538 //===--------------------------------------------------------------------===//
3539 // Visitor Methods
3540 //===--------------------------------------------------------------------===//
3541
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003542 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003543
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003544 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003545
John McCallf4cf1a12010-05-07 17:22:02 +00003546 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00003547 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003548 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00003549};
3550} // end anonymous namespace
3551
John McCallf4cf1a12010-05-07 17:22:02 +00003552static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
3553 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003554 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003555 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00003556}
3557
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003558bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
3559 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003560
3561 if (SubExpr->getType()->isRealFloatingType()) {
3562 Result.makeComplexFloat();
3563 APFloat &Imag = Result.FloatImag;
3564 if (!EvaluateFloat(SubExpr, Imag, Info))
3565 return false;
3566
3567 Result.FloatReal = APFloat(Imag.getSemantics());
3568 return true;
3569 } else {
3570 assert(SubExpr->getType()->isIntegerType() &&
3571 "Unexpected imaginary literal.");
3572
3573 Result.makeComplexInt();
3574 APSInt &Imag = Result.IntImag;
3575 if (!EvaluateInteger(SubExpr, Imag, Info))
3576 return false;
3577
3578 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
3579 return true;
3580 }
3581}
3582
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003583bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003584
John McCall8786da72010-12-14 17:51:41 +00003585 switch (E->getCastKind()) {
3586 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00003587 case CK_BaseToDerived:
3588 case CK_DerivedToBase:
3589 case CK_UncheckedDerivedToBase:
3590 case CK_Dynamic:
3591 case CK_ToUnion:
3592 case CK_ArrayToPointerDecay:
3593 case CK_FunctionToPointerDecay:
3594 case CK_NullToPointer:
3595 case CK_NullToMemberPointer:
3596 case CK_BaseToDerivedMemberPointer:
3597 case CK_DerivedToBaseMemberPointer:
3598 case CK_MemberPointerToBoolean:
3599 case CK_ConstructorConversion:
3600 case CK_IntegralToPointer:
3601 case CK_PointerToIntegral:
3602 case CK_PointerToBoolean:
3603 case CK_ToVoid:
3604 case CK_VectorSplat:
3605 case CK_IntegralCast:
3606 case CK_IntegralToBoolean:
3607 case CK_IntegralToFloating:
3608 case CK_FloatingToIntegral:
3609 case CK_FloatingToBoolean:
3610 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003611 case CK_CPointerToObjCPointerCast:
3612 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00003613 case CK_AnyPointerToBlockPointerCast:
3614 case CK_ObjCObjectLValueCast:
3615 case CK_FloatingComplexToReal:
3616 case CK_FloatingComplexToBoolean:
3617 case CK_IntegralComplexToReal:
3618 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00003619 case CK_ARCProduceObject:
3620 case CK_ARCConsumeObject:
3621 case CK_ARCReclaimReturnedObject:
3622 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00003623 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00003624
John McCall8786da72010-12-14 17:51:41 +00003625 case CK_LValueToRValue:
3626 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00003627 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00003628
3629 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00003630 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00003631 case CK_UserDefinedConversion:
3632 return false;
3633
3634 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003635 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00003636 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003637 return false;
3638
John McCall8786da72010-12-14 17:51:41 +00003639 Result.makeComplexFloat();
3640 Result.FloatImag = APFloat(Real.getSemantics());
3641 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003642 }
3643
John McCall8786da72010-12-14 17:51:41 +00003644 case CK_FloatingComplexCast: {
3645 if (!Visit(E->getSubExpr()))
3646 return false;
3647
3648 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3649 QualType From
3650 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3651
3652 Result.FloatReal
3653 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
3654 Result.FloatImag
3655 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
3656 return true;
3657 }
3658
3659 case CK_FloatingComplexToIntegralComplex: {
3660 if (!Visit(E->getSubExpr()))
3661 return false;
3662
3663 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3664 QualType From
3665 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3666 Result.makeComplexInt();
3667 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
3668 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
3669 return true;
3670 }
3671
3672 case CK_IntegralRealToComplex: {
3673 APSInt &Real = Result.IntReal;
3674 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
3675 return false;
3676
3677 Result.makeComplexInt();
3678 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
3679 return true;
3680 }
3681
3682 case CK_IntegralComplexCast: {
3683 if (!Visit(E->getSubExpr()))
3684 return false;
3685
3686 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3687 QualType From
3688 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3689
3690 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
3691 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
3692 return true;
3693 }
3694
3695 case CK_IntegralComplexToFloatingComplex: {
3696 if (!Visit(E->getSubExpr()))
3697 return false;
3698
3699 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3700 QualType From
3701 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3702 Result.makeComplexFloat();
3703 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
3704 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
3705 return true;
3706 }
3707 }
3708
3709 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003710 return false;
3711}
3712
John McCallf4cf1a12010-05-07 17:22:02 +00003713bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00003714 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00003715 VisitIgnoredValue(E->getLHS());
3716 return Visit(E->getRHS());
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00003717 }
John McCallf4cf1a12010-05-07 17:22:02 +00003718 if (!Visit(E->getLHS()))
3719 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003720
John McCallf4cf1a12010-05-07 17:22:02 +00003721 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003722 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00003723 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003724
Daniel Dunbar3f279872009-01-29 01:32:56 +00003725 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
3726 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00003727 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00003728 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00003729 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003730 if (Result.isComplexFloat()) {
3731 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
3732 APFloat::rmNearestTiesToEven);
3733 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
3734 APFloat::rmNearestTiesToEven);
3735 } else {
3736 Result.getComplexIntReal() += RHS.getComplexIntReal();
3737 Result.getComplexIntImag() += RHS.getComplexIntImag();
3738 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00003739 break;
John McCall2de56d12010-08-25 11:45:40 +00003740 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003741 if (Result.isComplexFloat()) {
3742 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
3743 APFloat::rmNearestTiesToEven);
3744 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
3745 APFloat::rmNearestTiesToEven);
3746 } else {
3747 Result.getComplexIntReal() -= RHS.getComplexIntReal();
3748 Result.getComplexIntImag() -= RHS.getComplexIntImag();
3749 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00003750 break;
John McCall2de56d12010-08-25 11:45:40 +00003751 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00003752 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00003753 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00003754 APFloat &LHS_r = LHS.getComplexFloatReal();
3755 APFloat &LHS_i = LHS.getComplexFloatImag();
3756 APFloat &RHS_r = RHS.getComplexFloatReal();
3757 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00003758
Daniel Dunbar3f279872009-01-29 01:32:56 +00003759 APFloat Tmp = LHS_r;
3760 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3761 Result.getComplexFloatReal() = Tmp;
3762 Tmp = LHS_i;
3763 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3764 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
3765
3766 Tmp = LHS_r;
3767 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3768 Result.getComplexFloatImag() = Tmp;
3769 Tmp = LHS_i;
3770 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3771 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
3772 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00003773 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00003774 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00003775 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
3776 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00003777 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00003778 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
3779 LHS.getComplexIntImag() * RHS.getComplexIntReal());
3780 }
3781 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00003782 case BO_Div:
3783 if (Result.isComplexFloat()) {
3784 ComplexValue LHS = Result;
3785 APFloat &LHS_r = LHS.getComplexFloatReal();
3786 APFloat &LHS_i = LHS.getComplexFloatImag();
3787 APFloat &RHS_r = RHS.getComplexFloatReal();
3788 APFloat &RHS_i = RHS.getComplexFloatImag();
3789 APFloat &Res_r = Result.getComplexFloatReal();
3790 APFloat &Res_i = Result.getComplexFloatImag();
3791
3792 APFloat Den = RHS_r;
3793 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3794 APFloat Tmp = RHS_i;
3795 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3796 Den.add(Tmp, APFloat::rmNearestTiesToEven);
3797
3798 Res_r = LHS_r;
3799 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3800 Tmp = LHS_i;
3801 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3802 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
3803 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
3804
3805 Res_i = LHS_i;
3806 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3807 Tmp = LHS_r;
3808 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3809 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
3810 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
3811 } else {
3812 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
3813 // FIXME: what about diagnostics?
3814 return false;
3815 }
3816 ComplexValue LHS = Result;
3817 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
3818 RHS.getComplexIntImag() * RHS.getComplexIntImag();
3819 Result.getComplexIntReal() =
3820 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
3821 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
3822 Result.getComplexIntImag() =
3823 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
3824 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
3825 }
3826 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00003827 }
3828
John McCallf4cf1a12010-05-07 17:22:02 +00003829 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00003830}
3831
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00003832bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
3833 // Get the operand value into 'Result'.
3834 if (!Visit(E->getSubExpr()))
3835 return false;
3836
3837 switch (E->getOpcode()) {
3838 default:
3839 // FIXME: what about diagnostics?
3840 return false;
3841 case UO_Extension:
3842 return true;
3843 case UO_Plus:
3844 // The result is always just the subexpr.
3845 return true;
3846 case UO_Minus:
3847 if (Result.isComplexFloat()) {
3848 Result.getComplexFloatReal().changeSign();
3849 Result.getComplexFloatImag().changeSign();
3850 }
3851 else {
3852 Result.getComplexIntReal() = -Result.getComplexIntReal();
3853 Result.getComplexIntImag() = -Result.getComplexIntImag();
3854 }
3855 return true;
3856 case UO_Not:
3857 if (Result.isComplexFloat())
3858 Result.getComplexFloatImag().changeSign();
3859 else
3860 Result.getComplexIntImag() = -Result.getComplexIntImag();
3861 return true;
3862 }
3863}
3864
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00003865//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00003866// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003867//===----------------------------------------------------------------------===//
3868
Richard Smith47a1eed2011-10-29 20:57:55 +00003869static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003870 // In C, function designators are not lvalues, but we evaluate them as if they
3871 // are.
3872 if (E->isGLValue() || E->getType()->isFunctionType()) {
3873 LValue LV;
3874 if (!EvaluateLValue(E, LV, Info))
3875 return false;
3876 LV.moveInto(Result);
3877 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00003878 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00003879 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00003880 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00003881 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00003882 return false;
John McCallefdb83e2010-05-07 21:00:08 +00003883 } else if (E->getType()->hasPointerRepresentation()) {
3884 LValue LV;
3885 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00003886 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00003887 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00003888 } else if (E->getType()->isRealFloatingType()) {
3889 llvm::APFloat F(0.0);
3890 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00003891 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00003892 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00003893 } else if (E->getType()->isAnyComplexType()) {
3894 ComplexValue C;
3895 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00003896 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00003897 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00003898 } else if (E->getType()->isMemberPointerType()) {
3899 // FIXME: Implement evaluation of pointer-to-member types.
3900 return false;
3901 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smith180f4792011-11-10 06:34:14 +00003902 LValue LV;
3903 LV.setExpr(E, Info.CurrentCall);
3904 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00003905 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003906 Result = Info.CurrentCall->Temporaries[E];
Richard Smith69c2c502011-11-04 05:33:44 +00003907 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smith180f4792011-11-10 06:34:14 +00003908 LValue LV;
3909 LV.setExpr(E, Info.CurrentCall);
3910 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
3911 return false;
3912 Result = Info.CurrentCall->Temporaries[E];
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003913 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00003914 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00003915
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00003916 return true;
3917}
3918
Richard Smith69c2c502011-11-04 05:33:44 +00003919/// EvaluateConstantExpression - Evaluate an expression as a constant expression
3920/// in-place in an APValue. In some cases, the in-place evaluation is essential,
3921/// since later initializers for an object can indirectly refer to subobjects
3922/// which were initialized earlier.
3923static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith180f4792011-11-10 06:34:14 +00003924 const LValue &This, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003925 if (E->isRValue() && E->getType()->isLiteralType()) {
3926 // Evaluate arrays and record types in-place, so that later initializers can
3927 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00003928 if (E->getType()->isArrayType())
3929 return EvaluateArray(E, This, Result, Info);
3930 else if (E->getType()->isRecordType())
3931 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00003932 }
3933
3934 // For any other type, in-place evaluation is unimportant.
3935 CCValue CoreConstResult;
3936 return Evaluate(CoreConstResult, Info, E) &&
3937 CheckConstantExpression(CoreConstResult, Result);
3938}
3939
Richard Smithc49bd112011-10-28 17:51:58 +00003940
Richard Smith51f47082011-10-29 00:50:52 +00003941/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00003942/// any crazy technique (that has nothing to do with language standards) that
3943/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00003944/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3945/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00003946bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith1445bba2011-11-10 03:30:42 +00003947 // FIXME: Evaluating initializers for large arrays can cause performance
3948 // problems, and we don't use such values yet. Once we have a more efficient
3949 // array representation, this should be reinstated, and used by CodeGen.
3950 if (isRValue() && getType()->isArrayType())
3951 return false;
3952
John McCall56ca35d2011-02-17 10:25:35 +00003953 EvalInfo Info(Ctx, Result);
Richard Smithc49bd112011-10-28 17:51:58 +00003954
Richard Smith180f4792011-11-10 06:34:14 +00003955 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smith47a1eed2011-10-29 20:57:55 +00003956 CCValue Value;
3957 if (!::Evaluate(Value, Info, this))
Richard Smithc49bd112011-10-28 17:51:58 +00003958 return false;
3959
3960 if (isGLValue()) {
3961 LValue LV;
Richard Smith47a1eed2011-10-29 20:57:55 +00003962 LV.setFrom(Value);
3963 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3964 return false;
Richard Smithc49bd112011-10-28 17:51:58 +00003965 }
3966
Richard Smith47a1eed2011-10-29 20:57:55 +00003967 // Check this core constant expression is a constant expression, and if so,
Richard Smith69c2c502011-11-04 05:33:44 +00003968 // convert it to one.
3969 return CheckConstantExpression(Value, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00003970}
3971
Jay Foad4ba2a172011-01-12 09:06:06 +00003972bool Expr::EvaluateAsBooleanCondition(bool &Result,
3973 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00003974 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00003975 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith177dce72011-11-01 16:57:24 +00003976 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00003977 Result);
John McCallcd7a4452010-01-05 23:42:56 +00003978}
3979
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003980bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00003981 EvalResult ExprResult;
Richard Smith51f47082011-10-29 00:50:52 +00003982 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithc49bd112011-10-28 17:51:58 +00003983 !ExprResult.Val.isInt()) {
3984 return false;
3985 }
3986 Result = ExprResult.Val.getInt();
3987 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003988}
3989
Jay Foad4ba2a172011-01-12 09:06:06 +00003990bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00003991 EvalInfo Info(Ctx, Result);
3992
John McCallefdb83e2010-05-07 21:00:08 +00003993 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00003994 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
3995 CheckLValueConstantExpression(LV, Result.Val);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00003996}
3997
Richard Smith51f47082011-10-29 00:50:52 +00003998/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3999/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00004000bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00004001 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00004002 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00004003}
Anders Carlsson51fe9962008-11-22 21:04:56 +00004004
Jay Foad4ba2a172011-01-12 09:06:06 +00004005bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00004006 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004007}
4008
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004009APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004010 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00004011 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00004012 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00004013 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004014 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00004015
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004016 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00004017}
John McCalld905f5a2010-05-07 05:32:02 +00004018
Abramo Bagnarae17a6432010-05-14 17:07:14 +00004019 bool Expr::EvalResult::isGlobalLValue() const {
4020 assert(Val.isLValue());
4021 return IsGlobalLValue(Val.getLValueBase());
4022 }
4023
4024
John McCalld905f5a2010-05-07 05:32:02 +00004025/// isIntegerConstantExpr - this recursive routine will test if an expression is
4026/// an integer constant expression.
4027
4028/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
4029/// comma, etc
4030///
4031/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
4032/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
4033/// cast+dereference.
4034
4035// CheckICE - This function does the fundamental ICE checking: the returned
4036// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
4037// Note that to reduce code duplication, this helper does no evaluation
4038// itself; the caller checks whether the expression is evaluatable, and
4039// in the rare cases where CheckICE actually cares about the evaluated
4040// value, it calls into Evalute.
4041//
4042// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00004043// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00004044// 1: This expression is not an ICE, but if it isn't evaluated, it's
4045// a legal subexpression for an ICE. This return value is used to handle
4046// the comma operator in C99 mode.
4047// 2: This expression is not an ICE, and is not a legal subexpression for one.
4048
Dan Gohman3c46e8d2010-07-26 21:25:24 +00004049namespace {
4050
John McCalld905f5a2010-05-07 05:32:02 +00004051struct ICEDiag {
4052 unsigned Val;
4053 SourceLocation Loc;
4054
4055 public:
4056 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
4057 ICEDiag() : Val(0) {}
4058};
4059
Dan Gohman3c46e8d2010-07-26 21:25:24 +00004060}
4061
4062static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00004063
4064static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
4065 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00004066 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00004067 !EVResult.Val.isInt()) {
4068 return ICEDiag(2, E->getLocStart());
4069 }
4070 return NoDiag();
4071}
4072
4073static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
4074 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004075 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00004076 return ICEDiag(2, E->getLocStart());
4077 }
4078
4079 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00004080#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00004081#define STMT(Node, Base) case Expr::Node##Class:
4082#define EXPR(Node, Base)
4083#include "clang/AST/StmtNodes.inc"
4084 case Expr::PredefinedExprClass:
4085 case Expr::FloatingLiteralClass:
4086 case Expr::ImaginaryLiteralClass:
4087 case Expr::StringLiteralClass:
4088 case Expr::ArraySubscriptExprClass:
4089 case Expr::MemberExprClass:
4090 case Expr::CompoundAssignOperatorClass:
4091 case Expr::CompoundLiteralExprClass:
4092 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004093 case Expr::DesignatedInitExprClass:
4094 case Expr::ImplicitValueInitExprClass:
4095 case Expr::ParenListExprClass:
4096 case Expr::VAArgExprClass:
4097 case Expr::AddrLabelExprClass:
4098 case Expr::StmtExprClass:
4099 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00004100 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004101 case Expr::CXXDynamicCastExprClass:
4102 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00004103 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004104 case Expr::CXXNullPtrLiteralExprClass:
4105 case Expr::CXXThisExprClass:
4106 case Expr::CXXThrowExprClass:
4107 case Expr::CXXNewExprClass:
4108 case Expr::CXXDeleteExprClass:
4109 case Expr::CXXPseudoDestructorExprClass:
4110 case Expr::UnresolvedLookupExprClass:
4111 case Expr::DependentScopeDeclRefExprClass:
4112 case Expr::CXXConstructExprClass:
4113 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00004114 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00004115 case Expr::CXXTemporaryObjectExprClass:
4116 case Expr::CXXUnresolvedConstructExprClass:
4117 case Expr::CXXDependentScopeMemberExprClass:
4118 case Expr::UnresolvedMemberExprClass:
4119 case Expr::ObjCStringLiteralClass:
4120 case Expr::ObjCEncodeExprClass:
4121 case Expr::ObjCMessageExprClass:
4122 case Expr::ObjCSelectorExprClass:
4123 case Expr::ObjCProtocolExprClass:
4124 case Expr::ObjCIvarRefExprClass:
4125 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004126 case Expr::ObjCIsaExprClass:
4127 case Expr::ShuffleVectorExprClass:
4128 case Expr::BlockExprClass:
4129 case Expr::BlockDeclRefExprClass:
4130 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00004131 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00004132 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00004133 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004134 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004135 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00004136 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00004137 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00004138 case Expr::AtomicExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004139 return ICEDiag(2, E->getLocStart());
4140
Sebastian Redlcea8d962011-09-24 17:48:14 +00004141 case Expr::InitListExprClass:
4142 if (Ctx.getLangOptions().CPlusPlus0x) {
4143 const InitListExpr *ILE = cast<InitListExpr>(E);
4144 if (ILE->getNumInits() == 0)
4145 return NoDiag();
4146 if (ILE->getNumInits() == 1)
4147 return CheckICE(ILE->getInit(0), Ctx);
4148 // Fall through for more than 1 expression.
4149 }
4150 return ICEDiag(2, E->getLocStart());
4151
Douglas Gregoree8aff02011-01-04 17:33:58 +00004152 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004153 case Expr::GNUNullExprClass:
4154 // GCC considers the GNU __null value to be an integral constant expression.
4155 return NoDiag();
4156
John McCall91a57552011-07-15 05:09:51 +00004157 case Expr::SubstNonTypeTemplateParmExprClass:
4158 return
4159 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
4160
John McCalld905f5a2010-05-07 05:32:02 +00004161 case Expr::ParenExprClass:
4162 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00004163 case Expr::GenericSelectionExprClass:
4164 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00004165 case Expr::IntegerLiteralClass:
4166 case Expr::CharacterLiteralClass:
4167 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00004168 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004169 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00004170 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00004171 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00004172 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00004173 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004174 return NoDiag();
4175 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00004176 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00004177 // C99 6.6/3 allows function calls within unevaluated subexpressions of
4178 // constant expressions, but they can never be ICEs because an ICE cannot
4179 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00004180 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00004181 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00004182 return CheckEvalInICE(E, Ctx);
4183 return ICEDiag(2, E->getLocStart());
4184 }
4185 case Expr::DeclRefExprClass:
4186 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
4187 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00004188 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00004189 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4190
4191 // Parameter variables are never constants. Without this check,
4192 // getAnyInitializer() can find a default argument, which leads
4193 // to chaos.
4194 if (isa<ParmVarDecl>(D))
4195 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4196
4197 // C++ 7.1.5.1p2
4198 // A variable of non-volatile const-qualified integral or enumeration
4199 // type initialized by an ICE can be used in ICEs.
4200 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00004201 if (!Dcl->getType()->isIntegralOrEnumerationType())
4202 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4203
John McCalld905f5a2010-05-07 05:32:02 +00004204 // Look for a declaration of this variable that has an initializer.
4205 const VarDecl *ID = 0;
4206 const Expr *Init = Dcl->getAnyInitializer(ID);
4207 if (Init) {
4208 if (ID->isInitKnownICE()) {
4209 // We have already checked whether this subexpression is an
4210 // integral constant expression.
4211 if (ID->isInitICE())
4212 return NoDiag();
4213 else
4214 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4215 }
4216
4217 // It's an ICE whether or not the definition we found is
4218 // out-of-line. See DR 721 and the discussion in Clang PR
4219 // 6206 for details.
4220
4221 if (Dcl->isCheckingICE()) {
4222 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4223 }
4224
4225 Dcl->setCheckingICE();
4226 ICEDiag Result = CheckICE(Init, Ctx);
4227 // Cache the result of the ICE test.
4228 Dcl->setInitKnownICE(Result.Val == 0);
4229 return Result;
4230 }
4231 }
4232 }
4233 return ICEDiag(2, E->getLocStart());
4234 case Expr::UnaryOperatorClass: {
4235 const UnaryOperator *Exp = cast<UnaryOperator>(E);
4236 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00004237 case UO_PostInc:
4238 case UO_PostDec:
4239 case UO_PreInc:
4240 case UO_PreDec:
4241 case UO_AddrOf:
4242 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00004243 // C99 6.6/3 allows increment and decrement within unevaluated
4244 // subexpressions of constant expressions, but they can never be ICEs
4245 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00004246 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00004247 case UO_Extension:
4248 case UO_LNot:
4249 case UO_Plus:
4250 case UO_Minus:
4251 case UO_Not:
4252 case UO_Real:
4253 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00004254 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00004255 }
4256
4257 // OffsetOf falls through here.
4258 }
4259 case Expr::OffsetOfExprClass: {
4260 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00004261 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00004262 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00004263 // compliance: we should warn earlier for offsetof expressions with
4264 // array subscripts that aren't ICEs, and if the array subscripts
4265 // are ICEs, the value of the offsetof must be an integer constant.
4266 return CheckEvalInICE(E, Ctx);
4267 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004268 case Expr::UnaryExprOrTypeTraitExprClass: {
4269 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
4270 if ((Exp->getKind() == UETT_SizeOf) &&
4271 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00004272 return ICEDiag(2, E->getLocStart());
4273 return NoDiag();
4274 }
4275 case Expr::BinaryOperatorClass: {
4276 const BinaryOperator *Exp = cast<BinaryOperator>(E);
4277 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00004278 case BO_PtrMemD:
4279 case BO_PtrMemI:
4280 case BO_Assign:
4281 case BO_MulAssign:
4282 case BO_DivAssign:
4283 case BO_RemAssign:
4284 case BO_AddAssign:
4285 case BO_SubAssign:
4286 case BO_ShlAssign:
4287 case BO_ShrAssign:
4288 case BO_AndAssign:
4289 case BO_XorAssign:
4290 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00004291 // C99 6.6/3 allows assignments within unevaluated subexpressions of
4292 // constant expressions, but they can never be ICEs because an ICE cannot
4293 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00004294 return ICEDiag(2, E->getLocStart());
4295
John McCall2de56d12010-08-25 11:45:40 +00004296 case BO_Mul:
4297 case BO_Div:
4298 case BO_Rem:
4299 case BO_Add:
4300 case BO_Sub:
4301 case BO_Shl:
4302 case BO_Shr:
4303 case BO_LT:
4304 case BO_GT:
4305 case BO_LE:
4306 case BO_GE:
4307 case BO_EQ:
4308 case BO_NE:
4309 case BO_And:
4310 case BO_Xor:
4311 case BO_Or:
4312 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00004313 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
4314 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00004315 if (Exp->getOpcode() == BO_Div ||
4316 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00004317 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00004318 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00004319 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004320 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00004321 if (REval == 0)
4322 return ICEDiag(1, E->getLocStart());
4323 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004324 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00004325 if (LEval.isMinSignedValue())
4326 return ICEDiag(1, E->getLocStart());
4327 }
4328 }
4329 }
John McCall2de56d12010-08-25 11:45:40 +00004330 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00004331 if (Ctx.getLangOptions().C99) {
4332 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
4333 // if it isn't evaluated.
4334 if (LHSResult.Val == 0 && RHSResult.Val == 0)
4335 return ICEDiag(1, E->getLocStart());
4336 } else {
4337 // In both C89 and C++, commas in ICEs are illegal.
4338 return ICEDiag(2, E->getLocStart());
4339 }
4340 }
4341 if (LHSResult.Val >= RHSResult.Val)
4342 return LHSResult;
4343 return RHSResult;
4344 }
John McCall2de56d12010-08-25 11:45:40 +00004345 case BO_LAnd:
4346 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00004347 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00004348
4349 // C++0x [expr.const]p2:
4350 // [...] subexpressions of logical AND (5.14), logical OR
4351 // (5.15), and condi- tional (5.16) operations that are not
4352 // evaluated are not considered.
4353 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
4354 if (Exp->getOpcode() == BO_LAnd &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004355 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregor63fe6812011-05-24 16:02:01 +00004356 return LHSResult;
4357
4358 if (Exp->getOpcode() == BO_LOr &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004359 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregor63fe6812011-05-24 16:02:01 +00004360 return LHSResult;
4361 }
4362
John McCalld905f5a2010-05-07 05:32:02 +00004363 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
4364 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
4365 // Rare case where the RHS has a comma "side-effect"; we need
4366 // to actually check the condition to see whether the side
4367 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00004368 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004369 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00004370 return RHSResult;
4371 return NoDiag();
4372 }
4373
4374 if (LHSResult.Val >= RHSResult.Val)
4375 return LHSResult;
4376 return RHSResult;
4377 }
4378 }
4379 }
4380 case Expr::ImplicitCastExprClass:
4381 case Expr::CStyleCastExprClass:
4382 case Expr::CXXFunctionalCastExprClass:
4383 case Expr::CXXStaticCastExprClass:
4384 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00004385 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004386 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00004387 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith98326ed2011-10-25 00:21:54 +00004388 if (isa<ExplicitCastExpr>(E) &&
Richard Smith32cb4712011-10-24 18:26:35 +00004389 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
4390 return NoDiag();
Eli Friedmaneea0e812011-09-29 21:49:34 +00004391 switch (cast<CastExpr>(E)->getCastKind()) {
4392 case CK_LValueToRValue:
4393 case CK_NoOp:
4394 case CK_IntegralToBoolean:
4395 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00004396 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00004397 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00004398 return ICEDiag(2, E->getLocStart());
4399 }
John McCalld905f5a2010-05-07 05:32:02 +00004400 }
John McCall56ca35d2011-02-17 10:25:35 +00004401 case Expr::BinaryConditionalOperatorClass: {
4402 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
4403 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
4404 if (CommonResult.Val == 2) return CommonResult;
4405 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
4406 if (FalseResult.Val == 2) return FalseResult;
4407 if (CommonResult.Val == 1) return CommonResult;
4408 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004409 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00004410 return FalseResult;
4411 }
John McCalld905f5a2010-05-07 05:32:02 +00004412 case Expr::ConditionalOperatorClass: {
4413 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
4414 // If the condition (ignoring parens) is a __builtin_constant_p call,
4415 // then only the true side is actually considered in an integer constant
4416 // expression, and it is fully evaluated. This is an important GNU
4417 // extension. See GCC PR38377 for discussion.
4418 if (const CallExpr *CallCE
4419 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith180f4792011-11-10 06:34:14 +00004420 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCalld905f5a2010-05-07 05:32:02 +00004421 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00004422 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00004423 !EVResult.Val.isInt()) {
4424 return ICEDiag(2, E->getLocStart());
4425 }
4426 return NoDiag();
4427 }
4428 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00004429 if (CondResult.Val == 2)
4430 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00004431
4432 // C++0x [expr.const]p2:
4433 // subexpressions of [...] conditional (5.16) operations that
4434 // are not evaluated are not considered
4435 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004436 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregor63fe6812011-05-24 16:02:01 +00004437 : false;
4438 ICEDiag TrueResult = NoDiag();
4439 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
4440 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
4441 ICEDiag FalseResult = NoDiag();
4442 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
4443 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
4444
John McCalld905f5a2010-05-07 05:32:02 +00004445 if (TrueResult.Val == 2)
4446 return TrueResult;
4447 if (FalseResult.Val == 2)
4448 return FalseResult;
4449 if (CondResult.Val == 1)
4450 return CondResult;
4451 if (TrueResult.Val == 0 && FalseResult.Val == 0)
4452 return NoDiag();
4453 // Rare case where the diagnostics depend on which side is evaluated
4454 // Note that if we get here, CondResult is 0, and at least one of
4455 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004456 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00004457 return FalseResult;
4458 }
4459 return TrueResult;
4460 }
4461 case Expr::CXXDefaultArgExprClass:
4462 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
4463 case Expr::ChooseExprClass: {
4464 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
4465 }
4466 }
4467
4468 // Silence a GCC warning
4469 return ICEDiag(2, E->getLocStart());
4470}
4471
4472bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
4473 SourceLocation *Loc, bool isEvaluated) const {
4474 ICEDiag d = CheckICE(this, Ctx);
4475 if (d.Val != 0) {
4476 if (Loc) *Loc = d.Loc;
4477 return false;
4478 }
Richard Smithc49bd112011-10-28 17:51:58 +00004479 if (!EvaluateAsInt(Result, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00004480 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00004481 return true;
4482}