blob: fc214bfa801174bf310922d06a3f74d2e89dcb36 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000046 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000049
Richard Smithce40ad62011-11-12 22:28:03 +000050 QualType getType(APValue::LValueBase B) {
51 if (!B) return QualType();
52 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
53 return D->getType();
54 return B.get<const Expr*>()->getType();
55 }
56
Richard Smithd62306a2011-11-10 06:34:14 +000057 /// Get an LValue path entry, which is known to not be an array index, as a
58 /// field declaration.
59 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
60 APValue::BaseOrMemberType Value;
61 Value.setFromOpaqueValue(E.BaseOrMember);
62 return dyn_cast<FieldDecl>(Value.getPointer());
63 }
64 /// Get an LValue path entry, which is known to not be an array index, as a
65 /// base class declaration.
66 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
67 APValue::BaseOrMemberType Value;
68 Value.setFromOpaqueValue(E.BaseOrMember);
69 return dyn_cast<CXXRecordDecl>(Value.getPointer());
70 }
71 /// Determine whether this LValue path entry for a base class names a virtual
72 /// base class.
73 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
74 APValue::BaseOrMemberType Value;
75 Value.setFromOpaqueValue(E.BaseOrMember);
76 return Value.getInt();
77 }
78
Richard Smith80815602011-11-07 05:07:52 +000079 /// Determine whether the described subobject is an array element.
80 static bool SubobjectIsArrayElement(QualType Base,
81 ArrayRef<APValue::LValuePathEntry> Path) {
82 bool IsArrayElement = false;
83 const Type *T = Base.getTypePtr();
84 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
85 IsArrayElement = T && T->isArrayType();
86 if (IsArrayElement)
87 T = T->getBaseElementTypeUnsafe();
Richard Smithd62306a2011-11-10 06:34:14 +000088 else if (const FieldDecl *FD = getAsField(Path[I]))
Richard Smith80815602011-11-07 05:07:52 +000089 T = FD->getType().getTypePtr();
90 else
91 // Path[I] describes a base class.
92 T = 0;
93 }
94 return IsArrayElement;
95 }
96
Richard Smith96e0c102011-11-04 02:25:55 +000097 /// A path from a glvalue to a subobject of that glvalue.
98 struct SubobjectDesignator {
99 /// True if the subobject was named in a manner not supported by C++11. Such
100 /// lvalues can still be folded, but they are not core constant expressions
101 /// and we cannot perform lvalue-to-rvalue conversions on them.
102 bool Invalid : 1;
103
104 /// Whether this designates an array element.
105 bool ArrayElement : 1;
106
107 /// Whether this designates 'one past the end' of the current subobject.
108 bool OnePastTheEnd : 1;
109
Richard Smith80815602011-11-07 05:07:52 +0000110 typedef APValue::LValuePathEntry PathEntry;
111
Richard Smith96e0c102011-11-04 02:25:55 +0000112 /// The entries on the path from the glvalue to the designated subobject.
113 SmallVector<PathEntry, 8> Entries;
114
115 SubobjectDesignator() :
116 Invalid(false), ArrayElement(false), OnePastTheEnd(false) {}
117
Richard Smith80815602011-11-07 05:07:52 +0000118 SubobjectDesignator(const APValue &V) :
119 Invalid(!V.isLValue() || !V.hasLValuePath()), ArrayElement(false),
120 OnePastTheEnd(false) {
121 if (!Invalid) {
122 ArrayRef<PathEntry> VEntries = V.getLValuePath();
123 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
124 if (V.getLValueBase())
Richard Smithce40ad62011-11-12 22:28:03 +0000125 ArrayElement = SubobjectIsArrayElement(getType(V.getLValueBase()),
Richard Smith80815602011-11-07 05:07:52 +0000126 V.getLValuePath());
127 else
128 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
Richard Smith027bf112011-11-17 22:56:20 +0000129 OnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000130 }
131 }
132
Richard Smith96e0c102011-11-04 02:25:55 +0000133 void setInvalid() {
134 Invalid = true;
135 Entries.clear();
136 }
137 /// Update this designator to refer to the given element within this array.
138 void addIndex(uint64_t N) {
139 if (Invalid) return;
140 if (OnePastTheEnd) {
141 setInvalid();
142 return;
143 }
144 PathEntry Entry;
Richard Smith80815602011-11-07 05:07:52 +0000145 Entry.ArrayIndex = N;
Richard Smith96e0c102011-11-04 02:25:55 +0000146 Entries.push_back(Entry);
147 ArrayElement = true;
148 }
149 /// Update this designator to refer to the given base or member of this
150 /// object.
Richard Smithd62306a2011-11-10 06:34:14 +0000151 void addDecl(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000152 if (Invalid) return;
153 if (OnePastTheEnd) {
154 setInvalid();
155 return;
156 }
157 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000158 APValue::BaseOrMemberType Value(D, Virtual);
159 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000160 Entries.push_back(Entry);
161 ArrayElement = false;
162 }
163 /// Add N to the address of this subobject.
164 void adjustIndex(uint64_t N) {
165 if (Invalid) return;
166 if (ArrayElement) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000167 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith80815602011-11-07 05:07:52 +0000168 Entries.back().ArrayIndex += N;
Richard Smith96e0c102011-11-04 02:25:55 +0000169 return;
170 }
171 if (OnePastTheEnd && N == (uint64_t)-1)
172 OnePastTheEnd = false;
173 else if (!OnePastTheEnd && N == 1)
174 OnePastTheEnd = true;
175 else if (N != 0)
176 setInvalid();
177 }
178 };
179
Richard Smith0b0a0b62011-10-29 20:57:55 +0000180 /// A core constant value. This can be the value of any constant expression,
181 /// or a pointer or reference to a non-static object or function parameter.
Richard Smith027bf112011-11-17 22:56:20 +0000182 ///
183 /// For an LValue, the base and offset are stored in the APValue subobject,
184 /// but the other information is stored in the SubobjectDesignator. For all
185 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000186 class CCValue : public APValue {
187 typedef llvm::APSInt APSInt;
188 typedef llvm::APFloat APFloat;
Richard Smithfec09922011-11-01 16:57:24 +0000189 /// If the value is a reference or pointer into a parameter or temporary,
190 /// this is the corresponding call stack frame.
191 CallStackFrame *CallFrame;
Richard Smith96e0c102011-11-04 02:25:55 +0000192 /// If the value is a reference or pointer, this is a description of how the
193 /// subobject was specified.
194 SubobjectDesignator Designator;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000195 public:
Richard Smithfec09922011-11-01 16:57:24 +0000196 struct GlobalValue {};
197
Richard Smith0b0a0b62011-10-29 20:57:55 +0000198 CCValue() {}
199 explicit CCValue(const APSInt &I) : APValue(I) {}
200 explicit CCValue(const APFloat &F) : APValue(F) {}
201 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
202 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
203 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smithfec09922011-11-01 16:57:24 +0000204 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smithce40ad62011-11-12 22:28:03 +0000205 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith96e0c102011-11-04 02:25:55 +0000206 const SubobjectDesignator &D) :
Richard Smith80815602011-11-07 05:07:52 +0000207 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithfec09922011-11-01 16:57:24 +0000208 CCValue(const APValue &V, GlobalValue) :
Richard Smith80815602011-11-07 05:07:52 +0000209 APValue(V), CallFrame(0), Designator(V) {}
Richard Smith027bf112011-11-17 22:56:20 +0000210 CCValue(const ValueDecl *D, bool IsDerivedMember,
211 ArrayRef<const CXXRecordDecl*> Path) :
212 APValue(D, IsDerivedMember, Path) {}
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000213 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
214 APValue(LHSExpr, RHSExpr) {}
Richard Smith0b0a0b62011-10-29 20:57:55 +0000215
Richard Smithfec09922011-11-01 16:57:24 +0000216 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000217 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +0000218 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000219 }
Richard Smith96e0c102011-11-04 02:25:55 +0000220 SubobjectDesignator &getLValueDesignator() {
221 assert(getKind() == LValue);
222 return Designator;
223 }
224 const SubobjectDesignator &getLValueDesignator() const {
225 return const_cast<CCValue*>(this)->getLValueDesignator();
226 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000227 };
228
Richard Smith254a73d2011-10-28 22:34:42 +0000229 /// A stack frame in the constexpr call stack.
230 struct CallStackFrame {
231 EvalInfo &Info;
232
233 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000234 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000235
Richard Smithf6f003a2011-12-16 19:06:07 +0000236 /// CallLoc - The location of the call expression for this call.
237 SourceLocation CallLoc;
238
239 /// Callee - The function which was called.
240 const FunctionDecl *Callee;
241
Richard Smithd62306a2011-11-10 06:34:14 +0000242 /// This - The binding for the this pointer in this call, if any.
243 const LValue *This;
244
Richard Smith254a73d2011-10-28 22:34:42 +0000245 /// ParmBindings - Parameter bindings for this function call, indexed by
246 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000247 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000248
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000249 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
250 typedef MapTy::const_iterator temp_iterator;
251 /// Temporaries - Temporary lvalues materialized within this stack frame.
252 MapTy Temporaries;
253
Richard Smithf6f003a2011-12-16 19:06:07 +0000254 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
255 const FunctionDecl *Callee, const LValue *This,
Richard Smithd62306a2011-11-10 06:34:14 +0000256 const CCValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000257 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000258 };
259
Richard Smith92b1ce02011-12-12 09:28:41 +0000260 /// A partial diagnostic which we might know in advance that we are not going
261 /// to emit.
262 class OptionalDiagnostic {
263 PartialDiagnostic *Diag;
264
265 public:
266 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
267
268 template<typename T>
269 OptionalDiagnostic &operator<<(const T &v) {
270 if (Diag)
271 *Diag << v;
272 return *this;
273 }
274 };
275
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000276 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000277 ASTContext &Ctx;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000278
279 /// EvalStatus - Contains information about the evaluation.
280 Expr::EvalStatus &EvalStatus;
281
282 /// CurrentCall - The top of the constexpr call stack.
283 CallStackFrame *CurrentCall;
284
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000285 /// CallStackDepth - The number of calls in the call stack right now.
286 unsigned CallStackDepth;
287
288 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
289 /// OpaqueValues - Values used as the common expression in a
290 /// BinaryConditionalOperator.
291 MapTy OpaqueValues;
292
293 /// BottomFrame - The frame in which evaluation started. This must be
294 /// initialized last.
295 CallStackFrame BottomFrame;
296
Richard Smithd62306a2011-11-10 06:34:14 +0000297 /// EvaluatingDecl - This is the declaration whose initializer is being
298 /// evaluated, if any.
299 const VarDecl *EvaluatingDecl;
300
301 /// EvaluatingDeclValue - This is the value being constructed for the
302 /// declaration whose initializer is being evaluated, if any.
303 APValue *EvaluatingDeclValue;
304
Richard Smith357362d2011-12-13 06:39:58 +0000305 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
306 /// notes attached to it will also be stored, otherwise they will not be.
307 bool HasActiveDiagnostic;
308
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000309
310 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith92b1ce02011-12-12 09:28:41 +0000311 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithf6f003a2011-12-16 19:06:07 +0000312 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
313 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000314
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000315 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
316 MapTy::const_iterator i = OpaqueValues.find(e);
317 if (i == OpaqueValues.end()) return 0;
318 return &i->second;
319 }
320
Richard Smithd62306a2011-11-10 06:34:14 +0000321 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
322 EvaluatingDecl = VD;
323 EvaluatingDeclValue = &Value;
324 }
325
Richard Smith9a568822011-11-21 19:36:32 +0000326 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
327
Richard Smith357362d2011-12-13 06:39:58 +0000328 bool CheckCallLimit(SourceLocation Loc) {
329 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
330 return true;
331 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
332 << getLangOpts().ConstexprCallDepth;
333 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000334 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000335
Richard Smith357362d2011-12-13 06:39:58 +0000336 private:
337 /// Add a diagnostic to the diagnostics list.
338 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
339 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
340 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
341 return EvalStatus.Diag->back().second;
342 }
343
Richard Smithf6f003a2011-12-16 19:06:07 +0000344 /// Add notes containing a call stack to the current point of evaluation.
345 void addCallStack(unsigned Limit);
346
Richard Smith357362d2011-12-13 06:39:58 +0000347 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000348 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000349 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
350 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000351 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000352 // If we have a prior diagnostic, it will be noting that the expression
353 // isn't a constant expression. This diagnostic is more important.
354 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000355 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000356 unsigned CallStackNotes = CallStackDepth - 1;
357 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
358 if (Limit)
359 CallStackNotes = std::min(CallStackNotes, Limit + 1);
360
Richard Smith357362d2011-12-13 06:39:58 +0000361 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000362 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000363 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
364 addDiag(Loc, DiagId);
365 addCallStack(Limit);
366 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000367 }
Richard Smith357362d2011-12-13 06:39:58 +0000368 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000369 return OptionalDiagnostic();
370 }
371
372 /// Diagnose that the evaluation does not produce a C++11 core constant
373 /// expression.
Richard Smithf2b681b2011-12-21 05:04:46 +0000374 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
375 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000376 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000377 // Don't override a previous diagnostic.
378 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
379 return OptionalDiagnostic();
Richard Smith357362d2011-12-13 06:39:58 +0000380 return Diag(Loc, DiagId, ExtraNotes);
381 }
382
383 /// Add a note to a prior diagnostic.
384 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
385 if (!HasActiveDiagnostic)
386 return OptionalDiagnostic();
387 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000388 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000389
390 /// Add a stack of notes to a prior diagnostic.
391 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
392 if (HasActiveDiagnostic) {
393 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
394 Diags.begin(), Diags.end());
395 }
396 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000397 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000398}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000399
Richard Smithf6f003a2011-12-16 19:06:07 +0000400CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
401 const FunctionDecl *Callee, const LValue *This,
402 const CCValue *Arguments)
403 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
404 This(This), Arguments(Arguments) {
405 Info.CurrentCall = this;
406 ++Info.CallStackDepth;
407}
408
409CallStackFrame::~CallStackFrame() {
410 assert(Info.CurrentCall == this && "calls retired out of order");
411 --Info.CallStackDepth;
412 Info.CurrentCall = Caller;
413}
414
415/// Produce a string describing the given constexpr call.
416static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
417 unsigned ArgIndex = 0;
418 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
419 !isa<CXXConstructorDecl>(Frame->Callee);
420
421 if (!IsMemberCall)
422 Out << *Frame->Callee << '(';
423
424 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
425 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
426 if (ArgIndex > IsMemberCall)
427 Out << ", ";
428
429 const ParmVarDecl *Param = *I;
430 const CCValue &Arg = Frame->Arguments[ArgIndex];
431 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
432 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
433 else {
434 // Deliberately slice off the frame to form an APValue we can print.
435 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
436 Arg.getLValueDesignator().Entries,
437 Arg.getLValueDesignator().OnePastTheEnd);
438 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
439 }
440
441 if (ArgIndex == 0 && IsMemberCall)
442 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000443 }
444
Richard Smithf6f003a2011-12-16 19:06:07 +0000445 Out << ')';
446}
447
448void EvalInfo::addCallStack(unsigned Limit) {
449 // Determine which calls to skip, if any.
450 unsigned ActiveCalls = CallStackDepth - 1;
451 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
452 if (Limit && Limit < ActiveCalls) {
453 SkipStart = Limit / 2 + Limit % 2;
454 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000455 }
456
Richard Smithf6f003a2011-12-16 19:06:07 +0000457 // Walk the call stack and add the diagnostics.
458 unsigned CallIdx = 0;
459 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
460 Frame = Frame->Caller, ++CallIdx) {
461 // Skip this call?
462 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
463 if (CallIdx == SkipStart) {
464 // Note that we're skipping calls.
465 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
466 << unsigned(ActiveCalls - Limit);
467 }
468 continue;
469 }
470
471 llvm::SmallVector<char, 128> Buffer;
472 llvm::raw_svector_ostream Out(Buffer);
473 describeCall(Frame, Out);
474 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
475 }
476}
477
478namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000479 struct ComplexValue {
480 private:
481 bool IsInt;
482
483 public:
484 APSInt IntReal, IntImag;
485 APFloat FloatReal, FloatImag;
486
487 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
488
489 void makeComplexFloat() { IsInt = false; }
490 bool isComplexFloat() const { return !IsInt; }
491 APFloat &getComplexFloatReal() { return FloatReal; }
492 APFloat &getComplexFloatImag() { return FloatImag; }
493
494 void makeComplexInt() { IsInt = true; }
495 bool isComplexInt() const { return IsInt; }
496 APSInt &getComplexIntReal() { return IntReal; }
497 APSInt &getComplexIntImag() { return IntImag; }
498
Richard Smith0b0a0b62011-10-29 20:57:55 +0000499 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000500 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000501 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000502 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000503 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000504 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000505 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000506 assert(v.isComplexFloat() || v.isComplexInt());
507 if (v.isComplexFloat()) {
508 makeComplexFloat();
509 FloatReal = v.getComplexFloatReal();
510 FloatImag = v.getComplexFloatImag();
511 } else {
512 makeComplexInt();
513 IntReal = v.getComplexIntReal();
514 IntImag = v.getComplexIntImag();
515 }
516 }
John McCall93d91dc2010-05-07 17:22:02 +0000517 };
John McCall45d55e42010-05-07 21:00:08 +0000518
519 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000520 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000521 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000522 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000523 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000524
Richard Smithce40ad62011-11-12 22:28:03 +0000525 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000526 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000527 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000528 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000529 SubobjectDesignator &getLValueDesignator() { return Designator; }
530 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000531
Richard Smith0b0a0b62011-10-29 20:57:55 +0000532 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000533 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000534 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000535 void setFrom(const CCValue &V) {
536 assert(V.isLValue());
537 Base = V.getLValueBase();
538 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000539 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000540 Designator = V.getLValueDesignator();
541 }
542
Richard Smithce40ad62011-11-12 22:28:03 +0000543 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
544 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000545 Offset = CharUnits::Zero();
546 Frame = F;
547 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000548 }
John McCall45d55e42010-05-07 21:00:08 +0000549 };
Richard Smith027bf112011-11-17 22:56:20 +0000550
551 struct MemberPtr {
552 MemberPtr() {}
553 explicit MemberPtr(const ValueDecl *Decl) :
554 DeclAndIsDerivedMember(Decl, false), Path() {}
555
556 /// The member or (direct or indirect) field referred to by this member
557 /// pointer, or 0 if this is a null member pointer.
558 const ValueDecl *getDecl() const {
559 return DeclAndIsDerivedMember.getPointer();
560 }
561 /// Is this actually a member of some type derived from the relevant class?
562 bool isDerivedMember() const {
563 return DeclAndIsDerivedMember.getInt();
564 }
565 /// Get the class which the declaration actually lives in.
566 const CXXRecordDecl *getContainingRecord() const {
567 return cast<CXXRecordDecl>(
568 DeclAndIsDerivedMember.getPointer()->getDeclContext());
569 }
570
571 void moveInto(CCValue &V) const {
572 V = CCValue(getDecl(), isDerivedMember(), Path);
573 }
574 void setFrom(const CCValue &V) {
575 assert(V.isMemberPointer());
576 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
577 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
578 Path.clear();
579 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
580 Path.insert(Path.end(), P.begin(), P.end());
581 }
582
583 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
584 /// whether the member is a member of some class derived from the class type
585 /// of the member pointer.
586 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
587 /// Path - The path of base/derived classes from the member declaration's
588 /// class (exclusive) to the class type of the member pointer (inclusive).
589 SmallVector<const CXXRecordDecl*, 4> Path;
590
591 /// Perform a cast towards the class of the Decl (either up or down the
592 /// hierarchy).
593 bool castBack(const CXXRecordDecl *Class) {
594 assert(!Path.empty());
595 const CXXRecordDecl *Expected;
596 if (Path.size() >= 2)
597 Expected = Path[Path.size() - 2];
598 else
599 Expected = getContainingRecord();
600 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
601 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
602 // if B does not contain the original member and is not a base or
603 // derived class of the class containing the original member, the result
604 // of the cast is undefined.
605 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
606 // (D::*). We consider that to be a language defect.
607 return false;
608 }
609 Path.pop_back();
610 return true;
611 }
612 /// Perform a base-to-derived member pointer cast.
613 bool castToDerived(const CXXRecordDecl *Derived) {
614 if (!getDecl())
615 return true;
616 if (!isDerivedMember()) {
617 Path.push_back(Derived);
618 return true;
619 }
620 if (!castBack(Derived))
621 return false;
622 if (Path.empty())
623 DeclAndIsDerivedMember.setInt(false);
624 return true;
625 }
626 /// Perform a derived-to-base member pointer cast.
627 bool castToBase(const CXXRecordDecl *Base) {
628 if (!getDecl())
629 return true;
630 if (Path.empty())
631 DeclAndIsDerivedMember.setInt(true);
632 if (isDerivedMember()) {
633 Path.push_back(Base);
634 return true;
635 }
636 return castBack(Base);
637 }
638 };
Richard Smith357362d2011-12-13 06:39:58 +0000639
640 /// Kinds of constant expression checking, for diagnostics.
641 enum CheckConstantExpressionKind {
642 CCEK_Constant, ///< A normal constant.
643 CCEK_ReturnValue, ///< A constexpr function return value.
644 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
645 };
John McCall93d91dc2010-05-07 17:22:02 +0000646}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000647
Richard Smith0b0a0b62011-10-29 20:57:55 +0000648static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000649static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +0000650 const LValue &This, const Expr *E,
651 CheckConstantExpressionKind CCEK
652 = CCEK_Constant);
John McCall45d55e42010-05-07 21:00:08 +0000653static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
654static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000655static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
656 EvalInfo &Info);
657static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000658static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000659static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000660 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000661static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000662static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000663
664//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000665// Misc utilities
666//===----------------------------------------------------------------------===//
667
Richard Smithd62306a2011-11-10 06:34:14 +0000668/// Should this call expression be treated as a string literal?
669static bool IsStringLiteralCall(const CallExpr *E) {
670 unsigned Builtin = E->isBuiltinCall();
671 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
672 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
673}
674
Richard Smithce40ad62011-11-12 22:28:03 +0000675static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000676 // C++11 [expr.const]p3 An address constant expression is a prvalue core
677 // constant expression of pointer type that evaluates to...
678
679 // ... a null pointer value, or a prvalue core constant expression of type
680 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000681 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000682
Richard Smithce40ad62011-11-12 22:28:03 +0000683 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
684 // ... the address of an object with static storage duration,
685 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
686 return VD->hasGlobalStorage();
687 // ... the address of a function,
688 return isa<FunctionDecl>(D);
689 }
690
691 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000692 switch (E->getStmtClass()) {
693 default:
694 return false;
Richard Smithd62306a2011-11-10 06:34:14 +0000695 case Expr::CompoundLiteralExprClass:
696 return cast<CompoundLiteralExpr>(E)->isFileScope();
697 // A string literal has static storage duration.
698 case Expr::StringLiteralClass:
699 case Expr::PredefinedExprClass:
700 case Expr::ObjCStringLiteralClass:
701 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000702 case Expr::CXXTypeidExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000703 return true;
704 case Expr::CallExprClass:
705 return IsStringLiteralCall(cast<CallExpr>(E));
706 // For GCC compatibility, &&label has static storage duration.
707 case Expr::AddrLabelExprClass:
708 return true;
709 // A Block literal expression may be used as the initialization value for
710 // Block variables at global or local static scope.
711 case Expr::BlockExprClass:
712 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
713 }
John McCall95007602010-05-10 23:27:23 +0000714}
715
Richard Smith80815602011-11-07 05:07:52 +0000716/// Check that this reference or pointer core constant expression is a valid
717/// value for a constant expression. Type T should be either LValue or CCValue.
718template<typename T>
Richard Smithf57d8cb2011-12-09 22:58:01 +0000719static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000720 const T &LVal, APValue &Value,
721 CheckConstantExpressionKind CCEK) {
722 APValue::LValueBase Base = LVal.getLValueBase();
723 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
724
725 if (!IsGlobalLValue(Base)) {
726 if (Info.getLangOpts().CPlusPlus0x) {
727 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
728 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
729 << E->isGLValue() << !Designator.Entries.empty()
730 << !!VD << CCEK << VD;
731 if (VD)
732 Info.Note(VD->getLocation(), diag::note_declared_at);
733 else
734 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
735 diag::note_constexpr_temporary_here);
736 } else {
Richard Smithf2b681b2011-12-21 05:04:46 +0000737 Info.Diag(E->getExprLoc());
Richard Smith357362d2011-12-13 06:39:58 +0000738 }
Richard Smith80815602011-11-07 05:07:52 +0000739 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000740 }
Richard Smith80815602011-11-07 05:07:52 +0000741
Richard Smith80815602011-11-07 05:07:52 +0000742 // A constant expression must refer to an object or be a null pointer.
Richard Smith027bf112011-11-17 22:56:20 +0000743 if (Designator.Invalid ||
Richard Smith80815602011-11-07 05:07:52 +0000744 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smith357362d2011-12-13 06:39:58 +0000745 // FIXME: This is not a core constant expression. We should have already
746 // produced a CCE diagnostic.
Richard Smith80815602011-11-07 05:07:52 +0000747 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
748 APValue::NoLValuePath());
749 return true;
750 }
751
Richard Smith357362d2011-12-13 06:39:58 +0000752 // Does this refer one past the end of some object?
753 // This is technically not an address constant expression nor a reference
754 // constant expression, but we allow it for address constant expressions.
755 if (E->isGLValue() && Base && Designator.OnePastTheEnd) {
756 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
757 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
758 << !Designator.Entries.empty() << !!VD << VD;
759 if (VD)
760 Info.Note(VD->getLocation(), diag::note_declared_at);
761 else
762 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
763 diag::note_constexpr_temporary_here);
764 return false;
765 }
766
Richard Smith80815602011-11-07 05:07:52 +0000767 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smith027bf112011-11-17 22:56:20 +0000768 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith80815602011-11-07 05:07:52 +0000769 return true;
770}
771
Richard Smithfddd3842011-12-30 21:15:51 +0000772/// Check that this core constant expression is of literal type, and if not,
773/// produce an appropriate diagnostic.
774static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
775 if (!E->isRValue() || E->getType()->isLiteralType())
776 return true;
777
778 // Prvalue constant expressions must be of literal types.
779 if (Info.getLangOpts().CPlusPlus0x)
780 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
781 << E->getType();
782 else
783 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
784 return false;
785}
786
Richard Smith0b0a0b62011-10-29 20:57:55 +0000787/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000788/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithfddd3842011-12-30 21:15:51 +0000789/// If not, report an appropriate diagnostic. Does not check that the expression
790/// is of literal type.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000791static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000792 const CCValue &CCValue, APValue &Value,
793 CheckConstantExpressionKind CCEK
794 = CCEK_Constant) {
Richard Smith80815602011-11-07 05:07:52 +0000795 if (!CCValue.isLValue()) {
796 Value = CCValue;
797 return true;
798 }
Richard Smith357362d2011-12-13 06:39:58 +0000799 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000800}
801
Richard Smith83c68212011-10-31 05:11:32 +0000802const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000803 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000804}
805
806static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000807 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000808}
809
Richard Smithcecf1842011-11-01 21:06:14 +0000810static bool IsWeakLValue(const LValue &Value) {
811 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000812 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000813}
814
Richard Smith027bf112011-11-17 22:56:20 +0000815static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000816 // A null base expression indicates a null pointer. These are always
817 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000818 if (!Value.getLValueBase()) {
819 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000820 return true;
821 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000822
John McCall95007602010-05-10 23:27:23 +0000823 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000824 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000825 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000826
Richard Smith027bf112011-11-17 22:56:20 +0000827 // We have a non-null base. These are generally known to be true, but if it's
828 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000829 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000830 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000831 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000832}
833
Richard Smith0b0a0b62011-10-29 20:57:55 +0000834static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000835 switch (Val.getKind()) {
836 case APValue::Uninitialized:
837 return false;
838 case APValue::Int:
839 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000840 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000841 case APValue::Float:
842 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000843 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000844 case APValue::ComplexInt:
845 Result = Val.getComplexIntReal().getBoolValue() ||
846 Val.getComplexIntImag().getBoolValue();
847 return true;
848 case APValue::ComplexFloat:
849 Result = !Val.getComplexFloatReal().isZero() ||
850 !Val.getComplexFloatImag().isZero();
851 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000852 case APValue::LValue:
853 return EvalPointerValueAsBool(Val, Result);
854 case APValue::MemberPointer:
855 Result = Val.getMemberPointerDecl();
856 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000857 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000858 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000859 case APValue::Struct:
860 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000861 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +0000862 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000863 }
864
Richard Smith11562c52011-10-28 17:51:58 +0000865 llvm_unreachable("unknown APValue kind");
866}
867
868static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
869 EvalInfo &Info) {
870 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000871 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000872 if (!Evaluate(Val, Info, E))
873 return false;
874 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000875}
876
Richard Smith357362d2011-12-13 06:39:58 +0000877template<typename T>
878static bool HandleOverflow(EvalInfo &Info, const Expr *E,
879 const T &SrcValue, QualType DestType) {
880 llvm::SmallVector<char, 32> Buffer;
881 SrcValue.toString(Buffer);
882 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
883 << StringRef(Buffer.data(), Buffer.size()) << DestType;
884 return false;
885}
886
887static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
888 QualType SrcType, const APFloat &Value,
889 QualType DestType, APSInt &Result) {
890 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000891 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000892 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000893
Richard Smith357362d2011-12-13 06:39:58 +0000894 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000895 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000896 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
897 & APFloat::opInvalidOp)
898 return HandleOverflow(Info, E, Value, DestType);
899 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000900}
901
Richard Smith357362d2011-12-13 06:39:58 +0000902static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
903 QualType SrcType, QualType DestType,
904 APFloat &Result) {
905 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000906 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000907 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
908 APFloat::rmNearestTiesToEven, &ignored)
909 & APFloat::opOverflow)
910 return HandleOverflow(Info, E, Value, DestType);
911 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000912}
913
Mike Stump11289f42009-09-09 15:08:12 +0000914static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000915 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000916 unsigned DestWidth = Ctx.getIntWidth(DestType);
917 APSInt Result = Value;
918 // Figure out if this is a truncate, extend or noop cast.
919 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000920 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000921 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000922 return Result;
923}
924
Richard Smith357362d2011-12-13 06:39:58 +0000925static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
926 QualType SrcType, const APSInt &Value,
927 QualType DestType, APFloat &Result) {
928 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
929 if (Result.convertFromAPInt(Value, Value.isSigned(),
930 APFloat::rmNearestTiesToEven)
931 & APFloat::opOverflow)
932 return HandleOverflow(Info, E, Value, DestType);
933 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000934}
935
Eli Friedman803acb32011-12-22 03:51:45 +0000936static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
937 llvm::APInt &Res) {
938 CCValue SVal;
939 if (!Evaluate(SVal, Info, E))
940 return false;
941 if (SVal.isInt()) {
942 Res = SVal.getInt();
943 return true;
944 }
945 if (SVal.isFloat()) {
946 Res = SVal.getFloat().bitcastToAPInt();
947 return true;
948 }
949 if (SVal.isVector()) {
950 QualType VecTy = E->getType();
951 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
952 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
953 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
954 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
955 Res = llvm::APInt::getNullValue(VecSize);
956 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
957 APValue &Elt = SVal.getVectorElt(i);
958 llvm::APInt EltAsInt;
959 if (Elt.isInt()) {
960 EltAsInt = Elt.getInt();
961 } else if (Elt.isFloat()) {
962 EltAsInt = Elt.getFloat().bitcastToAPInt();
963 } else {
964 // Don't try to handle vectors of anything other than int or float
965 // (not sure if it's possible to hit this case).
966 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
967 return false;
968 }
969 unsigned BaseEltSize = EltAsInt.getBitWidth();
970 if (BigEndian)
971 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
972 else
973 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
974 }
975 return true;
976 }
977 // Give up if the input isn't an int, float, or vector. For example, we
978 // reject "(v4i16)(intptr_t)&a".
979 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
980 return false;
981}
982
Richard Smith027bf112011-11-17 22:56:20 +0000983static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
984 const CXXRecordDecl *&MostDerivedType,
985 unsigned &MostDerivedPathLength,
986 bool &MostDerivedIsArrayElement) {
987 const SubobjectDesignator &D = LVal.Designator;
988 if (D.Invalid || !LVal.Base)
Richard Smithd62306a2011-11-10 06:34:14 +0000989 return false;
990
Richard Smith027bf112011-11-17 22:56:20 +0000991 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smithd62306a2011-11-10 06:34:14 +0000992
993 // Find path prefix which leads to the most-derived subobject.
Richard Smithd62306a2011-11-10 06:34:14 +0000994 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smith027bf112011-11-17 22:56:20 +0000995 MostDerivedPathLength = 0;
996 MostDerivedIsArrayElement = false;
Richard Smithd62306a2011-11-10 06:34:14 +0000997
998 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
999 bool IsArray = T && T->isArrayType();
1000 if (IsArray)
1001 T = T->getBaseElementTypeUnsafe();
1002 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
1003 T = FD->getType().getTypePtr();
1004 else
1005 T = 0;
1006
1007 if (T) {
1008 MostDerivedType = T->getAsCXXRecordDecl();
1009 MostDerivedPathLength = I + 1;
1010 MostDerivedIsArrayElement = IsArray;
1011 }
1012 }
1013
Richard Smithd62306a2011-11-10 06:34:14 +00001014 // (B*)&d + 1 has no most-derived object.
1015 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
1016 return false;
1017
Richard Smith027bf112011-11-17 22:56:20 +00001018 return MostDerivedType != 0;
1019}
1020
1021static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
1022 const RecordDecl *TruncatedType,
1023 unsigned TruncatedElements,
1024 bool IsArrayElement) {
1025 SubobjectDesignator &D = Result.Designator;
1026 const RecordDecl *RD = TruncatedType;
1027 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +00001028 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1029 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001030 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001031 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001032 else
Richard Smithd62306a2011-11-10 06:34:14 +00001033 Result.Offset -= Layout.getBaseClassOffset(Base);
1034 RD = Base;
1035 }
Richard Smith027bf112011-11-17 22:56:20 +00001036 D.Entries.resize(TruncatedElements);
1037 D.ArrayElement = IsArrayElement;
1038}
1039
1040/// If the given LValue refers to a base subobject of some object, find the most
1041/// derived object and the corresponding complete record type. This is necessary
1042/// in order to find the offset of a virtual base class.
1043static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
1044 const CXXRecordDecl *&MostDerivedType) {
1045 unsigned MostDerivedPathLength;
1046 bool MostDerivedIsArrayElement;
1047 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1048 MostDerivedPathLength, MostDerivedIsArrayElement))
1049 return false;
1050
1051 // Remove the trailing base class path entries and their offsets.
1052 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
1053 MostDerivedIsArrayElement);
Richard Smithd62306a2011-11-10 06:34:14 +00001054 return true;
1055}
1056
1057static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
1058 const CXXRecordDecl *Derived,
1059 const CXXRecordDecl *Base,
1060 const ASTRecordLayout *RL = 0) {
1061 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1062 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1063 Obj.Designator.addDecl(Base, /*Virtual*/ false);
1064}
1065
1066static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
1067 const CXXRecordDecl *DerivedDecl,
1068 const CXXBaseSpecifier *Base) {
1069 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1070
1071 if (!Base->isVirtual()) {
1072 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
1073 return true;
1074 }
1075
1076 // Extract most-derived object and corresponding type.
1077 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
1078 return false;
1079
1080 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1081 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1082 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
1083 return true;
1084}
1085
1086/// Update LVal to refer to the given field, which must be a member of the type
1087/// currently described by LVal.
1088static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
1089 const FieldDecl *FD,
1090 const ASTRecordLayout *RL = 0) {
1091 if (!RL)
1092 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1093
1094 unsigned I = FD->getFieldIndex();
1095 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1096 LVal.Designator.addDecl(FD);
1097}
1098
1099/// Get the size of the given type in char units.
1100static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1101 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1102 // extension.
1103 if (Type->isVoidType() || Type->isFunctionType()) {
1104 Size = CharUnits::One();
1105 return true;
1106 }
1107
1108 if (!Type->isConstantSizeType()) {
1109 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1110 return false;
1111 }
1112
1113 Size = Info.Ctx.getTypeSizeInChars(Type);
1114 return true;
1115}
1116
1117/// Update a pointer value to model pointer arithmetic.
1118/// \param Info - Information about the ongoing evaluation.
1119/// \param LVal - The pointer value to be updated.
1120/// \param EltTy - The pointee type represented by LVal.
1121/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1122static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
1123 QualType EltTy, int64_t Adjustment) {
1124 CharUnits SizeOfPointee;
1125 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1126 return false;
1127
1128 // Compute the new offset in the appropriate width.
1129 LVal.Offset += Adjustment * SizeOfPointee;
1130 LVal.Designator.adjustIndex(Adjustment);
1131 return true;
1132}
1133
Richard Smith27908702011-10-24 17:54:18 +00001134/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001135static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1136 const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +00001137 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001138 // If this is a parameter to an active constexpr function call, perform
1139 // argument substitution.
1140 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001141 if (!Frame || !Frame->Arguments) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001142 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001143 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001144 }
Richard Smithfec09922011-11-01 16:57:24 +00001145 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1146 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001147 }
Richard Smith27908702011-10-24 17:54:18 +00001148
Richard Smithd0b4dd62011-12-19 06:19:21 +00001149 // Dig out the initializer, and use the declaration which it's attached to.
1150 const Expr *Init = VD->getAnyInitializer(VD);
1151 if (!Init || Init->isValueDependent()) {
1152 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1153 return false;
1154 }
1155
Richard Smithd62306a2011-11-10 06:34:14 +00001156 // If we're currently evaluating the initializer of this declaration, use that
1157 // in-flight value.
1158 if (Info.EvaluatingDecl == VD) {
1159 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
1160 return !Result.isUninit();
1161 }
1162
Richard Smithcecf1842011-11-01 21:06:14 +00001163 // Never evaluate the initializer of a weak variable. We can't be sure that
1164 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001165 if (VD->isWeak()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001166 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001167 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001168 }
Richard Smithcecf1842011-11-01 21:06:14 +00001169
Richard Smithd0b4dd62011-12-19 06:19:21 +00001170 // Check that we can fold the initializer. In C++, we will have already done
1171 // this in the cases where it matters for conformance.
1172 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1173 if (!VD->evaluateValue(Notes)) {
1174 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1175 Notes.size() + 1) << VD;
1176 Info.Note(VD->getLocation(), diag::note_declared_at);
1177 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001178 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001179 } else if (!VD->checkInitIsICE()) {
1180 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1181 Notes.size() + 1) << VD;
1182 Info.Note(VD->getLocation(), diag::note_declared_at);
1183 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001184 }
Richard Smith27908702011-10-24 17:54:18 +00001185
Richard Smithd0b4dd62011-12-19 06:19:21 +00001186 Result = CCValue(*VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +00001187 return true;
Richard Smith27908702011-10-24 17:54:18 +00001188}
1189
Richard Smith11562c52011-10-28 17:51:58 +00001190static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001191 Qualifiers Quals = T.getQualifiers();
1192 return Quals.hasConst() && !Quals.hasVolatile();
1193}
1194
Richard Smithe97cbd72011-11-11 04:05:33 +00001195/// Get the base index of the given base class within an APValue representing
1196/// the given derived class.
1197static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1198 const CXXRecordDecl *Base) {
1199 Base = Base->getCanonicalDecl();
1200 unsigned Index = 0;
1201 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1202 E = Derived->bases_end(); I != E; ++I, ++Index) {
1203 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1204 return Index;
1205 }
1206
1207 llvm_unreachable("base class missing from derived class's bases list");
1208}
1209
Richard Smithf3e9e432011-11-07 09:22:26 +00001210/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001211static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1212 CCValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001213 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001214 if (Sub.Invalid) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001215 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001216 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001217 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001218 if (Sub.OnePastTheEnd) {
1219 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001220 (unsigned)diag::note_constexpr_read_past_end :
1221 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001222 return false;
1223 }
Richard Smith6804be52011-11-11 08:28:03 +00001224 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001225 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +00001226
1227 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1228 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001229 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001230 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001231 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001232 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001233 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001234 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001235 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001236 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001237 // Note, it should not be possible to form a pointer with a valid
1238 // designator which points more than one past the end of the array.
1239 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001240 (unsigned)diag::note_constexpr_read_past_end :
1241 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001242 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001243 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001244 if (O->getArrayInitializedElts() > Index)
1245 O = &O->getArrayInitializedElt(Index);
1246 else
1247 O = &O->getArrayFiller();
1248 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +00001249 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1250 // Next subobject is a class, struct or union field.
1251 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1252 if (RD->isUnion()) {
1253 const FieldDecl *UnionField = O->getUnionField();
1254 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001255 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001256 Info.Diag(E->getExprLoc(),
1257 diag::note_constexpr_read_inactive_union_member)
1258 << Field << !UnionField << UnionField;
Richard Smithd62306a2011-11-10 06:34:14 +00001259 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001260 }
Richard Smithd62306a2011-11-10 06:34:14 +00001261 O = &O->getUnionValue();
1262 } else
1263 O = &O->getStructField(Field->getFieldIndex());
1264 ObjType = Field->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001265
1266 if (ObjType.isVolatileQualified()) {
1267 if (Info.getLangOpts().CPlusPlus) {
1268 // FIXME: Include a description of the path to the volatile subobject.
1269 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1270 << 2 << Field;
1271 Info.Note(Field->getLocation(), diag::note_declared_at);
1272 } else {
1273 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1274 }
1275 return false;
1276 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001277 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001278 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001279 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1280 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1281 O = &O->getStructBase(getBaseIndex(Derived, Base));
1282 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001283 }
Richard Smithd62306a2011-11-10 06:34:14 +00001284
Richard Smithf57d8cb2011-12-09 22:58:01 +00001285 if (O->isUninit()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001286 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smithd62306a2011-11-10 06:34:14 +00001287 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001288 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001289 }
1290
Richard Smithf3e9e432011-11-07 09:22:26 +00001291 Obj = CCValue(*O, CCValue::GlobalValue());
1292 return true;
1293}
1294
Richard Smithd62306a2011-11-10 06:34:14 +00001295/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1296/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1297/// for looking up the glvalue referred to by an entity of reference type.
1298///
1299/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001300/// \param Conv - The expression for which we are performing the conversion.
1301/// Used for diagnostics.
Richard Smithd62306a2011-11-10 06:34:14 +00001302/// \param Type - The type we expect this conversion to produce.
1303/// \param LVal - The glvalue on which we are attempting to perform this action.
1304/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001305static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1306 QualType Type,
Richard Smithf3e9e432011-11-07 09:22:26 +00001307 const LValue &LVal, CCValue &RVal) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001308 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1309 if (!Info.getLangOpts().CPlusPlus)
1310 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1311
Richard Smithce40ad62011-11-12 22:28:03 +00001312 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001313 CallStackFrame *Frame = LVal.Frame;
Richard Smithf2b681b2011-12-21 05:04:46 +00001314 SourceLocation Loc = Conv->getExprLoc();
Richard Smith11562c52011-10-28 17:51:58 +00001315
Richard Smithf57d8cb2011-12-09 22:58:01 +00001316 if (!LVal.Base) {
1317 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithf2b681b2011-12-21 05:04:46 +00001318 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1319 return false;
1320 }
1321
1322 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1323 // is not a constant expression (even if the object is non-volatile). We also
1324 // apply this rule to C++98, in order to conform to the expected 'volatile'
1325 // semantics.
1326 if (Type.isVolatileQualified()) {
1327 if (Info.getLangOpts().CPlusPlus)
1328 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1329 else
1330 Info.Diag(Loc);
Richard Smith11562c52011-10-28 17:51:58 +00001331 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001332 }
Richard Smith11562c52011-10-28 17:51:58 +00001333
Richard Smithce40ad62011-11-12 22:28:03 +00001334 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001335 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1336 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001337 // expressions are constant expressions too. Inside constexpr functions,
1338 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001339 // In C, such things can also be folded, although they are not ICEs.
Richard Smith11562c52011-10-28 17:51:58 +00001340 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001341 if (!VD || VD->isInvalidDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001342 Info.Diag(Loc);
Richard Smith96e0c102011-11-04 02:25:55 +00001343 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001344 }
1345
Richard Smithf2b681b2011-12-21 05:04:46 +00001346 // DR1313: If the object is volatile-qualified but the glvalue was not,
1347 // behavior is undefined so the result is not a constant expression.
Richard Smithce40ad62011-11-12 22:28:03 +00001348 QualType VT = VD->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001349 if (VT.isVolatileQualified()) {
1350 if (Info.getLangOpts().CPlusPlus) {
1351 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1352 Info.Note(VD->getLocation(), diag::note_declared_at);
1353 } else {
1354 Info.Diag(Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001355 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001356 return false;
1357 }
1358
1359 if (!isa<ParmVarDecl>(VD)) {
1360 if (VD->isConstexpr()) {
1361 // OK, we can read this variable.
1362 } else if (VT->isIntegralOrEnumerationType()) {
1363 if (!VT.isConstQualified()) {
1364 if (Info.getLangOpts().CPlusPlus) {
1365 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1366 Info.Note(VD->getLocation(), diag::note_declared_at);
1367 } else {
1368 Info.Diag(Loc);
1369 }
1370 return false;
1371 }
1372 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1373 // We support folding of const floating-point types, in order to make
1374 // static const data members of such types (supported as an extension)
1375 // more useful.
1376 if (Info.getLangOpts().CPlusPlus0x) {
1377 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1378 Info.Note(VD->getLocation(), diag::note_declared_at);
1379 } else {
1380 Info.CCEDiag(Loc);
1381 }
1382 } else {
1383 // FIXME: Allow folding of values of any literal type in all languages.
1384 if (Info.getLangOpts().CPlusPlus0x) {
1385 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1386 Info.Note(VD->getLocation(), diag::note_declared_at);
1387 } else {
1388 Info.Diag(Loc);
1389 }
Richard Smith96e0c102011-11-04 02:25:55 +00001390 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001391 }
Richard Smith96e0c102011-11-04 02:25:55 +00001392 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001393
Richard Smithf57d8cb2011-12-09 22:58:01 +00001394 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001395 return false;
1396
Richard Smith0b0a0b62011-10-29 20:57:55 +00001397 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001398 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001399
1400 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1401 // conversion. This happens when the declaration and the lvalue should be
1402 // considered synonymous, for instance when initializing an array of char
1403 // from a string literal. Continue as if the initializer lvalue was the
1404 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001405 assert(RVal.getLValueOffset().isZero() &&
1406 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001407 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001408 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001409 }
1410
Richard Smithf2b681b2011-12-21 05:04:46 +00001411 // Volatile temporary objects cannot be read in constant expressions.
1412 if (Base->getType().isVolatileQualified()) {
1413 if (Info.getLangOpts().CPlusPlus) {
1414 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1415 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1416 } else {
1417 Info.Diag(Loc);
1418 }
1419 return false;
1420 }
1421
Richard Smith96e0c102011-11-04 02:25:55 +00001422 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1423 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1424 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001425 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001426 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001427 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001428 }
Richard Smith96e0c102011-11-04 02:25:55 +00001429
1430 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001431 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf2b681b2011-12-21 05:04:46 +00001432 const ConstantArrayType *CAT =
1433 Info.Ctx.getAsConstantArrayType(S->getType());
1434 if (Index >= CAT->getSize().getZExtValue()) {
1435 // Note, it should not be possible to form a pointer which points more
1436 // than one past the end of the array without producing a prior const expr
1437 // diagnostic.
1438 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith96e0c102011-11-04 02:25:55 +00001439 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001440 }
Richard Smith96e0c102011-11-04 02:25:55 +00001441 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1442 Type->isUnsignedIntegerType());
1443 if (Index < S->getLength())
1444 Value = S->getCodeUnit(Index);
1445 RVal = CCValue(Value);
1446 return true;
1447 }
1448
Richard Smithf3e9e432011-11-07 09:22:26 +00001449 if (Frame) {
1450 // If this is a temporary expression with a nontrivial initializer, grab the
1451 // value from the relevant stack frame.
1452 RVal = Frame->Temporaries[Base];
1453 } else if (const CompoundLiteralExpr *CLE
1454 = dyn_cast<CompoundLiteralExpr>(Base)) {
1455 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1456 // initializer until now for such expressions. Such an expression can't be
1457 // an ICE in C, so this only matters for fold.
1458 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1459 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1460 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001461 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00001462 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001463 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001464 }
Richard Smith96e0c102011-11-04 02:25:55 +00001465
Richard Smithf57d8cb2011-12-09 22:58:01 +00001466 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1467 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001468}
1469
Richard Smithe97cbd72011-11-11 04:05:33 +00001470/// Build an lvalue for the object argument of a member function call.
1471static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1472 LValue &This) {
1473 if (Object->getType()->isPointerType())
1474 return EvaluatePointer(Object, This, Info);
1475
1476 if (Object->isGLValue())
1477 return EvaluateLValue(Object, This, Info);
1478
Richard Smith027bf112011-11-17 22:56:20 +00001479 if (Object->getType()->isLiteralType())
1480 return EvaluateTemporary(Object, This, Info);
1481
1482 return false;
1483}
1484
1485/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1486/// lvalue referring to the result.
1487///
1488/// \param Info - Information about the ongoing evaluation.
1489/// \param BO - The member pointer access operation.
1490/// \param LV - Filled in with a reference to the resulting object.
1491/// \param IncludeMember - Specifies whether the member itself is included in
1492/// the resulting LValue subobject designator. This is not possible when
1493/// creating a bound member function.
1494/// \return The field or method declaration to which the member pointer refers,
1495/// or 0 if evaluation fails.
1496static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1497 const BinaryOperator *BO,
1498 LValue &LV,
1499 bool IncludeMember = true) {
1500 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1501
1502 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1503 return 0;
1504
1505 MemberPtr MemPtr;
1506 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1507 return 0;
1508
1509 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1510 // member value, the behavior is undefined.
1511 if (!MemPtr.getDecl())
1512 return 0;
1513
1514 if (MemPtr.isDerivedMember()) {
1515 // This is a member of some derived class. Truncate LV appropriately.
1516 const CXXRecordDecl *MostDerivedType;
1517 unsigned MostDerivedPathLength;
1518 bool MostDerivedIsArrayElement;
1519 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1520 MostDerivedIsArrayElement))
1521 return 0;
1522
1523 // The end of the derived-to-base path for the base object must match the
1524 // derived-to-base path for the member pointer.
1525 if (MostDerivedPathLength + MemPtr.Path.size() >
1526 LV.Designator.Entries.size())
1527 return 0;
1528 unsigned PathLengthToMember =
1529 LV.Designator.Entries.size() - MemPtr.Path.size();
1530 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1531 const CXXRecordDecl *LVDecl = getAsBaseClass(
1532 LV.Designator.Entries[PathLengthToMember + I]);
1533 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1534 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1535 return 0;
1536 }
1537
1538 // Truncate the lvalue to the appropriate derived class.
1539 bool ResultIsArray = false;
1540 if (PathLengthToMember == MostDerivedPathLength)
1541 ResultIsArray = MostDerivedIsArrayElement;
1542 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1543 PathLengthToMember, ResultIsArray);
1544 } else if (!MemPtr.Path.empty()) {
1545 // Extend the LValue path with the member pointer's path.
1546 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1547 MemPtr.Path.size() + IncludeMember);
1548
1549 // Walk down to the appropriate base class.
1550 QualType LVType = BO->getLHS()->getType();
1551 if (const PointerType *PT = LVType->getAs<PointerType>())
1552 LVType = PT->getPointeeType();
1553 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1554 assert(RD && "member pointer access on non-class-type expression");
1555 // The first class in the path is that of the lvalue.
1556 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1557 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1558 HandleLValueDirectBase(Info, LV, RD, Base);
1559 RD = Base;
1560 }
1561 // Finally cast to the class containing the member.
1562 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1563 }
1564
1565 // Add the member. Note that we cannot build bound member functions here.
1566 if (IncludeMember) {
1567 // FIXME: Deal with IndirectFieldDecls.
1568 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1569 if (!FD) return 0;
1570 HandleLValueMember(Info, LV, FD);
1571 }
1572
1573 return MemPtr.getDecl();
1574}
1575
1576/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1577/// the provided lvalue, which currently refers to the base object.
1578static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1579 LValue &Result) {
1580 const CXXRecordDecl *MostDerivedType;
1581 unsigned MostDerivedPathLength;
1582 bool MostDerivedIsArrayElement;
1583
1584 // Check this cast doesn't take us outside the object.
1585 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1586 MostDerivedPathLength,
1587 MostDerivedIsArrayElement))
1588 return false;
1589 SubobjectDesignator &D = Result.Designator;
1590 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1591 return false;
1592
1593 // Check the type of the final cast. We don't need to check the path,
1594 // since a cast can only be formed if the path is unique.
1595 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1596 bool ResultIsArray = false;
1597 QualType TargetQT = E->getType();
1598 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1599 TargetQT = PT->getPointeeType();
1600 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1601 const CXXRecordDecl *FinalType;
1602 if (NewEntriesSize == MostDerivedPathLength) {
1603 ResultIsArray = MostDerivedIsArrayElement;
1604 FinalType = MostDerivedType;
1605 } else
1606 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1607 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1608 return false;
1609
1610 // Truncate the lvalue to the appropriate derived class.
1611 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1612 ResultIsArray);
1613 return true;
Richard Smithe97cbd72011-11-11 04:05:33 +00001614}
1615
Mike Stump876387b2009-10-27 22:09:17 +00001616namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001617enum EvalStmtResult {
1618 /// Evaluation failed.
1619 ESR_Failed,
1620 /// Hit a 'return' statement.
1621 ESR_Returned,
1622 /// Evaluation succeeded.
1623 ESR_Succeeded
1624};
1625}
1626
1627// Evaluate a statement.
Richard Smith357362d2011-12-13 06:39:58 +00001628static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001629 const Stmt *S) {
1630 switch (S->getStmtClass()) {
1631 default:
1632 return ESR_Failed;
1633
1634 case Stmt::NullStmtClass:
1635 case Stmt::DeclStmtClass:
1636 return ESR_Succeeded;
1637
Richard Smith357362d2011-12-13 06:39:58 +00001638 case Stmt::ReturnStmtClass: {
1639 CCValue CCResult;
1640 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1641 if (!Evaluate(CCResult, Info, RetExpr) ||
1642 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1643 CCEK_ReturnValue))
1644 return ESR_Failed;
1645 return ESR_Returned;
1646 }
Richard Smith254a73d2011-10-28 22:34:42 +00001647
1648 case Stmt::CompoundStmtClass: {
1649 const CompoundStmt *CS = cast<CompoundStmt>(S);
1650 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1651 BE = CS->body_end(); BI != BE; ++BI) {
1652 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1653 if (ESR != ESR_Succeeded)
1654 return ESR;
1655 }
1656 return ESR_Succeeded;
1657 }
1658 }
1659}
1660
Richard Smithcc36f692011-12-22 02:22:31 +00001661/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1662/// default constructor. If so, we'll fold it whether or not it's marked as
1663/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1664/// so we need special handling.
1665static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00001666 const CXXConstructorDecl *CD,
1667 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00001668 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1669 return false;
1670
1671 if (!CD->isConstexpr()) {
1672 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smithfddd3842011-12-30 21:15:51 +00001673 // Value-initialization does not call a trivial default constructor, so
1674 // such a call is a core constant expression whether or not the
1675 // constructor is constexpr.
1676 if (!IsValueInitialization) {
1677 // FIXME: If DiagDecl is an implicitly-declared special member function,
1678 // we should be much more explicit about why it's not constexpr.
1679 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1680 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1681 Info.Note(CD->getLocation(), diag::note_declared_at);
1682 }
Richard Smithcc36f692011-12-22 02:22:31 +00001683 } else {
1684 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1685 }
1686 }
1687 return true;
1688}
1689
Richard Smith357362d2011-12-13 06:39:58 +00001690/// CheckConstexprFunction - Check that a function can be called in a constant
1691/// expression.
1692static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1693 const FunctionDecl *Declaration,
1694 const FunctionDecl *Definition) {
1695 // Can we evaluate this function call?
1696 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1697 return true;
1698
1699 if (Info.getLangOpts().CPlusPlus0x) {
1700 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001701 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1702 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00001703 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1704 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1705 << DiagDecl;
1706 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1707 } else {
1708 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1709 }
1710 return false;
1711}
1712
Richard Smithd62306a2011-11-10 06:34:14 +00001713namespace {
Richard Smith60494462011-11-11 05:48:57 +00001714typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001715}
1716
1717/// EvaluateArgs - Evaluate the arguments to a function call.
1718static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1719 EvalInfo &Info) {
1720 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1721 I != E; ++I)
1722 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1723 return false;
1724 return true;
1725}
1726
Richard Smith254a73d2011-10-28 22:34:42 +00001727/// Evaluate a function call.
Richard Smithf6f003a2011-12-16 19:06:07 +00001728static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1729 const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00001730 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith357362d2011-12-13 06:39:58 +00001731 EvalInfo &Info, APValue &Result) {
1732 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith254a73d2011-10-28 22:34:42 +00001733 return false;
1734
Richard Smithd62306a2011-11-10 06:34:14 +00001735 ArgVector ArgValues(Args.size());
1736 if (!EvaluateArgs(Args, ArgValues, Info))
1737 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001738
Richard Smithf6f003a2011-12-16 19:06:07 +00001739 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1740 ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001741 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1742}
1743
Richard Smithd62306a2011-11-10 06:34:14 +00001744/// Evaluate a constructor call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001745static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00001746 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001747 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00001748 EvalInfo &Info, APValue &Result) {
Richard Smith357362d2011-12-13 06:39:58 +00001749 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd62306a2011-11-10 06:34:14 +00001750 return false;
1751
1752 ArgVector ArgValues(Args.size());
1753 if (!EvaluateArgs(Args, ArgValues, Info))
1754 return false;
1755
Richard Smithf6f003a2011-12-16 19:06:07 +00001756 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1757 &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00001758
1759 // If it's a delegating constructor, just delegate.
1760 if (Definition->isDelegatingConstructor()) {
1761 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1762 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1763 }
1764
1765 // Reserve space for the struct members.
1766 const CXXRecordDecl *RD = Definition->getParent();
Richard Smithfddd3842011-12-30 21:15:51 +00001767 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00001768 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1769 std::distance(RD->field_begin(), RD->field_end()));
1770
1771 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1772
1773 unsigned BasesSeen = 0;
1774#ifndef NDEBUG
1775 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1776#endif
1777 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1778 E = Definition->init_end(); I != E; ++I) {
1779 if ((*I)->isBaseInitializer()) {
1780 QualType BaseType((*I)->getBaseClass(), 0);
1781#ifndef NDEBUG
1782 // Non-virtual base classes are initialized in the order in the class
1783 // definition. We cannot have a virtual base class for a literal type.
1784 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1785 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1786 "base class initializers not in expected order");
1787 ++BaseIt;
1788#endif
1789 LValue Subobject = This;
1790 HandleLValueDirectBase(Info, Subobject, RD,
1791 BaseType->getAsCXXRecordDecl(), &Layout);
1792 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1793 Subobject, (*I)->getInit()))
1794 return false;
1795 } else if (FieldDecl *FD = (*I)->getMember()) {
1796 LValue Subobject = This;
1797 HandleLValueMember(Info, Subobject, FD, &Layout);
1798 if (RD->isUnion()) {
1799 Result = APValue(FD);
Richard Smith357362d2011-12-13 06:39:58 +00001800 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1801 (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001802 return false;
1803 } else if (!EvaluateConstantExpression(
1804 Result.getStructField(FD->getFieldIndex()),
Richard Smith357362d2011-12-13 06:39:58 +00001805 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001806 return false;
1807 } else {
1808 // FIXME: handle indirect field initializers
Richard Smith92b1ce02011-12-12 09:28:41 +00001809 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf57d8cb2011-12-09 22:58:01 +00001810 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001811 return false;
1812 }
1813 }
1814
1815 return true;
1816}
1817
Richard Smith254a73d2011-10-28 22:34:42 +00001818namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001819class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001820 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001821 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001822public:
1823
Richard Smith725810a2011-10-16 21:26:27 +00001824 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001825
1826 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001827 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001828 return true;
1829 }
1830
Peter Collingbournee9200682011-05-13 03:29:01 +00001831 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1832 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001833 return Visit(E->getResultExpr());
1834 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001835 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001836 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001837 return true;
1838 return false;
1839 }
John McCall31168b02011-06-15 23:02:42 +00001840 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001841 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001842 return true;
1843 return false;
1844 }
1845 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001846 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001847 return true;
1848 return false;
1849 }
1850
Mike Stump876387b2009-10-27 22:09:17 +00001851 // We don't want to evaluate BlockExprs multiple times, as they generate
1852 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001853 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1854 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1855 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001856 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001857 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1858 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1859 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1860 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1861 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1862 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001863 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001864 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001865 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001866 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001867 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001868 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1869 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1870 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1871 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001872 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001873 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1874 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1875 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1876 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1877 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001878 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001879 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001880 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001881 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001882 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001883
1884 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001885 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001886 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1887 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001888 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001889 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001890 return false;
1891 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001892
Peter Collingbournee9200682011-05-13 03:29:01 +00001893 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001894};
1895
John McCallc07a0c72011-02-17 10:25:35 +00001896class OpaqueValueEvaluation {
1897 EvalInfo &info;
1898 OpaqueValueExpr *opaqueValue;
1899
1900public:
1901 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1902 Expr *value)
1903 : info(info), opaqueValue(opaqueValue) {
1904
1905 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00001906 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00001907 this->opaqueValue = 0;
1908 return;
1909 }
John McCallc07a0c72011-02-17 10:25:35 +00001910 }
1911
1912 bool hasError() const { return opaqueValue == 0; }
1913
1914 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00001915 // FIXME: This will not work for recursive constexpr functions using opaque
1916 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00001917 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1918 }
1919};
1920
Mike Stump876387b2009-10-27 22:09:17 +00001921} // end anonymous namespace
1922
Eli Friedman9a156e52008-11-12 09:44:48 +00001923//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00001924// Generic Evaluation
1925//===----------------------------------------------------------------------===//
1926namespace {
1927
Richard Smithf57d8cb2011-12-09 22:58:01 +00001928// FIXME: RetTy is always bool. Remove it.
1929template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00001930class ExprEvaluatorBase
1931 : public ConstStmtVisitor<Derived, RetTy> {
1932private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001933 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001934 return static_cast<Derived*>(this)->Success(V, E);
1935 }
Richard Smithfddd3842011-12-30 21:15:51 +00001936 RetTy DerivedZeroInitialization(const Expr *E) {
1937 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00001938 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001939
1940protected:
1941 EvalInfo &Info;
1942 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1943 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1944
Richard Smith92b1ce02011-12-12 09:28:41 +00001945 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith187ef012011-12-12 09:41:58 +00001946 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001947 }
1948
1949 /// Report an evaluation error. This should only be called when an error is
1950 /// first discovered. When propagating an error, just return false.
1951 bool Error(const Expr *E, diag::kind D) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001952 Info.Diag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001953 return false;
1954 }
1955 bool Error(const Expr *E) {
1956 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1957 }
1958
Richard Smithfddd3842011-12-30 21:15:51 +00001959 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00001960
Peter Collingbournee9200682011-05-13 03:29:01 +00001961public:
1962 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1963
1964 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00001965 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00001966 }
1967 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001968 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001969 }
1970
1971 RetTy VisitParenExpr(const ParenExpr *E)
1972 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1973 RetTy VisitUnaryExtension(const UnaryOperator *E)
1974 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1975 RetTy VisitUnaryPlus(const UnaryOperator *E)
1976 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1977 RetTy VisitChooseExpr(const ChooseExpr *E)
1978 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1979 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1980 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00001981 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1982 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00001983 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1984 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00001985 // We cannot create any objects for which cleanups are required, so there is
1986 // nothing to do here; all cleanups must come from unevaluated subexpressions.
1987 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
1988 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001989
Richard Smith6d6ecc32011-12-12 12:46:16 +00001990 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1991 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1992 return static_cast<Derived*>(this)->VisitCastExpr(E);
1993 }
1994 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1995 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1996 return static_cast<Derived*>(this)->VisitCastExpr(E);
1997 }
1998
Richard Smith027bf112011-11-17 22:56:20 +00001999 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2000 switch (E->getOpcode()) {
2001 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00002002 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002003
2004 case BO_Comma:
2005 VisitIgnoredValue(E->getLHS());
2006 return StmtVisitorTy::Visit(E->getRHS());
2007
2008 case BO_PtrMemD:
2009 case BO_PtrMemI: {
2010 LValue Obj;
2011 if (!HandleMemberPointerAccess(Info, E, Obj))
2012 return false;
2013 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002014 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00002015 return false;
2016 return DerivedSuccess(Result, E);
2017 }
2018 }
2019 }
2020
Peter Collingbournee9200682011-05-13 03:29:01 +00002021 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2022 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2023 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002024 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002025
2026 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00002027 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002028 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002029
2030 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2031 }
2032
2033 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2034 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002035 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002036 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002037
Richard Smith11562c52011-10-28 17:51:58 +00002038 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00002039 return StmtVisitorTy::Visit(EvalExpr);
2040 }
2041
2042 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002043 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002044 if (!Value) {
2045 const Expr *Source = E->getSourceExpr();
2046 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002047 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002048 if (Source == E) { // sanity checking.
2049 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00002050 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002051 }
2052 return StmtVisitorTy::Visit(Source);
2053 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00002054 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002055 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002056
Richard Smith254a73d2011-10-28 22:34:42 +00002057 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002058 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00002059 QualType CalleeType = Callee->getType();
2060
Richard Smith254a73d2011-10-28 22:34:42 +00002061 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00002062 LValue *This = 0, ThisVal;
2063 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00002064
Richard Smithe97cbd72011-11-11 04:05:33 +00002065 // Extract function decl and 'this' pointer from the callee.
2066 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002067 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00002068 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2069 // Explicit bound member calls, such as x.f() or p->g();
2070 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002071 return false;
2072 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002073 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002074 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2075 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00002076 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2077 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00002078 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002079 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002080 return Error(Callee);
2081
2082 FD = dyn_cast<FunctionDecl>(Member);
2083 if (!FD)
2084 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002085 } else if (CalleeType->isFunctionPointerType()) {
2086 CCValue Call;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002087 if (!Evaluate(Call, Info, Callee))
2088 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00002089
Richard Smithf57d8cb2011-12-09 22:58:01 +00002090 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
2091 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00002092 FD = dyn_cast_or_null<FunctionDecl>(
2093 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00002094 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002095 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002096
2097 // Overloaded operator calls to member functions are represented as normal
2098 // calls with '*this' as the first argument.
2099 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2100 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002101 // FIXME: When selecting an implicit conversion for an overloaded
2102 // operator delete, we sometimes try to evaluate calls to conversion
2103 // operators without a 'this' parameter!
2104 if (Args.empty())
2105 return Error(E);
2106
Richard Smithe97cbd72011-11-11 04:05:33 +00002107 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2108 return false;
2109 This = &ThisVal;
2110 Args = Args.slice(1);
2111 }
2112
2113 // Don't call function pointers which have been cast to some other type.
2114 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002115 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002116 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002117 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002118
Richard Smith357362d2011-12-13 06:39:58 +00002119 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002120 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00002121 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002122
Richard Smith357362d2011-12-13 06:39:58 +00002123 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smithf6f003a2011-12-16 19:06:07 +00002124 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002125 return false;
2126
2127 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00002128 }
2129
Richard Smith11562c52011-10-28 17:51:58 +00002130 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2131 return StmtVisitorTy::Visit(E->getInitializer());
2132 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002133 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00002134 if (E->getNumInits() == 0)
2135 return DerivedZeroInitialization(E);
2136 if (E->getNumInits() == 1)
2137 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00002138 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002139 }
2140 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002141 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002142 }
2143 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002144 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002145 }
Richard Smith027bf112011-11-17 22:56:20 +00002146 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002147 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002148 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002149
Richard Smithd62306a2011-11-10 06:34:14 +00002150 /// A member expression where the object is a prvalue is itself a prvalue.
2151 RetTy VisitMemberExpr(const MemberExpr *E) {
2152 assert(!E->isArrow() && "missing call to bound member function?");
2153
2154 CCValue Val;
2155 if (!Evaluate(Val, Info, E->getBase()))
2156 return false;
2157
2158 QualType BaseTy = E->getBase()->getType();
2159
2160 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002161 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002162 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2163 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2164 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2165
2166 SubobjectDesignator Designator;
2167 Designator.addDecl(FD);
2168
Richard Smithf57d8cb2011-12-09 22:58:01 +00002169 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002170 DerivedSuccess(Val, E);
2171 }
2172
Richard Smith11562c52011-10-28 17:51:58 +00002173 RetTy VisitCastExpr(const CastExpr *E) {
2174 switch (E->getCastKind()) {
2175 default:
2176 break;
2177
2178 case CK_NoOp:
2179 return StmtVisitorTy::Visit(E->getSubExpr());
2180
2181 case CK_LValueToRValue: {
2182 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002183 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2184 return false;
2185 CCValue RVal;
2186 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2187 return false;
2188 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002189 }
2190 }
2191
Richard Smithf57d8cb2011-12-09 22:58:01 +00002192 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002193 }
2194
Richard Smith4a678122011-10-24 18:44:57 +00002195 /// Visit a value which is evaluated, but whose value is ignored.
2196 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002197 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002198 if (!Evaluate(Scratch, Info, E))
2199 Info.EvalStatus.HasSideEffects = true;
2200 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002201};
2202
2203}
2204
2205//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002206// Common base class for lvalue and temporary evaluation.
2207//===----------------------------------------------------------------------===//
2208namespace {
2209template<class Derived>
2210class LValueExprEvaluatorBase
2211 : public ExprEvaluatorBase<Derived, bool> {
2212protected:
2213 LValue &Result;
2214 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2215 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2216
2217 bool Success(APValue::LValueBase B) {
2218 Result.set(B);
2219 return true;
2220 }
2221
2222public:
2223 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2224 ExprEvaluatorBaseTy(Info), Result(Result) {}
2225
2226 bool Success(const CCValue &V, const Expr *E) {
2227 Result.setFrom(V);
2228 return true;
2229 }
Richard Smith027bf112011-11-17 22:56:20 +00002230
2231 bool CheckValidLValue() {
2232 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
2233 // there are no null references, nor once-past-the-end references.
2234 // FIXME: Check for one-past-the-end array indices
2235 return Result.Base && !Result.Designator.Invalid &&
2236 !Result.Designator.OnePastTheEnd;
2237 }
2238
2239 bool VisitMemberExpr(const MemberExpr *E) {
2240 // Handle non-static data members.
2241 QualType BaseTy;
2242 if (E->isArrow()) {
2243 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2244 return false;
2245 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002246 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002247 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002248 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2249 return false;
2250 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002251 } else {
2252 if (!this->Visit(E->getBase()))
2253 return false;
2254 BaseTy = E->getBase()->getType();
2255 }
2256 // FIXME: In C++11, require the result to be a valid lvalue.
2257
2258 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2259 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00002260 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002261 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2262 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2263 (void)BaseTy;
2264
2265 HandleLValueMember(this->Info, Result, FD);
2266
2267 if (FD->getType()->isReferenceType()) {
2268 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002269 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002270 RefValue))
2271 return false;
2272 return Success(RefValue, E);
2273 }
2274 return true;
2275 }
2276
2277 bool VisitBinaryOperator(const BinaryOperator *E) {
2278 switch (E->getOpcode()) {
2279 default:
2280 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2281
2282 case BO_PtrMemD:
2283 case BO_PtrMemI:
2284 return HandleMemberPointerAccess(this->Info, E, Result);
2285 }
2286 }
2287
2288 bool VisitCastExpr(const CastExpr *E) {
2289 switch (E->getCastKind()) {
2290 default:
2291 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2292
2293 case CK_DerivedToBase:
2294 case CK_UncheckedDerivedToBase: {
2295 if (!this->Visit(E->getSubExpr()))
2296 return false;
2297 if (!CheckValidLValue())
2298 return false;
2299
2300 // Now figure out the necessary offset to add to the base LV to get from
2301 // the derived class to the base class.
2302 QualType Type = E->getSubExpr()->getType();
2303
2304 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2305 PathE = E->path_end(); PathI != PathE; ++PathI) {
2306 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2307 *PathI))
2308 return false;
2309 Type = (*PathI)->getType();
2310 }
2311
2312 return true;
2313 }
2314 }
2315 }
2316};
2317}
2318
2319//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002320// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002321//
2322// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2323// function designators (in C), decl references to void objects (in C), and
2324// temporaries (if building with -Wno-address-of-temporary).
2325//
2326// LValue evaluation produces values comprising a base expression of one of the
2327// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002328// - Declarations
2329// * VarDecl
2330// * FunctionDecl
2331// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002332// * CompoundLiteralExpr in C
2333// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00002334// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00002335// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002336// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002337// * ObjCEncodeExpr
2338// * AddrLabelExpr
2339// * BlockExpr
2340// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002341// - Locals and temporaries
2342// * Any Expr, with a Frame indicating the function in which the temporary was
2343// evaluated.
2344// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002345//===----------------------------------------------------------------------===//
2346namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002347class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002348 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002349public:
Richard Smith027bf112011-11-17 22:56:20 +00002350 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2351 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002352
Richard Smith11562c52011-10-28 17:51:58 +00002353 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2354
Peter Collingbournee9200682011-05-13 03:29:01 +00002355 bool VisitDeclRefExpr(const DeclRefExpr *E);
2356 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002357 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002358 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2359 bool VisitMemberExpr(const MemberExpr *E);
2360 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2361 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00002362 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002363 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2364 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002365
Peter Collingbournee9200682011-05-13 03:29:01 +00002366 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002367 switch (E->getCastKind()) {
2368 default:
Richard Smith027bf112011-11-17 22:56:20 +00002369 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002370
Eli Friedmance3e02a2011-10-11 00:13:24 +00002371 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002372 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002373 if (!Visit(E->getSubExpr()))
2374 return false;
2375 Result.Designator.setInvalid();
2376 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002377
Richard Smith027bf112011-11-17 22:56:20 +00002378 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002379 if (!Visit(E->getSubExpr()))
2380 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002381 if (!CheckValidLValue())
2382 return false;
2383 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002384 }
2385 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00002386
Eli Friedman449fe542009-03-23 04:56:01 +00002387 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00002388
Eli Friedman9a156e52008-11-12 09:44:48 +00002389};
2390} // end anonymous namespace
2391
Richard Smith11562c52011-10-28 17:51:58 +00002392/// Evaluate an expression as an lvalue. This can be legitimately called on
2393/// expressions which are not glvalues, in a few cases:
2394/// * function designators in C,
2395/// * "extern void" objects,
2396/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002397static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002398 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2399 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2400 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002401 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002402}
2403
Peter Collingbournee9200682011-05-13 03:29:01 +00002404bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002405 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2406 return Success(FD);
2407 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002408 return VisitVarDecl(E, VD);
2409 return Error(E);
2410}
Richard Smith733237d2011-10-24 23:14:33 +00002411
Richard Smith11562c52011-10-28 17:51:58 +00002412bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002413 if (!VD->getType()->isReferenceType()) {
2414 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002415 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002416 return true;
2417 }
Richard Smithce40ad62011-11-12 22:28:03 +00002418 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002419 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002420
Richard Smith0b0a0b62011-10-29 20:57:55 +00002421 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002422 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2423 return false;
2424 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002425}
2426
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002427bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2428 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002429 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002430 if (E->getType()->isRecordType())
Richard Smith027bf112011-11-17 22:56:20 +00002431 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2432
2433 Result.set(E, Info.CurrentCall);
2434 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2435 Result, E->GetTemporaryExpr());
2436 }
2437
2438 // Materialization of an lvalue temporary occurs when we need to force a copy
2439 // (for instance, if it's a bitfield).
2440 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2441 if (!Visit(E->GetTemporaryExpr()))
2442 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002443 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002444 Info.CurrentCall->Temporaries[E]))
2445 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002446 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002447 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002448}
2449
Peter Collingbournee9200682011-05-13 03:29:01 +00002450bool
2451LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002452 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2453 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2454 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002455 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002456}
2457
Richard Smith6e525142011-12-27 12:18:28 +00002458bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2459 if (E->isTypeOperand())
2460 return Success(E);
2461 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2462 if (RD && RD->isPolymorphic()) {
2463 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2464 << E->getExprOperand()->getType()
2465 << E->getExprOperand()->getSourceRange();
2466 return false;
2467 }
2468 return Success(E);
2469}
2470
Peter Collingbournee9200682011-05-13 03:29:01 +00002471bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002472 // Handle static data members.
2473 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2474 VisitIgnoredValue(E->getBase());
2475 return VisitVarDecl(E, VD);
2476 }
2477
Richard Smith254a73d2011-10-28 22:34:42 +00002478 // Handle static member functions.
2479 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2480 if (MD->isStatic()) {
2481 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002482 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002483 }
2484 }
2485
Richard Smithd62306a2011-11-10 06:34:14 +00002486 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002487 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002488}
2489
Peter Collingbournee9200682011-05-13 03:29:01 +00002490bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002491 // FIXME: Deal with vectors as array subscript bases.
2492 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002493 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002494
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002495 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002496 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002497
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002498 APSInt Index;
2499 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002500 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002501 int64_t IndexValue
2502 = Index.isSigned() ? Index.getSExtValue()
2503 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002504
Richard Smith027bf112011-11-17 22:56:20 +00002505 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002506 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002507}
Eli Friedman9a156e52008-11-12 09:44:48 +00002508
Peter Collingbournee9200682011-05-13 03:29:01 +00002509bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002510 // FIXME: In C++11, require the result to be a valid lvalue.
John McCall45d55e42010-05-07 21:00:08 +00002511 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002512}
2513
Eli Friedman9a156e52008-11-12 09:44:48 +00002514//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002515// Pointer Evaluation
2516//===----------------------------------------------------------------------===//
2517
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002518namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002519class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002520 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002521 LValue &Result;
2522
Peter Collingbournee9200682011-05-13 03:29:01 +00002523 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002524 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002525 return true;
2526 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002527public:
Mike Stump11289f42009-09-09 15:08:12 +00002528
John McCall45d55e42010-05-07 21:00:08 +00002529 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002530 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002531
Richard Smith0b0a0b62011-10-29 20:57:55 +00002532 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002533 Result.setFrom(V);
2534 return true;
2535 }
Richard Smithfddd3842011-12-30 21:15:51 +00002536 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002537 return Success((Expr*)0);
2538 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002539
John McCall45d55e42010-05-07 21:00:08 +00002540 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002541 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002542 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002543 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002544 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002545 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002546 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002547 bool VisitCallExpr(const CallExpr *E);
2548 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002549 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002550 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002551 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002552 }
Richard Smithd62306a2011-11-10 06:34:14 +00002553 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2554 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002555 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002556 Result = *Info.CurrentCall->This;
2557 return true;
2558 }
John McCallc07a0c72011-02-17 10:25:35 +00002559
Eli Friedman449fe542009-03-23 04:56:01 +00002560 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002561};
Chris Lattner05706e882008-07-11 18:11:29 +00002562} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002563
John McCall45d55e42010-05-07 21:00:08 +00002564static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002565 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002566 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002567}
2568
John McCall45d55e42010-05-07 21:00:08 +00002569bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002570 if (E->getOpcode() != BO_Add &&
2571 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002572 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002573
Chris Lattner05706e882008-07-11 18:11:29 +00002574 const Expr *PExp = E->getLHS();
2575 const Expr *IExp = E->getRHS();
2576 if (IExp->getType()->isPointerType())
2577 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002578
John McCall45d55e42010-05-07 21:00:08 +00002579 if (!EvaluatePointer(PExp, Result, Info))
2580 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002581
John McCall45d55e42010-05-07 21:00:08 +00002582 llvm::APSInt Offset;
2583 if (!EvaluateInteger(IExp, Offset, Info))
2584 return false;
2585 int64_t AdditionalOffset
2586 = Offset.isSigned() ? Offset.getSExtValue()
2587 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002588 if (E->getOpcode() == BO_Sub)
2589 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002590
Richard Smithd62306a2011-11-10 06:34:14 +00002591 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith027bf112011-11-17 22:56:20 +00002592 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002593 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002594}
Eli Friedman9a156e52008-11-12 09:44:48 +00002595
John McCall45d55e42010-05-07 21:00:08 +00002596bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2597 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002598}
Mike Stump11289f42009-09-09 15:08:12 +00002599
Peter Collingbournee9200682011-05-13 03:29:01 +00002600bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2601 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002602
Eli Friedman847a2bc2009-12-27 05:43:15 +00002603 switch (E->getCastKind()) {
2604 default:
2605 break;
2606
John McCalle3027922010-08-25 11:45:40 +00002607 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002608 case CK_CPointerToObjCPointerCast:
2609 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002610 case CK_AnyPointerToBlockPointerCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002611 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2612 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2613 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00002614 if (!E->getType()->isVoidPointerType()) {
2615 if (SubExpr->getType()->isVoidPointerType())
2616 CCEDiag(E, diag::note_constexpr_invalid_cast)
2617 << 3 << SubExpr->getType();
2618 else
2619 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2620 }
Richard Smith96e0c102011-11-04 02:25:55 +00002621 if (!Visit(SubExpr))
2622 return false;
2623 Result.Designator.setInvalid();
2624 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002625
Anders Carlsson18275092010-10-31 20:41:46 +00002626 case CK_DerivedToBase:
2627 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002628 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002629 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002630 if (!Result.Base && Result.Offset.isZero())
2631 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002632
Richard Smithd62306a2011-11-10 06:34:14 +00002633 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002634 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002635 QualType Type =
2636 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002637
Richard Smithd62306a2011-11-10 06:34:14 +00002638 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002639 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithd62306a2011-11-10 06:34:14 +00002640 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002641 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002642 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002643 }
2644
Anders Carlsson18275092010-10-31 20:41:46 +00002645 return true;
2646 }
2647
Richard Smith027bf112011-11-17 22:56:20 +00002648 case CK_BaseToDerived:
2649 if (!Visit(E->getSubExpr()))
2650 return false;
2651 if (!Result.Base && Result.Offset.isZero())
2652 return true;
2653 return HandleBaseToDerivedCast(Info, E, Result);
2654
Richard Smith0b0a0b62011-10-29 20:57:55 +00002655 case CK_NullToPointer:
Richard Smithfddd3842011-12-30 21:15:51 +00002656 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002657
John McCalle3027922010-08-25 11:45:40 +00002658 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00002659 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2660
Richard Smith0b0a0b62011-10-29 20:57:55 +00002661 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002662 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002663 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002664
John McCall45d55e42010-05-07 21:00:08 +00002665 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002666 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2667 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002668 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002669 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002670 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002671 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002672 return true;
2673 } else {
2674 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002675 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002676 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002677 }
2678 }
John McCalle3027922010-08-25 11:45:40 +00002679 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002680 if (SubExpr->isGLValue()) {
2681 if (!EvaluateLValue(SubExpr, Result, Info))
2682 return false;
2683 } else {
2684 Result.set(SubExpr, Info.CurrentCall);
2685 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2686 Info, Result, SubExpr))
2687 return false;
2688 }
Richard Smith96e0c102011-11-04 02:25:55 +00002689 // The result is a pointer to the first element of the array.
2690 Result.Designator.addIndex(0);
2691 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002692
John McCalle3027922010-08-25 11:45:40 +00002693 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002694 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002695 }
2696
Richard Smith11562c52011-10-28 17:51:58 +00002697 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002698}
Chris Lattner05706e882008-07-11 18:11:29 +00002699
Peter Collingbournee9200682011-05-13 03:29:01 +00002700bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002701 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002702 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002703
Peter Collingbournee9200682011-05-13 03:29:01 +00002704 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002705}
Chris Lattner05706e882008-07-11 18:11:29 +00002706
2707//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002708// Member Pointer Evaluation
2709//===----------------------------------------------------------------------===//
2710
2711namespace {
2712class MemberPointerExprEvaluator
2713 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2714 MemberPtr &Result;
2715
2716 bool Success(const ValueDecl *D) {
2717 Result = MemberPtr(D);
2718 return true;
2719 }
2720public:
2721
2722 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2723 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2724
2725 bool Success(const CCValue &V, const Expr *E) {
2726 Result.setFrom(V);
2727 return true;
2728 }
Richard Smithfddd3842011-12-30 21:15:51 +00002729 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002730 return Success((const ValueDecl*)0);
2731 }
2732
2733 bool VisitCastExpr(const CastExpr *E);
2734 bool VisitUnaryAddrOf(const UnaryOperator *E);
2735};
2736} // end anonymous namespace
2737
2738static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2739 EvalInfo &Info) {
2740 assert(E->isRValue() && E->getType()->isMemberPointerType());
2741 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2742}
2743
2744bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2745 switch (E->getCastKind()) {
2746 default:
2747 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2748
2749 case CK_NullToMemberPointer:
Richard Smithfddd3842011-12-30 21:15:51 +00002750 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002751
2752 case CK_BaseToDerivedMemberPointer: {
2753 if (!Visit(E->getSubExpr()))
2754 return false;
2755 if (E->path_empty())
2756 return true;
2757 // Base-to-derived member pointer casts store the path in derived-to-base
2758 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2759 // the wrong end of the derived->base arc, so stagger the path by one class.
2760 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2761 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2762 PathI != PathE; ++PathI) {
2763 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2764 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2765 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002766 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002767 }
2768 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2769 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002770 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002771 return true;
2772 }
2773
2774 case CK_DerivedToBaseMemberPointer:
2775 if (!Visit(E->getSubExpr()))
2776 return false;
2777 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2778 PathE = E->path_end(); PathI != PathE; ++PathI) {
2779 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2780 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2781 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002782 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002783 }
2784 return true;
2785 }
2786}
2787
2788bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2789 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2790 // member can be formed.
2791 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2792}
2793
2794//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002795// Record Evaluation
2796//===----------------------------------------------------------------------===//
2797
2798namespace {
2799 class RecordExprEvaluator
2800 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2801 const LValue &This;
2802 APValue &Result;
2803 public:
2804
2805 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2806 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2807
2808 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002809 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002810 }
Richard Smithfddd3842011-12-30 21:15:51 +00002811 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002812
Richard Smithe97cbd72011-11-11 04:05:33 +00002813 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002814 bool VisitInitListExpr(const InitListExpr *E);
2815 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2816 };
2817}
2818
Richard Smithfddd3842011-12-30 21:15:51 +00002819/// Perform zero-initialization on an object of non-union class type.
2820/// C++11 [dcl.init]p5:
2821/// To zero-initialize an object or reference of type T means:
2822/// [...]
2823/// -- if T is a (possibly cv-qualified) non-union class type,
2824/// each non-static data member and each base-class subobject is
2825/// zero-initialized
2826static bool HandleClassZeroInitialization(EvalInfo &Info, const RecordDecl *RD,
2827 const LValue &This, APValue &Result) {
2828 assert(!RD->isUnion() && "Expected non-union class type");
2829 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
2830 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
2831 std::distance(RD->field_begin(), RD->field_end()));
2832
2833 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2834
2835 if (CD) {
2836 unsigned Index = 0;
2837 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
2838 E = CD->bases_end(); I != E; ++I, ++Index) {
2839 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
2840 LValue Subobject = This;
2841 HandleLValueDirectBase(Info, Subobject, CD, Base, &Layout);
2842 if (!HandleClassZeroInitialization(Info, Base, Subobject,
2843 Result.getStructBase(Index)))
2844 return false;
2845 }
2846 }
2847
2848 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2849 I != E; ++I) {
2850 // -- if T is a reference type, no initialization is performed.
2851 if ((*I)->getType()->isReferenceType())
2852 continue;
2853
2854 LValue Subobject = This;
2855 HandleLValueMember(Info, Subobject, *I, &Layout);
2856
2857 ImplicitValueInitExpr VIE((*I)->getType());
2858 if (!EvaluateConstantExpression(
2859 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
2860 return false;
2861 }
2862
2863 return true;
2864}
2865
2866bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
2867 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2868 if (RD->isUnion()) {
2869 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
2870 // object's first non-static named data member is zero-initialized
2871 RecordDecl::field_iterator I = RD->field_begin();
2872 if (I == RD->field_end()) {
2873 Result = APValue((const FieldDecl*)0);
2874 return true;
2875 }
2876
2877 LValue Subobject = This;
2878 HandleLValueMember(Info, Subobject, *I);
2879 Result = APValue(*I);
2880 ImplicitValueInitExpr VIE((*I)->getType());
2881 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2882 Subobject, &VIE);
2883 }
2884
2885 return HandleClassZeroInitialization(Info, RD, This, Result);
2886}
2887
Richard Smithe97cbd72011-11-11 04:05:33 +00002888bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2889 switch (E->getCastKind()) {
2890 default:
2891 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2892
2893 case CK_ConstructorConversion:
2894 return Visit(E->getSubExpr());
2895
2896 case CK_DerivedToBase:
2897 case CK_UncheckedDerivedToBase: {
2898 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002899 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002900 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002901 if (!DerivedObject.isStruct())
2902 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00002903
2904 // Derived-to-base rvalue conversion: just slice off the derived part.
2905 APValue *Value = &DerivedObject;
2906 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2907 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2908 PathE = E->path_end(); PathI != PathE; ++PathI) {
2909 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2910 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2911 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2912 RD = Base;
2913 }
2914 Result = *Value;
2915 return true;
2916 }
2917 }
2918}
2919
Richard Smithd62306a2011-11-10 06:34:14 +00002920bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2921 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2922 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2923
2924 if (RD->isUnion()) {
2925 Result = APValue(E->getInitializedFieldInUnion());
2926 if (!E->getNumInits())
2927 return true;
2928 LValue Subobject = This;
2929 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2930 &Layout);
2931 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2932 Subobject, E->getInit(0));
2933 }
2934
2935 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2936 "initializer list for class with base classes");
2937 Result = APValue(APValue::UninitStruct(), 0,
2938 std::distance(RD->field_begin(), RD->field_end()));
2939 unsigned ElementNo = 0;
2940 for (RecordDecl::field_iterator Field = RD->field_begin(),
2941 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2942 // Anonymous bit-fields are not considered members of the class for
2943 // purposes of aggregate initialization.
2944 if (Field->isUnnamedBitfield())
2945 continue;
2946
2947 LValue Subobject = This;
2948 HandleLValueMember(Info, Subobject, *Field, &Layout);
2949
2950 if (ElementNo < E->getNumInits()) {
2951 if (!EvaluateConstantExpression(
2952 Result.getStructField((*Field)->getFieldIndex()),
2953 Info, Subobject, E->getInit(ElementNo++)))
2954 return false;
2955 } else {
2956 // Perform an implicit value-initialization for members beyond the end of
2957 // the initializer list.
2958 ImplicitValueInitExpr VIE(Field->getType());
2959 if (!EvaluateConstantExpression(
2960 Result.getStructField((*Field)->getFieldIndex()),
2961 Info, Subobject, &VIE))
2962 return false;
2963 }
2964 }
2965
2966 return true;
2967}
2968
2969bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2970 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithfddd3842011-12-30 21:15:51 +00002971 bool ZeroInit = E->requiresZeroInitialization();
2972 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
2973 if (ZeroInit)
2974 return ZeroInitialization(E);
2975
Richard Smithcc36f692011-12-22 02:22:31 +00002976 const CXXRecordDecl *RD = FD->getParent();
2977 if (RD->isUnion())
2978 Result = APValue((FieldDecl*)0);
2979 else
2980 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2981 std::distance(RD->field_begin(), RD->field_end()));
2982 return true;
2983 }
2984
Richard Smithd62306a2011-11-10 06:34:14 +00002985 const FunctionDecl *Definition = 0;
2986 FD->getBody(Definition);
2987
Richard Smith357362d2011-12-13 06:39:58 +00002988 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2989 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002990
2991 // FIXME: Elide the copy/move construction wherever we can.
Richard Smithfddd3842011-12-30 21:15:51 +00002992 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00002993 if (const MaterializeTemporaryExpr *ME
2994 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2995 return Visit(ME->GetTemporaryExpr());
2996
Richard Smithfddd3842011-12-30 21:15:51 +00002997 if (ZeroInit && !ZeroInitialization(E))
2998 return false;
2999
Richard Smithd62306a2011-11-10 06:34:14 +00003000 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003001 return HandleConstructorCall(E, This, Args,
3002 cast<CXXConstructorDecl>(Definition), Info,
3003 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00003004}
3005
3006static bool EvaluateRecord(const Expr *E, const LValue &This,
3007 APValue &Result, EvalInfo &Info) {
3008 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00003009 "can't evaluate expression as a record rvalue");
3010 return RecordExprEvaluator(Info, This, Result).Visit(E);
3011}
3012
3013//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003014// Temporary Evaluation
3015//
3016// Temporaries are represented in the AST as rvalues, but generally behave like
3017// lvalues. The full-object of which the temporary is a subobject is implicitly
3018// materialized so that a reference can bind to it.
3019//===----------------------------------------------------------------------===//
3020namespace {
3021class TemporaryExprEvaluator
3022 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3023public:
3024 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3025 LValueExprEvaluatorBaseTy(Info, Result) {}
3026
3027 /// Visit an expression which constructs the value of this temporary.
3028 bool VisitConstructExpr(const Expr *E) {
3029 Result.set(E, Info.CurrentCall);
3030 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3031 Result, E);
3032 }
3033
3034 bool VisitCastExpr(const CastExpr *E) {
3035 switch (E->getCastKind()) {
3036 default:
3037 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3038
3039 case CK_ConstructorConversion:
3040 return VisitConstructExpr(E->getSubExpr());
3041 }
3042 }
3043 bool VisitInitListExpr(const InitListExpr *E) {
3044 return VisitConstructExpr(E);
3045 }
3046 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3047 return VisitConstructExpr(E);
3048 }
3049 bool VisitCallExpr(const CallExpr *E) {
3050 return VisitConstructExpr(E);
3051 }
3052};
3053} // end anonymous namespace
3054
3055/// Evaluate an expression of record type as a temporary.
3056static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003057 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00003058 return TemporaryExprEvaluator(Info, Result).Visit(E);
3059}
3060
3061//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003062// Vector Evaluation
3063//===----------------------------------------------------------------------===//
3064
3065namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003066 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00003067 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3068 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003069 public:
Mike Stump11289f42009-09-09 15:08:12 +00003070
Richard Smith2d406342011-10-22 21:10:00 +00003071 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3072 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003073
Richard Smith2d406342011-10-22 21:10:00 +00003074 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3075 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3076 // FIXME: remove this APValue copy.
3077 Result = APValue(V.data(), V.size());
3078 return true;
3079 }
Richard Smithed5165f2011-11-04 05:33:44 +00003080 bool Success(const CCValue &V, const Expr *E) {
3081 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00003082 Result = V;
3083 return true;
3084 }
Richard Smithfddd3842011-12-30 21:15:51 +00003085 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003086
Richard Smith2d406342011-10-22 21:10:00 +00003087 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00003088 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00003089 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00003090 bool VisitInitListExpr(const InitListExpr *E);
3091 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003092 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00003093 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00003094 // shufflevector, ExtVectorElementExpr
3095 // (Note that these require implementing conversions
3096 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003097 };
3098} // end anonymous namespace
3099
3100static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003101 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00003102 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003103}
3104
Richard Smith2d406342011-10-22 21:10:00 +00003105bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3106 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003107 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003108
Richard Smith161f09a2011-12-06 22:44:34 +00003109 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00003110 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003111
Eli Friedmanc757de22011-03-25 00:43:55 +00003112 switch (E->getCastKind()) {
3113 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00003114 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00003115 if (SETy->isIntegerType()) {
3116 APSInt IntResult;
3117 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003118 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003119 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00003120 } else if (SETy->isRealFloatingType()) {
3121 APFloat F(0.0);
3122 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003123 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003124 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00003125 } else {
Richard Smith2d406342011-10-22 21:10:00 +00003126 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003127 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003128
3129 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00003130 SmallVector<APValue, 4> Elts(NElts, Val);
3131 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00003132 }
Eli Friedman803acb32011-12-22 03:51:45 +00003133 case CK_BitCast: {
3134 // Evaluate the operand into an APInt we can extract from.
3135 llvm::APInt SValInt;
3136 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3137 return false;
3138 // Extract the elements
3139 QualType EltTy = VTy->getElementType();
3140 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3141 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3142 SmallVector<APValue, 4> Elts;
3143 if (EltTy->isRealFloatingType()) {
3144 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3145 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3146 unsigned FloatEltSize = EltSize;
3147 if (&Sem == &APFloat::x87DoubleExtended)
3148 FloatEltSize = 80;
3149 for (unsigned i = 0; i < NElts; i++) {
3150 llvm::APInt Elt;
3151 if (BigEndian)
3152 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3153 else
3154 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3155 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3156 }
3157 } else if (EltTy->isIntegerType()) {
3158 for (unsigned i = 0; i < NElts; i++) {
3159 llvm::APInt Elt;
3160 if (BigEndian)
3161 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3162 else
3163 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3164 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3165 }
3166 } else {
3167 return Error(E);
3168 }
3169 return Success(Elts, E);
3170 }
Eli Friedmanc757de22011-03-25 00:43:55 +00003171 default:
Richard Smith11562c52011-10-28 17:51:58 +00003172 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003173 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003174}
3175
Richard Smith2d406342011-10-22 21:10:00 +00003176bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003177VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003178 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003179 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00003180 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003181
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003182 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003183 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003184
Eli Friedmanb9c71292012-01-03 23:24:20 +00003185 // The number of initializers can be less than the number of
3186 // vector elements. For OpenCL, this can be due to nested vector
3187 // initialization. For GCC compatibility, missing trailing elements
3188 // should be initialized with zeroes.
3189 unsigned CountInits = 0, CountElts = 0;
3190 while (CountElts < NumElements) {
3191 // Handle nested vector initialization.
3192 if (CountInits < NumInits
3193 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3194 APValue v;
3195 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3196 return Error(E);
3197 unsigned vlen = v.getVectorLength();
3198 for (unsigned j = 0; j < vlen; j++)
3199 Elements.push_back(v.getVectorElt(j));
3200 CountElts += vlen;
3201 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003202 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003203 if (CountInits < NumInits) {
3204 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3205 return Error(E);
3206 } else // trailing integer zero.
3207 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3208 Elements.push_back(APValue(sInt));
3209 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003210 } else {
3211 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003212 if (CountInits < NumInits) {
3213 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3214 return Error(E);
3215 } else // trailing float zero.
3216 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3217 Elements.push_back(APValue(f));
3218 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00003219 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00003220 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003221 }
Richard Smith2d406342011-10-22 21:10:00 +00003222 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003223}
3224
Richard Smith2d406342011-10-22 21:10:00 +00003225bool
Richard Smithfddd3842011-12-30 21:15:51 +00003226VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003227 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00003228 QualType EltTy = VT->getElementType();
3229 APValue ZeroElement;
3230 if (EltTy->isIntegerType())
3231 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3232 else
3233 ZeroElement =
3234 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3235
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003236 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00003237 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003238}
3239
Richard Smith2d406342011-10-22 21:10:00 +00003240bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00003241 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003242 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003243}
3244
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003245//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00003246// Array Evaluation
3247//===----------------------------------------------------------------------===//
3248
3249namespace {
3250 class ArrayExprEvaluator
3251 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00003252 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00003253 APValue &Result;
3254 public:
3255
Richard Smithd62306a2011-11-10 06:34:14 +00003256 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3257 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00003258
3259 bool Success(const APValue &V, const Expr *E) {
3260 assert(V.isArray() && "Expected array type");
3261 Result = V;
3262 return true;
3263 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003264
Richard Smithfddd3842011-12-30 21:15:51 +00003265 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003266 const ConstantArrayType *CAT =
3267 Info.Ctx.getAsConstantArrayType(E->getType());
3268 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003269 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003270
3271 Result = APValue(APValue::UninitArray(), 0,
3272 CAT->getSize().getZExtValue());
3273 if (!Result.hasArrayFiller()) return true;
3274
Richard Smithfddd3842011-12-30 21:15:51 +00003275 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00003276 LValue Subobject = This;
3277 Subobject.Designator.addIndex(0);
3278 ImplicitValueInitExpr VIE(CAT->getElementType());
3279 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3280 Subobject, &VIE);
3281 }
3282
Richard Smithf3e9e432011-11-07 09:22:26 +00003283 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00003284 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003285 };
3286} // end anonymous namespace
3287
Richard Smithd62306a2011-11-10 06:34:14 +00003288static bool EvaluateArray(const Expr *E, const LValue &This,
3289 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00003290 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00003291 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003292}
3293
3294bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3295 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3296 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003297 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003298
Richard Smithca2cfbf2011-12-22 01:07:19 +00003299 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3300 // an appropriately-typed string literal enclosed in braces.
3301 if (E->getNumInits() == 1 && CAT->getElementType()->isAnyCharacterType() &&
3302 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3303 LValue LV;
3304 if (!EvaluateLValue(E->getInit(0), LV, Info))
3305 return false;
3306 uint64_t NumElements = CAT->getSize().getZExtValue();
3307 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3308
3309 // Copy the string literal into the array. FIXME: Do this better.
3310 LV.Designator.addIndex(0);
3311 for (uint64_t I = 0; I < NumElements; ++I) {
3312 CCValue Char;
3313 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3314 CAT->getElementType(), LV, Char))
3315 return false;
3316 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3317 Result.getArrayInitializedElt(I)))
3318 return false;
3319 if (!HandleLValueArrayAdjustment(Info, LV, CAT->getElementType(), 1))
3320 return false;
3321 }
3322 return true;
3323 }
3324
Richard Smithf3e9e432011-11-07 09:22:26 +00003325 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3326 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00003327 LValue Subobject = This;
3328 Subobject.Designator.addIndex(0);
3329 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00003330 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00003331 I != End; ++I, ++Index) {
3332 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3333 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00003334 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003335 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
3336 return false;
3337 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003338
3339 if (!Result.hasArrayFiller()) return true;
3340 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00003341 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3342 // but sometimes does:
3343 // struct S { constexpr S() : p(&p) {} void *p; };
3344 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00003345 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00003346 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00003347}
3348
Richard Smith027bf112011-11-17 22:56:20 +00003349bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3350 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3351 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003352 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003353
3354 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3355 if (!Result.hasArrayFiller())
3356 return true;
3357
3358 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00003359
Richard Smithfddd3842011-12-30 21:15:51 +00003360 bool ZeroInit = E->requiresZeroInitialization();
3361 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3362 if (ZeroInit) {
3363 LValue Subobject = This;
3364 Subobject.Designator.addIndex(0);
3365 ImplicitValueInitExpr VIE(CAT->getElementType());
3366 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3367 Subobject, &VIE);
3368 }
3369
Richard Smithcc36f692011-12-22 02:22:31 +00003370 const CXXRecordDecl *RD = FD->getParent();
3371 if (RD->isUnion())
3372 Result.getArrayFiller() = APValue((FieldDecl*)0);
3373 else
3374 Result.getArrayFiller() =
3375 APValue(APValue::UninitStruct(), RD->getNumBases(),
3376 std::distance(RD->field_begin(), RD->field_end()));
3377 return true;
3378 }
3379
Richard Smith027bf112011-11-17 22:56:20 +00003380 const FunctionDecl *Definition = 0;
3381 FD->getBody(Definition);
3382
Richard Smith357362d2011-12-13 06:39:58 +00003383 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3384 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003385
3386 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3387 // but sometimes does:
3388 // struct S { constexpr S() : p(&p) {} void *p; };
3389 // S s[10];
3390 LValue Subobject = This;
3391 Subobject.Designator.addIndex(0);
Richard Smithfddd3842011-12-30 21:15:51 +00003392
3393 if (ZeroInit) {
3394 ImplicitValueInitExpr VIE(CAT->getElementType());
3395 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3396 &VIE))
3397 return false;
3398 }
3399
Richard Smith027bf112011-11-17 22:56:20 +00003400 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003401 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003402 cast<CXXConstructorDecl>(Definition),
3403 Info, Result.getArrayFiller());
3404}
3405
Richard Smithf3e9e432011-11-07 09:22:26 +00003406//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003407// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003408//
3409// As a GNU extension, we support casting pointers to sufficiently-wide integer
3410// types and back in constant folding. Integer values are thus represented
3411// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003412//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003413
3414namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003415class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003416 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003417 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003418public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00003419 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003420 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003421
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003422 bool Success(const llvm::APSInt &SI, const Expr *E) {
3423 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003424 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003425 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003426 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003427 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003428 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003429 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003430 return true;
3431 }
3432
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003433 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003434 assert(E->getType()->isIntegralOrEnumerationType() &&
3435 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003436 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003437 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003438 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003439 Result.getInt().setIsUnsigned(
3440 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003441 return true;
3442 }
3443
3444 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003445 assert(E->getType()->isIntegralOrEnumerationType() &&
3446 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003447 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003448 return true;
3449 }
3450
Ken Dyckdbc01912011-03-11 02:13:43 +00003451 bool Success(CharUnits Size, const Expr *E) {
3452 return Success(Size.getQuantity(), E);
3453 }
3454
Richard Smith0b0a0b62011-10-29 20:57:55 +00003455 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00003456 if (V.isLValue()) {
3457 Result = V;
3458 return true;
3459 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003460 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003461 }
Mike Stump11289f42009-09-09 15:08:12 +00003462
Richard Smithfddd3842011-12-30 21:15:51 +00003463 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00003464
Peter Collingbournee9200682011-05-13 03:29:01 +00003465 //===--------------------------------------------------------------------===//
3466 // Visitor Methods
3467 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003468
Chris Lattner7174bf32008-07-12 00:38:25 +00003469 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003470 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003471 }
3472 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003473 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003474 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003475
3476 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3477 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003478 if (CheckReferencedDecl(E, E->getDecl()))
3479 return true;
3480
3481 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003482 }
3483 bool VisitMemberExpr(const MemberExpr *E) {
3484 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00003485 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003486 return true;
3487 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003488
3489 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003490 }
3491
Peter Collingbournee9200682011-05-13 03:29:01 +00003492 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003493 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00003494 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003495 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00003496
Peter Collingbournee9200682011-05-13 03:29:01 +00003497 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003498 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00003499
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003500 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003501 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003502 }
Mike Stump11289f42009-09-09 15:08:12 +00003503
Richard Smith4ce706a2011-10-11 21:43:33 +00003504 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00003505 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003506 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003507 }
3508
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003509 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003510 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003511 }
3512
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003513 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3514 return Success(E->getValue(), E);
3515 }
3516
John Wiegley6242b6a2011-04-28 00:16:57 +00003517 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3518 return Success(E->getValue(), E);
3519 }
3520
John Wiegleyf9f65842011-04-25 06:54:41 +00003521 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3522 return Success(E->getValue(), E);
3523 }
3524
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003525 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003526 bool VisitUnaryImag(const UnaryOperator *E);
3527
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003528 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003529 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00003530
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003531private:
Ken Dyck160146e2010-01-27 17:10:57 +00003532 CharUnits GetAlignOfExpr(const Expr *E);
3533 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00003534 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00003535 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003536 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00003537};
Chris Lattner05706e882008-07-11 18:11:29 +00003538} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003539
Richard Smith11562c52011-10-28 17:51:58 +00003540/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3541/// produce either the integer value or a pointer.
3542///
3543/// GCC has a heinous extension which folds casts between pointer types and
3544/// pointer-sized integral types. We support this by allowing the evaluation of
3545/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3546/// Some simple arithmetic on such values is supported (they are treated much
3547/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00003548static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00003549 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003550 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003551 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00003552}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003553
Richard Smithf57d8cb2011-12-09 22:58:01 +00003554static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003555 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003556 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00003557 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003558 if (!Val.isInt()) {
3559 // FIXME: It would be better to produce the diagnostic for casting
3560 // a pointer to an integer.
Richard Smith92b1ce02011-12-12 09:28:41 +00003561 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003562 return false;
3563 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003564 Result = Val.getInt();
3565 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003566}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003567
Richard Smithf57d8cb2011-12-09 22:58:01 +00003568/// Check whether the given declaration can be directly converted to an integral
3569/// rvalue. If not, no diagnostic is produced; there are other things we can
3570/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003571bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003572 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003573 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003574 // Check for signedness/width mismatches between E type and ECD value.
3575 bool SameSign = (ECD->getInitVal().isSigned()
3576 == E->getType()->isSignedIntegerOrEnumerationType());
3577 bool SameWidth = (ECD->getInitVal().getBitWidth()
3578 == Info.Ctx.getIntWidth(E->getType()));
3579 if (SameSign && SameWidth)
3580 return Success(ECD->getInitVal(), E);
3581 else {
3582 // Get rid of mismatch (otherwise Success assertions will fail)
3583 // by computing a new value matching the type of E.
3584 llvm::APSInt Val = ECD->getInitVal();
3585 if (!SameSign)
3586 Val.setIsSigned(!ECD->getInitVal().isSigned());
3587 if (!SameWidth)
3588 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3589 return Success(Val, E);
3590 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003591 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003592 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003593}
3594
Chris Lattner86ee2862008-10-06 06:40:35 +00003595/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3596/// as GCC.
3597static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3598 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003599 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003600 enum gcc_type_class {
3601 no_type_class = -1,
3602 void_type_class, integer_type_class, char_type_class,
3603 enumeral_type_class, boolean_type_class,
3604 pointer_type_class, reference_type_class, offset_type_class,
3605 real_type_class, complex_type_class,
3606 function_type_class, method_type_class,
3607 record_type_class, union_type_class,
3608 array_type_class, string_type_class,
3609 lang_type_class
3610 };
Mike Stump11289f42009-09-09 15:08:12 +00003611
3612 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003613 // ideal, however it is what gcc does.
3614 if (E->getNumArgs() == 0)
3615 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003616
Chris Lattner86ee2862008-10-06 06:40:35 +00003617 QualType ArgTy = E->getArg(0)->getType();
3618 if (ArgTy->isVoidType())
3619 return void_type_class;
3620 else if (ArgTy->isEnumeralType())
3621 return enumeral_type_class;
3622 else if (ArgTy->isBooleanType())
3623 return boolean_type_class;
3624 else if (ArgTy->isCharType())
3625 return string_type_class; // gcc doesn't appear to use char_type_class
3626 else if (ArgTy->isIntegerType())
3627 return integer_type_class;
3628 else if (ArgTy->isPointerType())
3629 return pointer_type_class;
3630 else if (ArgTy->isReferenceType())
3631 return reference_type_class;
3632 else if (ArgTy->isRealType())
3633 return real_type_class;
3634 else if (ArgTy->isComplexType())
3635 return complex_type_class;
3636 else if (ArgTy->isFunctionType())
3637 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003638 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003639 return record_type_class;
3640 else if (ArgTy->isUnionType())
3641 return union_type_class;
3642 else if (ArgTy->isArrayType())
3643 return array_type_class;
3644 else if (ArgTy->isUnionType())
3645 return union_type_class;
3646 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003647 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003648 return -1;
3649}
3650
Richard Smith5fab0c92011-12-28 19:48:30 +00003651/// EvaluateBuiltinConstantPForLValue - Determine the result of
3652/// __builtin_constant_p when applied to the given lvalue.
3653///
3654/// An lvalue is only "constant" if it is a pointer or reference to the first
3655/// character of a string literal.
3656template<typename LValue>
3657static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3658 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3659 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3660}
3661
3662/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3663/// GCC as we can manage.
3664static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3665 QualType ArgType = Arg->getType();
3666
3667 // __builtin_constant_p always has one operand. The rules which gcc follows
3668 // are not precisely documented, but are as follows:
3669 //
3670 // - If the operand is of integral, floating, complex or enumeration type,
3671 // and can be folded to a known value of that type, it returns 1.
3672 // - If the operand and can be folded to a pointer to the first character
3673 // of a string literal (or such a pointer cast to an integral type), it
3674 // returns 1.
3675 //
3676 // Otherwise, it returns 0.
3677 //
3678 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3679 // its support for this does not currently work.
3680 if (ArgType->isIntegralOrEnumerationType()) {
3681 Expr::EvalResult Result;
3682 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3683 return false;
3684
3685 APValue &V = Result.Val;
3686 if (V.getKind() == APValue::Int)
3687 return true;
3688
3689 return EvaluateBuiltinConstantPForLValue(V);
3690 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3691 return Arg->isEvaluatable(Ctx);
3692 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3693 LValue LV;
3694 Expr::EvalStatus Status;
3695 EvalInfo Info(Ctx, Status);
3696 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3697 : EvaluatePointer(Arg, LV, Info)) &&
3698 !Status.HasSideEffects)
3699 return EvaluateBuiltinConstantPForLValue(LV);
3700 }
3701
3702 // Anything else isn't considered to be sufficiently constant.
3703 return false;
3704}
3705
John McCall95007602010-05-10 23:27:23 +00003706/// Retrieves the "underlying object type" of the given expression,
3707/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003708QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3709 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3710 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003711 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003712 } else if (const Expr *E = B.get<const Expr*>()) {
3713 if (isa<CompoundLiteralExpr>(E))
3714 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003715 }
3716
3717 return QualType();
3718}
3719
Peter Collingbournee9200682011-05-13 03:29:01 +00003720bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003721 // TODO: Perhaps we should let LLVM lower this?
3722 LValue Base;
3723 if (!EvaluatePointer(E->getArg(0), Base, Info))
3724 return false;
3725
3726 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003727 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003728
Richard Smithce40ad62011-11-12 22:28:03 +00003729 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003730 if (T.isNull() ||
3731 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003732 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003733 T->isVariablyModifiedType() ||
3734 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003735 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003736
3737 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3738 CharUnits Offset = Base.getLValueOffset();
3739
3740 if (!Offset.isNegative() && Offset <= Size)
3741 Size -= Offset;
3742 else
3743 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003744 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003745}
3746
Peter Collingbournee9200682011-05-13 03:29:01 +00003747bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003748 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003749 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003750 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003751
3752 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003753 if (TryEvaluateBuiltinObjectSize(E))
3754 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003755
Eric Christopher99469702010-01-19 22:58:35 +00003756 // If evaluating the argument has side-effects we can't determine
3757 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003758 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003759 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003760 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003761 return Success(0, E);
3762 }
Mike Stump876387b2009-10-27 22:09:17 +00003763
Richard Smithf57d8cb2011-12-09 22:58:01 +00003764 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003765 }
3766
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003767 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003768 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003769
Richard Smith5fab0c92011-12-28 19:48:30 +00003770 case Builtin::BI__builtin_constant_p:
3771 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00003772
Chris Lattnerd545ad12009-09-23 06:06:36 +00003773 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003774 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003775 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003776 return Success(Operand, E);
3777 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003778
3779 case Builtin::BI__builtin_expect:
3780 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003781
3782 case Builtin::BIstrlen:
3783 case Builtin::BI__builtin_strlen:
3784 // As an extension, we support strlen() and __builtin_strlen() as constant
3785 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003786 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003787 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3788 // The string literal may have embedded null characters. Find the first
3789 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003790 StringRef Str = S->getString();
3791 StringRef::size_type Pos = Str.find(0);
3792 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003793 Str = Str.substr(0, Pos);
3794
3795 return Success(Str.size(), E);
3796 }
3797
Richard Smithf57d8cb2011-12-09 22:58:01 +00003798 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003799
3800 case Builtin::BI__atomic_is_lock_free: {
3801 APSInt SizeVal;
3802 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3803 return false;
3804
3805 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3806 // of two less than the maximum inline atomic width, we know it is
3807 // lock-free. If the size isn't a power of two, or greater than the
3808 // maximum alignment where we promote atomics, we know it is not lock-free
3809 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3810 // the answer can only be determined at runtime; for example, 16-byte
3811 // atomics have lock-free implementations on some, but not all,
3812 // x86-64 processors.
3813
3814 // Check power-of-two.
3815 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3816 if (!Size.isPowerOfTwo())
3817#if 0
3818 // FIXME: Suppress this folding until the ABI for the promotion width
3819 // settles.
3820 return Success(0, E);
3821#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003822 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003823#endif
3824
3825#if 0
3826 // Check against promotion width.
3827 // FIXME: Suppress this folding until the ABI for the promotion width
3828 // settles.
3829 unsigned PromoteWidthBits =
3830 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3831 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3832 return Success(0, E);
3833#endif
3834
3835 // Check against inlining width.
3836 unsigned InlineWidthBits =
3837 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3838 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3839 return Success(1, E);
3840
Richard Smithf57d8cb2011-12-09 22:58:01 +00003841 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003842 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003843 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003844}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003845
Richard Smith8b3497e2011-10-31 01:37:14 +00003846static bool HasSameBase(const LValue &A, const LValue &B) {
3847 if (!A.getLValueBase())
3848 return !B.getLValueBase();
3849 if (!B.getLValueBase())
3850 return false;
3851
Richard Smithce40ad62011-11-12 22:28:03 +00003852 if (A.getLValueBase().getOpaqueValue() !=
3853 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003854 const Decl *ADecl = GetLValueBaseDecl(A);
3855 if (!ADecl)
3856 return false;
3857 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003858 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003859 return false;
3860 }
3861
3862 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003863 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003864}
3865
Chris Lattnere13042c2008-07-11 19:10:17 +00003866bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003867 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003868 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003869
John McCalle3027922010-08-25 11:45:40 +00003870 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003871 VisitIgnoredValue(E->getLHS());
3872 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003873 }
3874
3875 if (E->isLogicalOp()) {
3876 // These need to be handled specially because the operands aren't
3877 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003878 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003879
Richard Smith11562c52011-10-28 17:51:58 +00003880 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003881 // We were able to evaluate the LHS, see if we can get away with not
3882 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003883 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003884 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003885
Richard Smith11562c52011-10-28 17:51:58 +00003886 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003887 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003888 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003889 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003890 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003891 }
3892 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003893 // FIXME: If both evaluations fail, we should produce the diagnostic from
3894 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3895 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003896 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003897 // We can't evaluate the LHS; however, sometimes the result
3898 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003899 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003900 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003901 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00003902 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003903
3904 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003905 }
3906 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00003907 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00003908
Eli Friedman5a332ea2008-11-13 06:09:17 +00003909 return false;
3910 }
3911
Anders Carlssonacc79812008-11-16 07:17:21 +00003912 QualType LHSTy = E->getLHS()->getType();
3913 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003914
3915 if (LHSTy->isAnyComplexType()) {
3916 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00003917 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003918
3919 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3920 return false;
3921
3922 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3923 return false;
3924
3925 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00003926 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003927 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00003928 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003929 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3930
John McCalle3027922010-08-25 11:45:40 +00003931 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003932 return Success((CR_r == APFloat::cmpEqual &&
3933 CR_i == APFloat::cmpEqual), E);
3934 else {
John McCalle3027922010-08-25 11:45:40 +00003935 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003936 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00003937 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003938 CR_r == APFloat::cmpLessThan ||
3939 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00003940 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003941 CR_i == APFloat::cmpLessThan ||
3942 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003943 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003944 } else {
John McCalle3027922010-08-25 11:45:40 +00003945 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003946 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3947 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3948 else {
John McCalle3027922010-08-25 11:45:40 +00003949 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003950 "Invalid compex comparison.");
3951 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3952 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3953 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003954 }
3955 }
Mike Stump11289f42009-09-09 15:08:12 +00003956
Anders Carlssonacc79812008-11-16 07:17:21 +00003957 if (LHSTy->isRealFloatingType() &&
3958 RHSTy->isRealFloatingType()) {
3959 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00003960
Anders Carlssonacc79812008-11-16 07:17:21 +00003961 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3962 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003963
Anders Carlssonacc79812008-11-16 07:17:21 +00003964 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3965 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003966
Anders Carlssonacc79812008-11-16 07:17:21 +00003967 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00003968
Anders Carlssonacc79812008-11-16 07:17:21 +00003969 switch (E->getOpcode()) {
3970 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003971 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00003972 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003973 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00003974 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003975 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00003976 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003977 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003978 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00003979 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003980 E);
John McCalle3027922010-08-25 11:45:40 +00003981 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003982 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003983 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00003984 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00003985 || CR == APFloat::cmpLessThan
3986 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00003987 }
Anders Carlssonacc79812008-11-16 07:17:21 +00003988 }
Mike Stump11289f42009-09-09 15:08:12 +00003989
Eli Friedmana38da572009-04-28 19:17:36 +00003990 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003991 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00003992 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003993 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3994 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003995
John McCall45d55e42010-05-07 21:00:08 +00003996 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003997 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3998 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003999
Richard Smith8b3497e2011-10-31 01:37:14 +00004000 // Reject differing bases from the normal codepath; we special-case
4001 // comparisons to null.
4002 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004003 if (E->getOpcode() == BO_Sub) {
4004 // Handle &&A - &&B.
4005 // FIXME: We're missing a check that both labels have the same
4006 // associated function; I'm not sure how to write this check.
4007 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4008 return false;
4009 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4010 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4011 if (!LHSExpr || !RHSExpr)
4012 return false;
4013 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4014 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4015 if (!LHSAddrExpr || !RHSAddrExpr)
4016 return false;
4017 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4018 return true;
4019 }
Richard Smith83c68212011-10-31 05:11:32 +00004020 // Inequalities and subtractions between unrelated pointers have
4021 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00004022 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004023 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004024 // A constant address may compare equal to the address of a symbol.
4025 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00004026 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004027 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4028 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004029 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004030 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00004031 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00004032 // distinct. However, we do know that the address of a literal will be
4033 // non-null.
4034 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4035 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004036 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004037 // We can't tell whether weak symbols will end up pointing to the same
4038 // object.
4039 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004040 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004041 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00004042 // (Note that clang defaults to -fmerge-all-constants, which can
4043 // lead to inconsistent results for comparisons involving the address
4044 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00004045 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00004046 }
Eli Friedman64004332009-03-23 04:38:34 +00004047
Richard Smithf3e9e432011-11-07 09:22:26 +00004048 // FIXME: Implement the C++11 restrictions:
4049 // - Pointer subtractions must be on elements of the same array.
4050 // - Pointer comparisons must be between members with the same access.
4051
John McCalle3027922010-08-25 11:45:40 +00004052 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00004053 QualType Type = E->getLHS()->getType();
4054 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004055
Richard Smithd62306a2011-11-10 06:34:14 +00004056 CharUnits ElementSize;
4057 if (!HandleSizeof(Info, ElementType, ElementSize))
4058 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004059
Richard Smithd62306a2011-11-10 06:34:14 +00004060 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00004061 RHSValue.getLValueOffset();
4062 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00004063 }
Richard Smith8b3497e2011-10-31 01:37:14 +00004064
4065 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4066 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4067 switch (E->getOpcode()) {
4068 default: llvm_unreachable("missing comparison operator");
4069 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4070 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4071 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4072 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4073 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4074 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00004075 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004076 }
4077 }
Douglas Gregorb90df602010-06-16 00:17:44 +00004078 if (!LHSTy->isIntegralOrEnumerationType() ||
4079 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004080 // We can't continue from here for non-integral types.
4081 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004082 }
4083
Anders Carlsson9c181652008-07-08 14:35:21 +00004084 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00004085 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00004086 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004087 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00004088
Richard Smith11562c52011-10-28 17:51:58 +00004089 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004090 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004091 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00004092
4093 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00004094 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00004095 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4096 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00004097 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00004098 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00004099 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00004100 LHSVal.getLValueOffset() -= AdditionalOffset;
4101 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00004102 return true;
4103 }
4104
4105 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00004106 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00004107 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004108 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4109 LHSVal.getInt().getZExtValue());
4110 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00004111 return true;
4112 }
4113
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004114 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4115 // Handle (intptr_t)&&A - (intptr_t)&&B.
4116 // FIXME: We're missing a check that both labels have the same
4117 // associated function; I'm not sure how to write this check.
4118 if (!LHSVal.getLValueOffset().isZero() ||
4119 !RHSVal.getLValueOffset().isZero())
4120 return false;
4121 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4122 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4123 if (!LHSExpr || !RHSExpr)
4124 return false;
4125 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4126 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4127 if (!LHSAddrExpr || !RHSAddrExpr)
4128 return false;
4129 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4130 return true;
4131 }
4132
Eli Friedman94c25c62009-03-24 01:14:50 +00004133 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00004134 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004135 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004136
Richard Smith11562c52011-10-28 17:51:58 +00004137 APSInt &LHS = LHSVal.getInt();
4138 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00004139
Anders Carlsson9c181652008-07-08 14:35:21 +00004140 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004141 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004142 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004143 case BO_Mul: return Success(LHS * RHS, E);
4144 case BO_Add: return Success(LHS + RHS, E);
4145 case BO_Sub: return Success(LHS - RHS, E);
4146 case BO_And: return Success(LHS & RHS, E);
4147 case BO_Xor: return Success(LHS ^ RHS, E);
4148 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004149 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00004150 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004151 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004152 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004153 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00004154 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004155 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004156 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004157 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00004158 // During constant-folding, a negative shift is an opposite shift.
4159 if (RHS.isSigned() && RHS.isNegative()) {
4160 RHS = -RHS;
4161 goto shift_right;
4162 }
4163
4164 shift_left:
4165 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00004166 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4167 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004168 }
John McCalle3027922010-08-25 11:45:40 +00004169 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00004170 // During constant-folding, a negative shift is an opposite shift.
4171 if (RHS.isSigned() && RHS.isNegative()) {
4172 RHS = -RHS;
4173 goto shift_left;
4174 }
4175
4176 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00004177 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00004178 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4179 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004180 }
Mike Stump11289f42009-09-09 15:08:12 +00004181
Richard Smith11562c52011-10-28 17:51:58 +00004182 case BO_LT: return Success(LHS < RHS, E);
4183 case BO_GT: return Success(LHS > RHS, E);
4184 case BO_LE: return Success(LHS <= RHS, E);
4185 case BO_GE: return Success(LHS >= RHS, E);
4186 case BO_EQ: return Success(LHS == RHS, E);
4187 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00004188 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004189}
4190
Ken Dyck160146e2010-01-27 17:10:57 +00004191CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00004192 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4193 // the result is the size of the referenced type."
4194 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4195 // result shall be the alignment of the referenced type."
4196 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4197 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00004198
4199 // __alignof is defined to return the preferred alignment.
4200 return Info.Ctx.toCharUnitsFromBits(
4201 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00004202}
4203
Ken Dyck160146e2010-01-27 17:10:57 +00004204CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00004205 E = E->IgnoreParens();
4206
4207 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00004208 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00004209 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004210 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4211 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00004212
Chris Lattner68061312009-01-24 21:53:27 +00004213 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004214 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4215 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00004216
Chris Lattner24aeeab2009-01-24 21:09:06 +00004217 return GetAlignOfType(E->getType());
4218}
4219
4220
Peter Collingbournee190dee2011-03-11 19:24:49 +00004221/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4222/// a result as the expression's type.
4223bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4224 const UnaryExprOrTypeTraitExpr *E) {
4225 switch(E->getKind()) {
4226 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00004227 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00004228 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004229 else
Ken Dyckdbc01912011-03-11 02:13:43 +00004230 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004231 }
Eli Friedman64004332009-03-23 04:38:34 +00004232
Peter Collingbournee190dee2011-03-11 19:24:49 +00004233 case UETT_VecStep: {
4234 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00004235
Peter Collingbournee190dee2011-03-11 19:24:49 +00004236 if (Ty->isVectorType()) {
4237 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00004238
Peter Collingbournee190dee2011-03-11 19:24:49 +00004239 // The vec_step built-in functions that take a 3-component
4240 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4241 if (n == 3)
4242 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00004243
Peter Collingbournee190dee2011-03-11 19:24:49 +00004244 return Success(n, E);
4245 } else
4246 return Success(1, E);
4247 }
4248
4249 case UETT_SizeOf: {
4250 QualType SrcTy = E->getTypeOfArgument();
4251 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4252 // the result is the size of the referenced type."
4253 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4254 // result shall be the alignment of the referenced type."
4255 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4256 SrcTy = Ref->getPointeeType();
4257
Richard Smithd62306a2011-11-10 06:34:14 +00004258 CharUnits Sizeof;
4259 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00004260 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004261 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004262 }
4263 }
4264
4265 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004266 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004267}
4268
Peter Collingbournee9200682011-05-13 03:29:01 +00004269bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00004270 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00004271 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00004272 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004273 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00004274 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00004275 for (unsigned i = 0; i != n; ++i) {
4276 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4277 switch (ON.getKind()) {
4278 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00004279 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00004280 APSInt IdxResult;
4281 if (!EvaluateInteger(Idx, IdxResult, Info))
4282 return false;
4283 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4284 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004285 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004286 CurrentType = AT->getElementType();
4287 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4288 Result += IdxResult.getSExtValue() * ElementSize;
4289 break;
4290 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004291
Douglas Gregor882211c2010-04-28 22:16:22 +00004292 case OffsetOfExpr::OffsetOfNode::Field: {
4293 FieldDecl *MemberDecl = ON.getField();
4294 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004295 if (!RT)
4296 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004297 RecordDecl *RD = RT->getDecl();
4298 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00004299 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00004300 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00004301 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00004302 CurrentType = MemberDecl->getType().getNonReferenceType();
4303 break;
4304 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004305
Douglas Gregor882211c2010-04-28 22:16:22 +00004306 case OffsetOfExpr::OffsetOfNode::Identifier:
4307 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004308 return Error(OOE);
4309
Douglas Gregord1702062010-04-29 00:18:15 +00004310 case OffsetOfExpr::OffsetOfNode::Base: {
4311 CXXBaseSpecifier *BaseSpec = ON.getBase();
4312 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004313 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004314
4315 // Find the layout of the class whose base we are looking into.
4316 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004317 if (!RT)
4318 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004319 RecordDecl *RD = RT->getDecl();
4320 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4321
4322 // Find the base class itself.
4323 CurrentType = BaseSpec->getType();
4324 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4325 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004326 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004327
4328 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00004329 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00004330 break;
4331 }
Douglas Gregor882211c2010-04-28 22:16:22 +00004332 }
4333 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004334 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004335}
4336
Chris Lattnere13042c2008-07-11 19:10:17 +00004337bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004338 switch (E->getOpcode()) {
4339 default:
4340 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4341 // See C99 6.6p3.
4342 return Error(E);
4343 case UO_Extension:
4344 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4345 // If so, we could clear the diagnostic ID.
4346 return Visit(E->getSubExpr());
4347 case UO_Plus:
4348 // The result is just the value.
4349 return Visit(E->getSubExpr());
4350 case UO_Minus: {
4351 if (!Visit(E->getSubExpr()))
4352 return false;
4353 if (!Result.isInt()) return Error(E);
4354 return Success(-Result.getInt(), E);
4355 }
4356 case UO_Not: {
4357 if (!Visit(E->getSubExpr()))
4358 return false;
4359 if (!Result.isInt()) return Error(E);
4360 return Success(~Result.getInt(), E);
4361 }
4362 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00004363 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00004364 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00004365 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004366 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004367 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004368 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004369}
Mike Stump11289f42009-09-09 15:08:12 +00004370
Chris Lattner477c4be2008-07-12 01:15:53 +00004371/// HandleCast - This is used to evaluate implicit or explicit casts where the
4372/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00004373bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4374 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004375 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00004376 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004377
Eli Friedmanc757de22011-03-25 00:43:55 +00004378 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00004379 case CK_BaseToDerived:
4380 case CK_DerivedToBase:
4381 case CK_UncheckedDerivedToBase:
4382 case CK_Dynamic:
4383 case CK_ToUnion:
4384 case CK_ArrayToPointerDecay:
4385 case CK_FunctionToPointerDecay:
4386 case CK_NullToPointer:
4387 case CK_NullToMemberPointer:
4388 case CK_BaseToDerivedMemberPointer:
4389 case CK_DerivedToBaseMemberPointer:
4390 case CK_ConstructorConversion:
4391 case CK_IntegralToPointer:
4392 case CK_ToVoid:
4393 case CK_VectorSplat:
4394 case CK_IntegralToFloating:
4395 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004396 case CK_CPointerToObjCPointerCast:
4397 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004398 case CK_AnyPointerToBlockPointerCast:
4399 case CK_ObjCObjectLValueCast:
4400 case CK_FloatingRealToComplex:
4401 case CK_FloatingComplexToReal:
4402 case CK_FloatingComplexCast:
4403 case CK_FloatingComplexToIntegralComplex:
4404 case CK_IntegralRealToComplex:
4405 case CK_IntegralComplexCast:
4406 case CK_IntegralComplexToFloatingComplex:
4407 llvm_unreachable("invalid cast kind for integral value");
4408
Eli Friedman9faf2f92011-03-25 19:07:11 +00004409 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004410 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004411 case CK_LValueBitCast:
4412 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00004413 case CK_ARCProduceObject:
4414 case CK_ARCConsumeObject:
4415 case CK_ARCReclaimReturnedObject:
4416 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004417 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004418
4419 case CK_LValueToRValue:
4420 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004421 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004422
4423 case CK_MemberPointerToBoolean:
4424 case CK_PointerToBoolean:
4425 case CK_IntegralToBoolean:
4426 case CK_FloatingToBoolean:
4427 case CK_FloatingComplexToBoolean:
4428 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004429 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00004430 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004431 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004432 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004433 }
4434
Eli Friedmanc757de22011-03-25 00:43:55 +00004435 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00004436 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00004437 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004438
Eli Friedman742421e2009-02-20 01:15:07 +00004439 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004440 // Allow casts of address-of-label differences if they are no-ops
4441 // or narrowing. (The narrowing case isn't actually guaranteed to
4442 // be constant-evaluatable except in some narrow cases which are hard
4443 // to detect here. We let it through on the assumption the user knows
4444 // what they are doing.)
4445 if (Result.isAddrLabelDiff())
4446 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00004447 // Only allow casts of lvalues if they are lossless.
4448 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4449 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004450
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004451 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004452 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00004453 }
Mike Stump11289f42009-09-09 15:08:12 +00004454
Eli Friedmanc757de22011-03-25 00:43:55 +00004455 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004456 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4457
John McCall45d55e42010-05-07 21:00:08 +00004458 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00004459 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00004460 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00004461
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004462 if (LV.getLValueBase()) {
4463 // Only allow based lvalue casts if they are lossless.
4464 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004465 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004466
Richard Smithcf74da72011-11-16 07:18:12 +00004467 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004468 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004469 return true;
4470 }
4471
Ken Dyck02990832010-01-15 12:37:54 +00004472 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4473 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004474 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004475 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004476
Eli Friedmanc757de22011-03-25 00:43:55 +00004477 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00004478 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004479 if (!EvaluateComplex(SubExpr, C, Info))
4480 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00004481 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004482 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00004483
Eli Friedmanc757de22011-03-25 00:43:55 +00004484 case CK_FloatingToIntegral: {
4485 APFloat F(0.0);
4486 if (!EvaluateFloat(SubExpr, F, Info))
4487 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00004488
Richard Smith357362d2011-12-13 06:39:58 +00004489 APSInt Value;
4490 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4491 return false;
4492 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004493 }
4494 }
Mike Stump11289f42009-09-09 15:08:12 +00004495
Eli Friedmanc757de22011-03-25 00:43:55 +00004496 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004497 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00004498}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004499
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004500bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4501 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004502 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004503 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4504 return false;
4505 if (!LV.isComplexInt())
4506 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004507 return Success(LV.getComplexIntReal(), E);
4508 }
4509
4510 return Visit(E->getSubExpr());
4511}
4512
Eli Friedman4e7a2412009-02-27 04:45:43 +00004513bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004514 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004515 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004516 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4517 return false;
4518 if (!LV.isComplexInt())
4519 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004520 return Success(LV.getComplexIntImag(), E);
4521 }
4522
Richard Smith4a678122011-10-24 18:44:57 +00004523 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00004524 return Success(0, E);
4525}
4526
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004527bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4528 return Success(E->getPackLength(), E);
4529}
4530
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004531bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4532 return Success(E->getValue(), E);
4533}
4534
Chris Lattner05706e882008-07-11 18:11:29 +00004535//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00004536// Float Evaluation
4537//===----------------------------------------------------------------------===//
4538
4539namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004540class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004541 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00004542 APFloat &Result;
4543public:
4544 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004545 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00004546
Richard Smith0b0a0b62011-10-29 20:57:55 +00004547 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004548 Result = V.getFloat();
4549 return true;
4550 }
Eli Friedman24c01542008-08-22 00:06:13 +00004551
Richard Smithfddd3842011-12-30 21:15:51 +00004552 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004553 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4554 return true;
4555 }
4556
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004557 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004558
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004559 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004560 bool VisitBinaryOperator(const BinaryOperator *E);
4561 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004562 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00004563
John McCallb1fb0d32010-05-07 22:08:54 +00004564 bool VisitUnaryReal(const UnaryOperator *E);
4565 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00004566
Richard Smithfddd3842011-12-30 21:15:51 +00004567 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00004568};
4569} // end anonymous namespace
4570
4571static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004572 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004573 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00004574}
4575
Jay Foad39c79802011-01-12 09:06:06 +00004576static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00004577 QualType ResultTy,
4578 const Expr *Arg,
4579 bool SNaN,
4580 llvm::APFloat &Result) {
4581 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4582 if (!S) return false;
4583
4584 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4585
4586 llvm::APInt fill;
4587
4588 // Treat empty strings as if they were zero.
4589 if (S->getString().empty())
4590 fill = llvm::APInt(32, 0);
4591 else if (S->getString().getAsInteger(0, fill))
4592 return false;
4593
4594 if (SNaN)
4595 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4596 else
4597 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4598 return true;
4599}
4600
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004601bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004602 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004603 default:
4604 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4605
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004606 case Builtin::BI__builtin_huge_val:
4607 case Builtin::BI__builtin_huge_valf:
4608 case Builtin::BI__builtin_huge_vall:
4609 case Builtin::BI__builtin_inf:
4610 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004611 case Builtin::BI__builtin_infl: {
4612 const llvm::fltSemantics &Sem =
4613 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00004614 Result = llvm::APFloat::getInf(Sem);
4615 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004616 }
Mike Stump11289f42009-09-09 15:08:12 +00004617
John McCall16291492010-02-28 13:00:19 +00004618 case Builtin::BI__builtin_nans:
4619 case Builtin::BI__builtin_nansf:
4620 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004621 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4622 true, Result))
4623 return Error(E);
4624 return true;
John McCall16291492010-02-28 13:00:19 +00004625
Chris Lattner0b7282e2008-10-06 06:31:58 +00004626 case Builtin::BI__builtin_nan:
4627 case Builtin::BI__builtin_nanf:
4628 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00004629 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00004630 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004631 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4632 false, Result))
4633 return Error(E);
4634 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004635
4636 case Builtin::BI__builtin_fabs:
4637 case Builtin::BI__builtin_fabsf:
4638 case Builtin::BI__builtin_fabsl:
4639 if (!EvaluateFloat(E->getArg(0), Result, Info))
4640 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004641
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004642 if (Result.isNegative())
4643 Result.changeSign();
4644 return true;
4645
Mike Stump11289f42009-09-09 15:08:12 +00004646 case Builtin::BI__builtin_copysign:
4647 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004648 case Builtin::BI__builtin_copysignl: {
4649 APFloat RHS(0.);
4650 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4651 !EvaluateFloat(E->getArg(1), RHS, Info))
4652 return false;
4653 Result.copySign(RHS);
4654 return true;
4655 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004656 }
4657}
4658
John McCallb1fb0d32010-05-07 22:08:54 +00004659bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004660 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4661 ComplexValue CV;
4662 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4663 return false;
4664 Result = CV.FloatReal;
4665 return true;
4666 }
4667
4668 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004669}
4670
4671bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004672 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4673 ComplexValue CV;
4674 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4675 return false;
4676 Result = CV.FloatImag;
4677 return true;
4678 }
4679
Richard Smith4a678122011-10-24 18:44:57 +00004680 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004681 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4682 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004683 return true;
4684}
4685
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004686bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004687 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004688 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004689 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004690 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004691 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004692 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4693 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004694 Result.changeSign();
4695 return true;
4696 }
4697}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004698
Eli Friedman24c01542008-08-22 00:06:13 +00004699bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004700 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4701 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004702
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004703 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004704 if (!EvaluateFloat(E->getLHS(), Result, Info))
4705 return false;
4706 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4707 return false;
4708
4709 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004710 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004711 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004712 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4713 return true;
John McCalle3027922010-08-25 11:45:40 +00004714 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004715 Result.add(RHS, APFloat::rmNearestTiesToEven);
4716 return true;
John McCalle3027922010-08-25 11:45:40 +00004717 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004718 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4719 return true;
John McCalle3027922010-08-25 11:45:40 +00004720 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004721 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4722 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004723 }
4724}
4725
4726bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4727 Result = E->getValue();
4728 return true;
4729}
4730
Peter Collingbournee9200682011-05-13 03:29:01 +00004731bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4732 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004733
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004734 switch (E->getCastKind()) {
4735 default:
Richard Smith11562c52011-10-28 17:51:58 +00004736 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004737
4738 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004739 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00004740 return EvaluateInteger(SubExpr, IntResult, Info) &&
4741 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4742 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004743 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004744
4745 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004746 if (!Visit(SubExpr))
4747 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004748 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4749 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004750 }
John McCalld7646252010-11-14 08:17:51 +00004751
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004752 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004753 ComplexValue V;
4754 if (!EvaluateComplex(SubExpr, V, Info))
4755 return false;
4756 Result = V.getComplexFloatReal();
4757 return true;
4758 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004759 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004760
Richard Smithf57d8cb2011-12-09 22:58:01 +00004761 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004762}
4763
Eli Friedman24c01542008-08-22 00:06:13 +00004764//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004765// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004766//===----------------------------------------------------------------------===//
4767
4768namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004769class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004770 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004771 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004772
Anders Carlsson537969c2008-11-16 20:27:53 +00004773public:
John McCall93d91dc2010-05-07 17:22:02 +00004774 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004775 : ExprEvaluatorBaseTy(info), Result(Result) {}
4776
Richard Smith0b0a0b62011-10-29 20:57:55 +00004777 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004778 Result.setFrom(V);
4779 return true;
4780 }
Mike Stump11289f42009-09-09 15:08:12 +00004781
Anders Carlsson537969c2008-11-16 20:27:53 +00004782 //===--------------------------------------------------------------------===//
4783 // Visitor Methods
4784 //===--------------------------------------------------------------------===//
4785
Peter Collingbournee9200682011-05-13 03:29:01 +00004786 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00004787
Peter Collingbournee9200682011-05-13 03:29:01 +00004788 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004789
John McCall93d91dc2010-05-07 17:22:02 +00004790 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004791 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004792 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00004793};
4794} // end anonymous namespace
4795
John McCall93d91dc2010-05-07 17:22:02 +00004796static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4797 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004798 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004799 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004800}
4801
Peter Collingbournee9200682011-05-13 03:29:01 +00004802bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4803 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004804
4805 if (SubExpr->getType()->isRealFloatingType()) {
4806 Result.makeComplexFloat();
4807 APFloat &Imag = Result.FloatImag;
4808 if (!EvaluateFloat(SubExpr, Imag, Info))
4809 return false;
4810
4811 Result.FloatReal = APFloat(Imag.getSemantics());
4812 return true;
4813 } else {
4814 assert(SubExpr->getType()->isIntegerType() &&
4815 "Unexpected imaginary literal.");
4816
4817 Result.makeComplexInt();
4818 APSInt &Imag = Result.IntImag;
4819 if (!EvaluateInteger(SubExpr, Imag, Info))
4820 return false;
4821
4822 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4823 return true;
4824 }
4825}
4826
Peter Collingbournee9200682011-05-13 03:29:01 +00004827bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004828
John McCallfcef3cf2010-12-14 17:51:41 +00004829 switch (E->getCastKind()) {
4830 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004831 case CK_BaseToDerived:
4832 case CK_DerivedToBase:
4833 case CK_UncheckedDerivedToBase:
4834 case CK_Dynamic:
4835 case CK_ToUnion:
4836 case CK_ArrayToPointerDecay:
4837 case CK_FunctionToPointerDecay:
4838 case CK_NullToPointer:
4839 case CK_NullToMemberPointer:
4840 case CK_BaseToDerivedMemberPointer:
4841 case CK_DerivedToBaseMemberPointer:
4842 case CK_MemberPointerToBoolean:
4843 case CK_ConstructorConversion:
4844 case CK_IntegralToPointer:
4845 case CK_PointerToIntegral:
4846 case CK_PointerToBoolean:
4847 case CK_ToVoid:
4848 case CK_VectorSplat:
4849 case CK_IntegralCast:
4850 case CK_IntegralToBoolean:
4851 case CK_IntegralToFloating:
4852 case CK_FloatingToIntegral:
4853 case CK_FloatingToBoolean:
4854 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004855 case CK_CPointerToObjCPointerCast:
4856 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004857 case CK_AnyPointerToBlockPointerCast:
4858 case CK_ObjCObjectLValueCast:
4859 case CK_FloatingComplexToReal:
4860 case CK_FloatingComplexToBoolean:
4861 case CK_IntegralComplexToReal:
4862 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004863 case CK_ARCProduceObject:
4864 case CK_ARCConsumeObject:
4865 case CK_ARCReclaimReturnedObject:
4866 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004867 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004868
John McCallfcef3cf2010-12-14 17:51:41 +00004869 case CK_LValueToRValue:
4870 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004871 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004872
4873 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004874 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004875 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004876 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004877
4878 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004879 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004880 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004881 return false;
4882
John McCallfcef3cf2010-12-14 17:51:41 +00004883 Result.makeComplexFloat();
4884 Result.FloatImag = APFloat(Real.getSemantics());
4885 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004886 }
4887
John McCallfcef3cf2010-12-14 17:51:41 +00004888 case CK_FloatingComplexCast: {
4889 if (!Visit(E->getSubExpr()))
4890 return false;
4891
4892 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4893 QualType From
4894 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4895
Richard Smith357362d2011-12-13 06:39:58 +00004896 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4897 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004898 }
4899
4900 case CK_FloatingComplexToIntegralComplex: {
4901 if (!Visit(E->getSubExpr()))
4902 return false;
4903
4904 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4905 QualType From
4906 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4907 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00004908 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4909 To, Result.IntReal) &&
4910 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4911 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004912 }
4913
4914 case CK_IntegralRealToComplex: {
4915 APSInt &Real = Result.IntReal;
4916 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4917 return false;
4918
4919 Result.makeComplexInt();
4920 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4921 return true;
4922 }
4923
4924 case CK_IntegralComplexCast: {
4925 if (!Visit(E->getSubExpr()))
4926 return false;
4927
4928 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4929 QualType From
4930 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4931
4932 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4933 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4934 return true;
4935 }
4936
4937 case CK_IntegralComplexToFloatingComplex: {
4938 if (!Visit(E->getSubExpr()))
4939 return false;
4940
4941 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4942 QualType From
4943 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4944 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00004945 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4946 To, Result.FloatReal) &&
4947 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4948 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004949 }
4950 }
4951
4952 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004953 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004954}
4955
John McCall93d91dc2010-05-07 17:22:02 +00004956bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004957 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00004958 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4959
John McCall93d91dc2010-05-07 17:22:02 +00004960 if (!Visit(E->getLHS()))
4961 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004962
John McCall93d91dc2010-05-07 17:22:02 +00004963 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004964 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00004965 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004966
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004967 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4968 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004969 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004970 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004971 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004972 if (Result.isComplexFloat()) {
4973 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4974 APFloat::rmNearestTiesToEven);
4975 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4976 APFloat::rmNearestTiesToEven);
4977 } else {
4978 Result.getComplexIntReal() += RHS.getComplexIntReal();
4979 Result.getComplexIntImag() += RHS.getComplexIntImag();
4980 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004981 break;
John McCalle3027922010-08-25 11:45:40 +00004982 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004983 if (Result.isComplexFloat()) {
4984 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4985 APFloat::rmNearestTiesToEven);
4986 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4987 APFloat::rmNearestTiesToEven);
4988 } else {
4989 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4990 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4991 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004992 break;
John McCalle3027922010-08-25 11:45:40 +00004993 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004994 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00004995 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004996 APFloat &LHS_r = LHS.getComplexFloatReal();
4997 APFloat &LHS_i = LHS.getComplexFloatImag();
4998 APFloat &RHS_r = RHS.getComplexFloatReal();
4999 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00005000
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005001 APFloat Tmp = LHS_r;
5002 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5003 Result.getComplexFloatReal() = Tmp;
5004 Tmp = LHS_i;
5005 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5006 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5007
5008 Tmp = LHS_r;
5009 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5010 Result.getComplexFloatImag() = Tmp;
5011 Tmp = LHS_i;
5012 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5013 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5014 } else {
John McCall93d91dc2010-05-07 17:22:02 +00005015 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00005016 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005017 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5018 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00005019 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005020 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5021 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5022 }
5023 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005024 case BO_Div:
5025 if (Result.isComplexFloat()) {
5026 ComplexValue LHS = Result;
5027 APFloat &LHS_r = LHS.getComplexFloatReal();
5028 APFloat &LHS_i = LHS.getComplexFloatImag();
5029 APFloat &RHS_r = RHS.getComplexFloatReal();
5030 APFloat &RHS_i = RHS.getComplexFloatImag();
5031 APFloat &Res_r = Result.getComplexFloatReal();
5032 APFloat &Res_i = Result.getComplexFloatImag();
5033
5034 APFloat Den = RHS_r;
5035 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5036 APFloat Tmp = RHS_i;
5037 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5038 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5039
5040 Res_r = LHS_r;
5041 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5042 Tmp = LHS_i;
5043 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5044 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5045 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5046
5047 Res_i = LHS_i;
5048 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5049 Tmp = LHS_r;
5050 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5051 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5052 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5053 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005054 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5055 return Error(E, diag::note_expr_divide_by_zero);
5056
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005057 ComplexValue LHS = Result;
5058 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5059 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5060 Result.getComplexIntReal() =
5061 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5062 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5063 Result.getComplexIntImag() =
5064 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5065 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5066 }
5067 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005068 }
5069
John McCall93d91dc2010-05-07 17:22:02 +00005070 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005071}
5072
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005073bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5074 // Get the operand value into 'Result'.
5075 if (!Visit(E->getSubExpr()))
5076 return false;
5077
5078 switch (E->getOpcode()) {
5079 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005080 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005081 case UO_Extension:
5082 return true;
5083 case UO_Plus:
5084 // The result is always just the subexpr.
5085 return true;
5086 case UO_Minus:
5087 if (Result.isComplexFloat()) {
5088 Result.getComplexFloatReal().changeSign();
5089 Result.getComplexFloatImag().changeSign();
5090 }
5091 else {
5092 Result.getComplexIntReal() = -Result.getComplexIntReal();
5093 Result.getComplexIntImag() = -Result.getComplexIntImag();
5094 }
5095 return true;
5096 case UO_Not:
5097 if (Result.isComplexFloat())
5098 Result.getComplexFloatImag().changeSign();
5099 else
5100 Result.getComplexIntImag() = -Result.getComplexIntImag();
5101 return true;
5102 }
5103}
5104
Anders Carlsson537969c2008-11-16 20:27:53 +00005105//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00005106// Void expression evaluation, primarily for a cast to void on the LHS of a
5107// comma operator
5108//===----------------------------------------------------------------------===//
5109
5110namespace {
5111class VoidExprEvaluator
5112 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5113public:
5114 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5115
5116 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00005117
5118 bool VisitCastExpr(const CastExpr *E) {
5119 switch (E->getCastKind()) {
5120 default:
5121 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5122 case CK_ToVoid:
5123 VisitIgnoredValue(E->getSubExpr());
5124 return true;
5125 }
5126 }
5127};
5128} // end anonymous namespace
5129
5130static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5131 assert(E->isRValue() && E->getType()->isVoidType());
5132 return VoidExprEvaluator(Info).Visit(E);
5133}
5134
5135//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00005136// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00005137//===----------------------------------------------------------------------===//
5138
Richard Smith0b0a0b62011-10-29 20:57:55 +00005139static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005140 // In C, function designators are not lvalues, but we evaluate them as if they
5141 // are.
5142 if (E->isGLValue() || E->getType()->isFunctionType()) {
5143 LValue LV;
5144 if (!EvaluateLValue(E, LV, Info))
5145 return false;
5146 LV.moveInto(Result);
5147 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005148 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005149 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005150 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005151 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005152 return false;
John McCall45d55e42010-05-07 21:00:08 +00005153 } else if (E->getType()->hasPointerRepresentation()) {
5154 LValue LV;
5155 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005156 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005157 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00005158 } else if (E->getType()->isRealFloatingType()) {
5159 llvm::APFloat F(0.0);
5160 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005161 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005162 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00005163 } else if (E->getType()->isAnyComplexType()) {
5164 ComplexValue C;
5165 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005166 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005167 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00005168 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00005169 MemberPtr P;
5170 if (!EvaluateMemberPointer(E, P, Info))
5171 return false;
5172 P.moveInto(Result);
5173 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00005174 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005175 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005176 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005177 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00005178 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005179 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00005180 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005181 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005182 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005183 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5184 return false;
5185 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00005186 } else if (E->getType()->isVoidType()) {
Richard Smith357362d2011-12-13 06:39:58 +00005187 if (Info.getLangOpts().CPlusPlus0x)
5188 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5189 << E->getType();
5190 else
5191 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith42d3af92011-12-07 00:43:50 +00005192 if (!EvaluateVoid(E, Info))
5193 return false;
Richard Smith357362d2011-12-13 06:39:58 +00005194 } else if (Info.getLangOpts().CPlusPlus0x) {
5195 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5196 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005197 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00005198 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00005199 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005200 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005201
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00005202 return true;
5203}
5204
Richard Smithed5165f2011-11-04 05:33:44 +00005205/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5206/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5207/// since later initializers for an object can indirectly refer to subobjects
5208/// which were initialized earlier.
5209static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +00005210 const LValue &This, const Expr *E,
5211 CheckConstantExpressionKind CCEK) {
Richard Smithfddd3842011-12-30 21:15:51 +00005212 if (!CheckLiteralType(Info, E))
5213 return false;
5214
5215 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00005216 // Evaluate arrays and record types in-place, so that later initializers can
5217 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00005218 if (E->getType()->isArrayType())
5219 return EvaluateArray(E, This, Result, Info);
5220 else if (E->getType()->isRecordType())
5221 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00005222 }
5223
5224 // For any other type, in-place evaluation is unimportant.
5225 CCValue CoreConstResult;
5226 return Evaluate(CoreConstResult, Info, E) &&
Richard Smith357362d2011-12-13 06:39:58 +00005227 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smithed5165f2011-11-04 05:33:44 +00005228}
5229
Richard Smithf57d8cb2011-12-09 22:58:01 +00005230/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5231/// lvalue-to-rvalue cast if it is an lvalue.
5232static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00005233 if (!CheckLiteralType(Info, E))
5234 return false;
5235
Richard Smithf57d8cb2011-12-09 22:58:01 +00005236 CCValue Value;
5237 if (!::Evaluate(Value, Info, E))
5238 return false;
5239
5240 if (E->isGLValue()) {
5241 LValue LV;
5242 LV.setFrom(Value);
5243 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5244 return false;
5245 }
5246
5247 // Check this core constant expression is a constant expression, and if so,
5248 // convert it to one.
5249 return CheckConstantExpression(Info, E, Value, Result);
5250}
Richard Smith11562c52011-10-28 17:51:58 +00005251
Richard Smith7b553f12011-10-29 00:50:52 +00005252/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00005253/// any crazy technique (that has nothing to do with language standards) that
5254/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00005255/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5256/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00005257bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00005258 // Fast-path evaluations of integer literals, since we sometimes see files
5259 // containing vast quantities of these.
5260 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5261 Result.Val = APValue(APSInt(L->getValue(),
5262 L->getType()->isUnsignedIntegerType()));
5263 return true;
5264 }
5265
Richard Smith5686e752011-11-10 03:30:42 +00005266 // FIXME: Evaluating initializers for large arrays can cause performance
5267 // problems, and we don't use such values yet. Once we have a more efficient
5268 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00005269 // The same problem affects large records.
5270 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5271 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00005272 return false;
5273
Richard Smithd62306a2011-11-10 06:34:14 +00005274 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005275 EvalInfo Info(Ctx, Result);
5276 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00005277}
5278
Jay Foad39c79802011-01-12 09:06:06 +00005279bool Expr::EvaluateAsBooleanCondition(bool &Result,
5280 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00005281 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00005282 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00005283 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00005284 Result);
John McCall1be1c632010-01-05 23:42:56 +00005285}
5286
Richard Smith5fab0c92011-12-28 19:48:30 +00005287bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5288 SideEffectsKind AllowSideEffects) const {
5289 if (!getType()->isIntegralOrEnumerationType())
5290 return false;
5291
Richard Smith11562c52011-10-28 17:51:58 +00005292 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00005293 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5294 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00005295 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005296
Richard Smith11562c52011-10-28 17:51:58 +00005297 Result = ExprResult.Val.getInt();
5298 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00005299}
5300
Jay Foad39c79802011-01-12 09:06:06 +00005301bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00005302 EvalInfo Info(Ctx, Result);
5303
John McCall45d55e42010-05-07 21:00:08 +00005304 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00005305 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smith357362d2011-12-13 06:39:58 +00005306 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5307 CCEK_Constant);
Eli Friedman7d45c482009-09-13 10:17:44 +00005308}
5309
Richard Smithd0b4dd62011-12-19 06:19:21 +00005310bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5311 const VarDecl *VD,
5312 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
5313 Expr::EvalStatus EStatus;
5314 EStatus.Diag = &Notes;
5315
5316 EvalInfo InitInfo(Ctx, EStatus);
5317 InitInfo.setEvaluatingDecl(VD, Value);
5318
Richard Smithfddd3842011-12-30 21:15:51 +00005319 if (!CheckLiteralType(InitInfo, this))
5320 return false;
5321
Richard Smithd0b4dd62011-12-19 06:19:21 +00005322 LValue LVal;
5323 LVal.set(VD);
5324
Richard Smithfddd3842011-12-30 21:15:51 +00005325 // C++11 [basic.start.init]p2:
5326 // Variables with static storage duration or thread storage duration shall be
5327 // zero-initialized before any other initialization takes place.
5328 // This behavior is not present in C.
5329 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5330 !VD->getType()->isReferenceType()) {
5331 ImplicitValueInitExpr VIE(VD->getType());
5332 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5333 return false;
5334 }
5335
Richard Smithd0b4dd62011-12-19 06:19:21 +00005336 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5337 !EStatus.HasSideEffects;
5338}
5339
Richard Smith7b553f12011-10-29 00:50:52 +00005340/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5341/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00005342bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00005343 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00005344 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00005345}
Anders Carlsson59689ed2008-11-22 21:04:56 +00005346
Jay Foad39c79802011-01-12 09:06:06 +00005347bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00005348 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005349}
5350
Richard Smithcaf33902011-10-10 18:28:20 +00005351APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005352 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005353 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00005354 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00005355 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005356 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00005357
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005358 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00005359}
John McCall864e3962010-05-07 05:32:02 +00005360
Abramo Bagnaraf8199452010-05-14 17:07:14 +00005361 bool Expr::EvalResult::isGlobalLValue() const {
5362 assert(Val.isLValue());
5363 return IsGlobalLValue(Val.getLValueBase());
5364 }
5365
5366
John McCall864e3962010-05-07 05:32:02 +00005367/// isIntegerConstantExpr - this recursive routine will test if an expression is
5368/// an integer constant expression.
5369
5370/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5371/// comma, etc
5372///
5373/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5374/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5375/// cast+dereference.
5376
5377// CheckICE - This function does the fundamental ICE checking: the returned
5378// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5379// Note that to reduce code duplication, this helper does no evaluation
5380// itself; the caller checks whether the expression is evaluatable, and
5381// in the rare cases where CheckICE actually cares about the evaluated
5382// value, it calls into Evalute.
5383//
5384// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00005385// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00005386// 1: This expression is not an ICE, but if it isn't evaluated, it's
5387// a legal subexpression for an ICE. This return value is used to handle
5388// the comma operator in C99 mode.
5389// 2: This expression is not an ICE, and is not a legal subexpression for one.
5390
Dan Gohman28ade552010-07-26 21:25:24 +00005391namespace {
5392
John McCall864e3962010-05-07 05:32:02 +00005393struct ICEDiag {
5394 unsigned Val;
5395 SourceLocation Loc;
5396
5397 public:
5398 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5399 ICEDiag() : Val(0) {}
5400};
5401
Dan Gohman28ade552010-07-26 21:25:24 +00005402}
5403
5404static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00005405
5406static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5407 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005408 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005409 !EVResult.Val.isInt()) {
5410 return ICEDiag(2, E->getLocStart());
5411 }
5412 return NoDiag();
5413}
5414
5415static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5416 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00005417 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00005418 return ICEDiag(2, E->getLocStart());
5419 }
5420
5421 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00005422#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00005423#define STMT(Node, Base) case Expr::Node##Class:
5424#define EXPR(Node, Base)
5425#include "clang/AST/StmtNodes.inc"
5426 case Expr::PredefinedExprClass:
5427 case Expr::FloatingLiteralClass:
5428 case Expr::ImaginaryLiteralClass:
5429 case Expr::StringLiteralClass:
5430 case Expr::ArraySubscriptExprClass:
5431 case Expr::MemberExprClass:
5432 case Expr::CompoundAssignOperatorClass:
5433 case Expr::CompoundLiteralExprClass:
5434 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00005435 case Expr::DesignatedInitExprClass:
5436 case Expr::ImplicitValueInitExprClass:
5437 case Expr::ParenListExprClass:
5438 case Expr::VAArgExprClass:
5439 case Expr::AddrLabelExprClass:
5440 case Expr::StmtExprClass:
5441 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00005442 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00005443 case Expr::CXXDynamicCastExprClass:
5444 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00005445 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00005446 case Expr::CXXNullPtrLiteralExprClass:
5447 case Expr::CXXThisExprClass:
5448 case Expr::CXXThrowExprClass:
5449 case Expr::CXXNewExprClass:
5450 case Expr::CXXDeleteExprClass:
5451 case Expr::CXXPseudoDestructorExprClass:
5452 case Expr::UnresolvedLookupExprClass:
5453 case Expr::DependentScopeDeclRefExprClass:
5454 case Expr::CXXConstructExprClass:
5455 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00005456 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00005457 case Expr::CXXTemporaryObjectExprClass:
5458 case Expr::CXXUnresolvedConstructExprClass:
5459 case Expr::CXXDependentScopeMemberExprClass:
5460 case Expr::UnresolvedMemberExprClass:
5461 case Expr::ObjCStringLiteralClass:
5462 case Expr::ObjCEncodeExprClass:
5463 case Expr::ObjCMessageExprClass:
5464 case Expr::ObjCSelectorExprClass:
5465 case Expr::ObjCProtocolExprClass:
5466 case Expr::ObjCIvarRefExprClass:
5467 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00005468 case Expr::ObjCIsaExprClass:
5469 case Expr::ShuffleVectorExprClass:
5470 case Expr::BlockExprClass:
5471 case Expr::BlockDeclRefExprClass:
5472 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00005473 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005474 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00005475 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00005476 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00005477 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00005478 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00005479 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00005480 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005481 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005482 return ICEDiag(2, E->getLocStart());
5483
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005484 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00005485 case Expr::GNUNullExprClass:
5486 // GCC considers the GNU __null value to be an integral constant expression.
5487 return NoDiag();
5488
John McCall7c454bb2011-07-15 05:09:51 +00005489 case Expr::SubstNonTypeTemplateParmExprClass:
5490 return
5491 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5492
John McCall864e3962010-05-07 05:32:02 +00005493 case Expr::ParenExprClass:
5494 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00005495 case Expr::GenericSelectionExprClass:
5496 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005497 case Expr::IntegerLiteralClass:
5498 case Expr::CharacterLiteralClass:
5499 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00005500 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00005501 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005502 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00005503 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00005504 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005505 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00005506 return NoDiag();
5507 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00005508 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00005509 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5510 // constant expressions, but they can never be ICEs because an ICE cannot
5511 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00005512 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005513 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00005514 return CheckEvalInICE(E, Ctx);
5515 return ICEDiag(2, E->getLocStart());
5516 }
5517 case Expr::DeclRefExprClass:
5518 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5519 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00005520 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00005521 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5522
5523 // Parameter variables are never constants. Without this check,
5524 // getAnyInitializer() can find a default argument, which leads
5525 // to chaos.
5526 if (isa<ParmVarDecl>(D))
5527 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5528
5529 // C++ 7.1.5.1p2
5530 // A variable of non-volatile const-qualified integral or enumeration
5531 // type initialized by an ICE can be used in ICEs.
5532 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00005533 if (!Dcl->getType()->isIntegralOrEnumerationType())
5534 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5535
Richard Smithd0b4dd62011-12-19 06:19:21 +00005536 const VarDecl *VD;
5537 // Look for a declaration of this variable that has an initializer, and
5538 // check whether it is an ICE.
5539 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5540 return NoDiag();
5541 else
5542 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00005543 }
5544 }
5545 return ICEDiag(2, E->getLocStart());
5546 case Expr::UnaryOperatorClass: {
5547 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5548 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005549 case UO_PostInc:
5550 case UO_PostDec:
5551 case UO_PreInc:
5552 case UO_PreDec:
5553 case UO_AddrOf:
5554 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00005555 // C99 6.6/3 allows increment and decrement within unevaluated
5556 // subexpressions of constant expressions, but they can never be ICEs
5557 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005558 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00005559 case UO_Extension:
5560 case UO_LNot:
5561 case UO_Plus:
5562 case UO_Minus:
5563 case UO_Not:
5564 case UO_Real:
5565 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00005566 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005567 }
5568
5569 // OffsetOf falls through here.
5570 }
5571 case Expr::OffsetOfExprClass: {
5572 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00005573 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00005574 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00005575 // compliance: we should warn earlier for offsetof expressions with
5576 // array subscripts that aren't ICEs, and if the array subscripts
5577 // are ICEs, the value of the offsetof must be an integer constant.
5578 return CheckEvalInICE(E, Ctx);
5579 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00005580 case Expr::UnaryExprOrTypeTraitExprClass: {
5581 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5582 if ((Exp->getKind() == UETT_SizeOf) &&
5583 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00005584 return ICEDiag(2, E->getLocStart());
5585 return NoDiag();
5586 }
5587 case Expr::BinaryOperatorClass: {
5588 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5589 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005590 case BO_PtrMemD:
5591 case BO_PtrMemI:
5592 case BO_Assign:
5593 case BO_MulAssign:
5594 case BO_DivAssign:
5595 case BO_RemAssign:
5596 case BO_AddAssign:
5597 case BO_SubAssign:
5598 case BO_ShlAssign:
5599 case BO_ShrAssign:
5600 case BO_AndAssign:
5601 case BO_XorAssign:
5602 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00005603 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5604 // constant expressions, but they can never be ICEs because an ICE cannot
5605 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005606 return ICEDiag(2, E->getLocStart());
5607
John McCalle3027922010-08-25 11:45:40 +00005608 case BO_Mul:
5609 case BO_Div:
5610 case BO_Rem:
5611 case BO_Add:
5612 case BO_Sub:
5613 case BO_Shl:
5614 case BO_Shr:
5615 case BO_LT:
5616 case BO_GT:
5617 case BO_LE:
5618 case BO_GE:
5619 case BO_EQ:
5620 case BO_NE:
5621 case BO_And:
5622 case BO_Xor:
5623 case BO_Or:
5624 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00005625 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5626 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00005627 if (Exp->getOpcode() == BO_Div ||
5628 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00005629 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00005630 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00005631 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00005632 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005633 if (REval == 0)
5634 return ICEDiag(1, E->getLocStart());
5635 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00005636 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005637 if (LEval.isMinSignedValue())
5638 return ICEDiag(1, E->getLocStart());
5639 }
5640 }
5641 }
John McCalle3027922010-08-25 11:45:40 +00005642 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00005643 if (Ctx.getLangOptions().C99) {
5644 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5645 // if it isn't evaluated.
5646 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5647 return ICEDiag(1, E->getLocStart());
5648 } else {
5649 // In both C89 and C++, commas in ICEs are illegal.
5650 return ICEDiag(2, E->getLocStart());
5651 }
5652 }
5653 if (LHSResult.Val >= RHSResult.Val)
5654 return LHSResult;
5655 return RHSResult;
5656 }
John McCalle3027922010-08-25 11:45:40 +00005657 case BO_LAnd:
5658 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00005659 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5660 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5661 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5662 // Rare case where the RHS has a comma "side-effect"; we need
5663 // to actually check the condition to see whether the side
5664 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00005665 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00005666 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00005667 return RHSResult;
5668 return NoDiag();
5669 }
5670
5671 if (LHSResult.Val >= RHSResult.Val)
5672 return LHSResult;
5673 return RHSResult;
5674 }
5675 }
5676 }
5677 case Expr::ImplicitCastExprClass:
5678 case Expr::CStyleCastExprClass:
5679 case Expr::CXXFunctionalCastExprClass:
5680 case Expr::CXXStaticCastExprClass:
5681 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005682 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005683 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005684 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00005685 if (isa<ExplicitCastExpr>(E)) {
5686 if (const FloatingLiteral *FL
5687 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5688 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5689 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5690 APSInt IgnoredVal(DestWidth, !DestSigned);
5691 bool Ignored;
5692 // If the value does not fit in the destination type, the behavior is
5693 // undefined, so we are not required to treat it as a constant
5694 // expression.
5695 if (FL->getValue().convertToInteger(IgnoredVal,
5696 llvm::APFloat::rmTowardZero,
5697 &Ignored) & APFloat::opInvalidOp)
5698 return ICEDiag(2, E->getLocStart());
5699 return NoDiag();
5700 }
5701 }
Eli Friedman76d4e432011-09-29 21:49:34 +00005702 switch (cast<CastExpr>(E)->getCastKind()) {
5703 case CK_LValueToRValue:
5704 case CK_NoOp:
5705 case CK_IntegralToBoolean:
5706 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005707 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005708 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005709 return ICEDiag(2, E->getLocStart());
5710 }
John McCall864e3962010-05-07 05:32:02 +00005711 }
John McCallc07a0c72011-02-17 10:25:35 +00005712 case Expr::BinaryConditionalOperatorClass: {
5713 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5714 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5715 if (CommonResult.Val == 2) return CommonResult;
5716 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5717 if (FalseResult.Val == 2) return FalseResult;
5718 if (CommonResult.Val == 1) return CommonResult;
5719 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005720 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005721 return FalseResult;
5722 }
John McCall864e3962010-05-07 05:32:02 +00005723 case Expr::ConditionalOperatorClass: {
5724 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5725 // If the condition (ignoring parens) is a __builtin_constant_p call,
5726 // then only the true side is actually considered in an integer constant
5727 // expression, and it is fully evaluated. This is an important GNU
5728 // extension. See GCC PR38377 for discussion.
5729 if (const CallExpr *CallCE
5730 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00005731 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
5732 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00005733 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005734 if (CondResult.Val == 2)
5735 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005736
Richard Smithf57d8cb2011-12-09 22:58:01 +00005737 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5738 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005739
John McCall864e3962010-05-07 05:32:02 +00005740 if (TrueResult.Val == 2)
5741 return TrueResult;
5742 if (FalseResult.Val == 2)
5743 return FalseResult;
5744 if (CondResult.Val == 1)
5745 return CondResult;
5746 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5747 return NoDiag();
5748 // Rare case where the diagnostics depend on which side is evaluated
5749 // Note that if we get here, CondResult is 0, and at least one of
5750 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005751 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005752 return FalseResult;
5753 }
5754 return TrueResult;
5755 }
5756 case Expr::CXXDefaultArgExprClass:
5757 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5758 case Expr::ChooseExprClass: {
5759 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5760 }
5761 }
5762
5763 // Silence a GCC warning
5764 return ICEDiag(2, E->getLocStart());
5765}
5766
Richard Smithf57d8cb2011-12-09 22:58:01 +00005767/// Evaluate an expression as a C++11 integral constant expression.
5768static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5769 const Expr *E,
5770 llvm::APSInt *Value,
5771 SourceLocation *Loc) {
5772 if (!E->getType()->isIntegralOrEnumerationType()) {
5773 if (Loc) *Loc = E->getExprLoc();
5774 return false;
5775 }
5776
5777 Expr::EvalResult Result;
Richard Smith92b1ce02011-12-12 09:28:41 +00005778 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5779 Result.Diag = &Diags;
5780 EvalInfo Info(Ctx, Result);
5781
5782 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5783 if (!Diags.empty()) {
5784 IsICE = false;
5785 if (Loc) *Loc = Diags[0].first;
5786 } else if (!IsICE && Loc) {
5787 *Loc = E->getExprLoc();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005788 }
Richard Smith92b1ce02011-12-12 09:28:41 +00005789
5790 if (!IsICE)
5791 return false;
5792
5793 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5794 if (Value) *Value = Result.Val.getInt();
5795 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005796}
5797
Richard Smith92b1ce02011-12-12 09:28:41 +00005798bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005799 if (Ctx.getLangOptions().CPlusPlus0x)
5800 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5801
John McCall864e3962010-05-07 05:32:02 +00005802 ICEDiag d = CheckICE(this, Ctx);
5803 if (d.Val != 0) {
5804 if (Loc) *Loc = d.Loc;
5805 return false;
5806 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005807 return true;
5808}
5809
5810bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5811 SourceLocation *Loc, bool isEvaluated) const {
5812 if (Ctx.getLangOptions().CPlusPlus0x)
5813 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5814
5815 if (!isIntegerConstantExpr(Ctx, Loc))
5816 return false;
5817 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005818 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005819 return true;
5820}