blob: 46580697deec59ddbc4500bbc21f21a45c15319f [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) {}
Richard Smith0b0a0b62011-10-29 20:57:55 +0000213
Richard Smithfec09922011-11-01 16:57:24 +0000214 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000215 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +0000216 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000217 }
Richard Smith96e0c102011-11-04 02:25:55 +0000218 SubobjectDesignator &getLValueDesignator() {
219 assert(getKind() == LValue);
220 return Designator;
221 }
222 const SubobjectDesignator &getLValueDesignator() const {
223 return const_cast<CCValue*>(this)->getLValueDesignator();
224 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000225 };
226
Richard Smith254a73d2011-10-28 22:34:42 +0000227 /// A stack frame in the constexpr call stack.
228 struct CallStackFrame {
229 EvalInfo &Info;
230
231 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000232 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000233
Richard Smithf6f003a2011-12-16 19:06:07 +0000234 /// CallLoc - The location of the call expression for this call.
235 SourceLocation CallLoc;
236
237 /// Callee - The function which was called.
238 const FunctionDecl *Callee;
239
Richard Smithd62306a2011-11-10 06:34:14 +0000240 /// This - The binding for the this pointer in this call, if any.
241 const LValue *This;
242
Richard Smith254a73d2011-10-28 22:34:42 +0000243 /// ParmBindings - Parameter bindings for this function call, indexed by
244 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000245 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000246
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000247 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
248 typedef MapTy::const_iterator temp_iterator;
249 /// Temporaries - Temporary lvalues materialized within this stack frame.
250 MapTy Temporaries;
251
Richard Smithf6f003a2011-12-16 19:06:07 +0000252 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
253 const FunctionDecl *Callee, const LValue *This,
Richard Smithd62306a2011-11-10 06:34:14 +0000254 const CCValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000255 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000256 };
257
Richard Smith92b1ce02011-12-12 09:28:41 +0000258 /// A partial diagnostic which we might know in advance that we are not going
259 /// to emit.
260 class OptionalDiagnostic {
261 PartialDiagnostic *Diag;
262
263 public:
264 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
265
266 template<typename T>
267 OptionalDiagnostic &operator<<(const T &v) {
268 if (Diag)
269 *Diag << v;
270 return *this;
271 }
272 };
273
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000274 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000275 ASTContext &Ctx;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000276
277 /// EvalStatus - Contains information about the evaluation.
278 Expr::EvalStatus &EvalStatus;
279
280 /// CurrentCall - The top of the constexpr call stack.
281 CallStackFrame *CurrentCall;
282
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000283 /// CallStackDepth - The number of calls in the call stack right now.
284 unsigned CallStackDepth;
285
286 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
287 /// OpaqueValues - Values used as the common expression in a
288 /// BinaryConditionalOperator.
289 MapTy OpaqueValues;
290
291 /// BottomFrame - The frame in which evaluation started. This must be
292 /// initialized last.
293 CallStackFrame BottomFrame;
294
Richard Smithd62306a2011-11-10 06:34:14 +0000295 /// EvaluatingDecl - This is the declaration whose initializer is being
296 /// evaluated, if any.
297 const VarDecl *EvaluatingDecl;
298
299 /// EvaluatingDeclValue - This is the value being constructed for the
300 /// declaration whose initializer is being evaluated, if any.
301 APValue *EvaluatingDeclValue;
302
Richard Smith357362d2011-12-13 06:39:58 +0000303 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
304 /// notes attached to it will also be stored, otherwise they will not be.
305 bool HasActiveDiagnostic;
306
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000307
308 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith92b1ce02011-12-12 09:28:41 +0000309 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithf6f003a2011-12-16 19:06:07 +0000310 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
311 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000312
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000313 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
314 MapTy::const_iterator i = OpaqueValues.find(e);
315 if (i == OpaqueValues.end()) return 0;
316 return &i->second;
317 }
318
Richard Smithd62306a2011-11-10 06:34:14 +0000319 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
320 EvaluatingDecl = VD;
321 EvaluatingDeclValue = &Value;
322 }
323
Richard Smith9a568822011-11-21 19:36:32 +0000324 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
325
Richard Smith357362d2011-12-13 06:39:58 +0000326 bool CheckCallLimit(SourceLocation Loc) {
327 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
328 return true;
329 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
330 << getLangOpts().ConstexprCallDepth;
331 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000332 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000333
Richard Smith357362d2011-12-13 06:39:58 +0000334 private:
335 /// Add a diagnostic to the diagnostics list.
336 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
337 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
338 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
339 return EvalStatus.Diag->back().second;
340 }
341
Richard Smithf6f003a2011-12-16 19:06:07 +0000342 /// Add notes containing a call stack to the current point of evaluation.
343 void addCallStack(unsigned Limit);
344
Richard Smith357362d2011-12-13 06:39:58 +0000345 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000346 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000347 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
348 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000349 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000350 // If we have a prior diagnostic, it will be noting that the expression
351 // isn't a constant expression. This diagnostic is more important.
352 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000353 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000354 unsigned CallStackNotes = CallStackDepth - 1;
355 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
356 if (Limit)
357 CallStackNotes = std::min(CallStackNotes, Limit + 1);
358
Richard Smith357362d2011-12-13 06:39:58 +0000359 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000360 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000361 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
362 addDiag(Loc, DiagId);
363 addCallStack(Limit);
364 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000365 }
Richard Smith357362d2011-12-13 06:39:58 +0000366 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000367 return OptionalDiagnostic();
368 }
369
370 /// Diagnose that the evaluation does not produce a C++11 core constant
371 /// expression.
Richard Smithf2b681b2011-12-21 05:04:46 +0000372 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
373 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000374 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000375 // Don't override a previous diagnostic.
376 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
377 return OptionalDiagnostic();
Richard Smith357362d2011-12-13 06:39:58 +0000378 return Diag(Loc, DiagId, ExtraNotes);
379 }
380
381 /// Add a note to a prior diagnostic.
382 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
383 if (!HasActiveDiagnostic)
384 return OptionalDiagnostic();
385 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000386 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000387
388 /// Add a stack of notes to a prior diagnostic.
389 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
390 if (HasActiveDiagnostic) {
391 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
392 Diags.begin(), Diags.end());
393 }
394 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000395 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000396}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000397
Richard Smithf6f003a2011-12-16 19:06:07 +0000398CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
399 const FunctionDecl *Callee, const LValue *This,
400 const CCValue *Arguments)
401 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
402 This(This), Arguments(Arguments) {
403 Info.CurrentCall = this;
404 ++Info.CallStackDepth;
405}
406
407CallStackFrame::~CallStackFrame() {
408 assert(Info.CurrentCall == this && "calls retired out of order");
409 --Info.CallStackDepth;
410 Info.CurrentCall = Caller;
411}
412
413/// Produce a string describing the given constexpr call.
414static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
415 unsigned ArgIndex = 0;
416 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
417 !isa<CXXConstructorDecl>(Frame->Callee);
418
419 if (!IsMemberCall)
420 Out << *Frame->Callee << '(';
421
422 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
423 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
424 if (ArgIndex > IsMemberCall)
425 Out << ", ";
426
427 const ParmVarDecl *Param = *I;
428 const CCValue &Arg = Frame->Arguments[ArgIndex];
429 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
430 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
431 else {
432 // Deliberately slice off the frame to form an APValue we can print.
433 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
434 Arg.getLValueDesignator().Entries,
435 Arg.getLValueDesignator().OnePastTheEnd);
436 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
437 }
438
439 if (ArgIndex == 0 && IsMemberCall)
440 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000441 }
442
Richard Smithf6f003a2011-12-16 19:06:07 +0000443 Out << ')';
444}
445
446void EvalInfo::addCallStack(unsigned Limit) {
447 // Determine which calls to skip, if any.
448 unsigned ActiveCalls = CallStackDepth - 1;
449 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
450 if (Limit && Limit < ActiveCalls) {
451 SkipStart = Limit / 2 + Limit % 2;
452 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000453 }
454
Richard Smithf6f003a2011-12-16 19:06:07 +0000455 // Walk the call stack and add the diagnostics.
456 unsigned CallIdx = 0;
457 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
458 Frame = Frame->Caller, ++CallIdx) {
459 // Skip this call?
460 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
461 if (CallIdx == SkipStart) {
462 // Note that we're skipping calls.
463 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
464 << unsigned(ActiveCalls - Limit);
465 }
466 continue;
467 }
468
469 llvm::SmallVector<char, 128> Buffer;
470 llvm::raw_svector_ostream Out(Buffer);
471 describeCall(Frame, Out);
472 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
473 }
474}
475
476namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000477 struct ComplexValue {
478 private:
479 bool IsInt;
480
481 public:
482 APSInt IntReal, IntImag;
483 APFloat FloatReal, FloatImag;
484
485 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
486
487 void makeComplexFloat() { IsInt = false; }
488 bool isComplexFloat() const { return !IsInt; }
489 APFloat &getComplexFloatReal() { return FloatReal; }
490 APFloat &getComplexFloatImag() { return FloatImag; }
491
492 void makeComplexInt() { IsInt = true; }
493 bool isComplexInt() const { return IsInt; }
494 APSInt &getComplexIntReal() { return IntReal; }
495 APSInt &getComplexIntImag() { return IntImag; }
496
Richard Smith0b0a0b62011-10-29 20:57:55 +0000497 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000498 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000499 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000500 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000501 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000502 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000503 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000504 assert(v.isComplexFloat() || v.isComplexInt());
505 if (v.isComplexFloat()) {
506 makeComplexFloat();
507 FloatReal = v.getComplexFloatReal();
508 FloatImag = v.getComplexFloatImag();
509 } else {
510 makeComplexInt();
511 IntReal = v.getComplexIntReal();
512 IntImag = v.getComplexIntImag();
513 }
514 }
John McCall93d91dc2010-05-07 17:22:02 +0000515 };
John McCall45d55e42010-05-07 21:00:08 +0000516
517 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000518 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000519 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000520 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000521 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000522
Richard Smithce40ad62011-11-12 22:28:03 +0000523 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000524 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000525 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000526 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000527 SubobjectDesignator &getLValueDesignator() { return Designator; }
528 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000529
Richard Smith0b0a0b62011-10-29 20:57:55 +0000530 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000531 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000532 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000533 void setFrom(const CCValue &V) {
534 assert(V.isLValue());
535 Base = V.getLValueBase();
536 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000537 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000538 Designator = V.getLValueDesignator();
539 }
540
Richard Smithce40ad62011-11-12 22:28:03 +0000541 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
542 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000543 Offset = CharUnits::Zero();
544 Frame = F;
545 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000546 }
John McCall45d55e42010-05-07 21:00:08 +0000547 };
Richard Smith027bf112011-11-17 22:56:20 +0000548
549 struct MemberPtr {
550 MemberPtr() {}
551 explicit MemberPtr(const ValueDecl *Decl) :
552 DeclAndIsDerivedMember(Decl, false), Path() {}
553
554 /// The member or (direct or indirect) field referred to by this member
555 /// pointer, or 0 if this is a null member pointer.
556 const ValueDecl *getDecl() const {
557 return DeclAndIsDerivedMember.getPointer();
558 }
559 /// Is this actually a member of some type derived from the relevant class?
560 bool isDerivedMember() const {
561 return DeclAndIsDerivedMember.getInt();
562 }
563 /// Get the class which the declaration actually lives in.
564 const CXXRecordDecl *getContainingRecord() const {
565 return cast<CXXRecordDecl>(
566 DeclAndIsDerivedMember.getPointer()->getDeclContext());
567 }
568
569 void moveInto(CCValue &V) const {
570 V = CCValue(getDecl(), isDerivedMember(), Path);
571 }
572 void setFrom(const CCValue &V) {
573 assert(V.isMemberPointer());
574 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
575 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
576 Path.clear();
577 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
578 Path.insert(Path.end(), P.begin(), P.end());
579 }
580
581 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
582 /// whether the member is a member of some class derived from the class type
583 /// of the member pointer.
584 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
585 /// Path - The path of base/derived classes from the member declaration's
586 /// class (exclusive) to the class type of the member pointer (inclusive).
587 SmallVector<const CXXRecordDecl*, 4> Path;
588
589 /// Perform a cast towards the class of the Decl (either up or down the
590 /// hierarchy).
591 bool castBack(const CXXRecordDecl *Class) {
592 assert(!Path.empty());
593 const CXXRecordDecl *Expected;
594 if (Path.size() >= 2)
595 Expected = Path[Path.size() - 2];
596 else
597 Expected = getContainingRecord();
598 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
599 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
600 // if B does not contain the original member and is not a base or
601 // derived class of the class containing the original member, the result
602 // of the cast is undefined.
603 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
604 // (D::*). We consider that to be a language defect.
605 return false;
606 }
607 Path.pop_back();
608 return true;
609 }
610 /// Perform a base-to-derived member pointer cast.
611 bool castToDerived(const CXXRecordDecl *Derived) {
612 if (!getDecl())
613 return true;
614 if (!isDerivedMember()) {
615 Path.push_back(Derived);
616 return true;
617 }
618 if (!castBack(Derived))
619 return false;
620 if (Path.empty())
621 DeclAndIsDerivedMember.setInt(false);
622 return true;
623 }
624 /// Perform a derived-to-base member pointer cast.
625 bool castToBase(const CXXRecordDecl *Base) {
626 if (!getDecl())
627 return true;
628 if (Path.empty())
629 DeclAndIsDerivedMember.setInt(true);
630 if (isDerivedMember()) {
631 Path.push_back(Base);
632 return true;
633 }
634 return castBack(Base);
635 }
636 };
Richard Smith357362d2011-12-13 06:39:58 +0000637
638 /// Kinds of constant expression checking, for diagnostics.
639 enum CheckConstantExpressionKind {
640 CCEK_Constant, ///< A normal constant.
641 CCEK_ReturnValue, ///< A constexpr function return value.
642 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
643 };
John McCall93d91dc2010-05-07 17:22:02 +0000644}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000645
Richard Smith0b0a0b62011-10-29 20:57:55 +0000646static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000647static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +0000648 const LValue &This, const Expr *E,
649 CheckConstantExpressionKind CCEK
650 = CCEK_Constant);
John McCall45d55e42010-05-07 21:00:08 +0000651static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
652static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000653static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
654 EvalInfo &Info);
655static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000656static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000657static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000658 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000659static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000660static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000661
662//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000663// Misc utilities
664//===----------------------------------------------------------------------===//
665
Richard Smithd62306a2011-11-10 06:34:14 +0000666/// Should this call expression be treated as a string literal?
667static bool IsStringLiteralCall(const CallExpr *E) {
668 unsigned Builtin = E->isBuiltinCall();
669 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
670 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
671}
672
Richard Smithce40ad62011-11-12 22:28:03 +0000673static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000674 // C++11 [expr.const]p3 An address constant expression is a prvalue core
675 // constant expression of pointer type that evaluates to...
676
677 // ... a null pointer value, or a prvalue core constant expression of type
678 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000679 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000680
Richard Smithce40ad62011-11-12 22:28:03 +0000681 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
682 // ... the address of an object with static storage duration,
683 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
684 return VD->hasGlobalStorage();
685 // ... the address of a function,
686 return isa<FunctionDecl>(D);
687 }
688
689 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000690 switch (E->getStmtClass()) {
691 default:
692 return false;
Richard Smithd62306a2011-11-10 06:34:14 +0000693 case Expr::CompoundLiteralExprClass:
694 return cast<CompoundLiteralExpr>(E)->isFileScope();
695 // A string literal has static storage duration.
696 case Expr::StringLiteralClass:
697 case Expr::PredefinedExprClass:
698 case Expr::ObjCStringLiteralClass:
699 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000700 case Expr::CXXTypeidExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000701 return true;
702 case Expr::CallExprClass:
703 return IsStringLiteralCall(cast<CallExpr>(E));
704 // For GCC compatibility, &&label has static storage duration.
705 case Expr::AddrLabelExprClass:
706 return true;
707 // A Block literal expression may be used as the initialization value for
708 // Block variables at global or local static scope.
709 case Expr::BlockExprClass:
710 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
711 }
John McCall95007602010-05-10 23:27:23 +0000712}
713
Richard Smith80815602011-11-07 05:07:52 +0000714/// Check that this reference or pointer core constant expression is a valid
715/// value for a constant expression. Type T should be either LValue or CCValue.
716template<typename T>
Richard Smithf57d8cb2011-12-09 22:58:01 +0000717static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000718 const T &LVal, APValue &Value,
719 CheckConstantExpressionKind CCEK) {
720 APValue::LValueBase Base = LVal.getLValueBase();
721 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
722
723 if (!IsGlobalLValue(Base)) {
724 if (Info.getLangOpts().CPlusPlus0x) {
725 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
726 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
727 << E->isGLValue() << !Designator.Entries.empty()
728 << !!VD << CCEK << VD;
729 if (VD)
730 Info.Note(VD->getLocation(), diag::note_declared_at);
731 else
732 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
733 diag::note_constexpr_temporary_here);
734 } else {
Richard Smithf2b681b2011-12-21 05:04:46 +0000735 Info.Diag(E->getExprLoc());
Richard Smith357362d2011-12-13 06:39:58 +0000736 }
Richard Smith80815602011-11-07 05:07:52 +0000737 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000738 }
Richard Smith80815602011-11-07 05:07:52 +0000739
Richard Smith80815602011-11-07 05:07:52 +0000740 // A constant expression must refer to an object or be a null pointer.
Richard Smith027bf112011-11-17 22:56:20 +0000741 if (Designator.Invalid ||
Richard Smith80815602011-11-07 05:07:52 +0000742 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smith357362d2011-12-13 06:39:58 +0000743 // FIXME: This is not a core constant expression. We should have already
744 // produced a CCE diagnostic.
Richard Smith80815602011-11-07 05:07:52 +0000745 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
746 APValue::NoLValuePath());
747 return true;
748 }
749
Richard Smith357362d2011-12-13 06:39:58 +0000750 // Does this refer one past the end of some object?
751 // This is technically not an address constant expression nor a reference
752 // constant expression, but we allow it for address constant expressions.
753 if (E->isGLValue() && Base && Designator.OnePastTheEnd) {
754 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
755 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
756 << !Designator.Entries.empty() << !!VD << VD;
757 if (VD)
758 Info.Note(VD->getLocation(), diag::note_declared_at);
759 else
760 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
761 diag::note_constexpr_temporary_here);
762 return false;
763 }
764
Richard Smith80815602011-11-07 05:07:52 +0000765 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smith027bf112011-11-17 22:56:20 +0000766 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith80815602011-11-07 05:07:52 +0000767 return true;
768}
769
Richard Smith771c4a12011-12-25 20:00:17 +0000770/// Check that this core constant expression is of literal type, and if not,
771/// produce an appropriate diagnostic.
772static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
773 if (!E->isRValue() || E->getType()->isLiteralType())
774 return true;
775
776 // Prvalue constant expressions must be of literal types.
777 if (Info.getLangOpts().CPlusPlus0x)
778 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
779 << E->getType();
780 else
781 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
782 return false;
783}
784
Richard Smith0b0a0b62011-10-29 20:57:55 +0000785/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000786/// constant expression, and if it is, produce the corresponding constant value.
Richard Smith771c4a12011-12-25 20:00:17 +0000787/// If not, report an appropriate diagnostic. Does not check that the expression
788/// is of literal type.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000789static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000790 const CCValue &CCValue, APValue &Value,
791 CheckConstantExpressionKind CCEK
792 = CCEK_Constant) {
Richard Smith80815602011-11-07 05:07:52 +0000793 if (!CCValue.isLValue()) {
794 Value = CCValue;
795 return true;
796 }
Richard Smith357362d2011-12-13 06:39:58 +0000797 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000798}
799
Richard Smith83c68212011-10-31 05:11:32 +0000800const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000801 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000802}
803
804static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000805 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000806}
807
Richard Smithcecf1842011-11-01 21:06:14 +0000808static bool IsWeakLValue(const LValue &Value) {
809 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000810 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000811}
812
Richard Smith027bf112011-11-17 22:56:20 +0000813static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000814 // A null base expression indicates a null pointer. These are always
815 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000816 if (!Value.getLValueBase()) {
817 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000818 return true;
819 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000820
John McCall95007602010-05-10 23:27:23 +0000821 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000822 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000823 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000824
Richard Smith027bf112011-11-17 22:56:20 +0000825 // We have a non-null base. These are generally known to be true, but if it's
826 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000827 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000828 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000829 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000830}
831
Richard Smith0b0a0b62011-10-29 20:57:55 +0000832static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000833 switch (Val.getKind()) {
834 case APValue::Uninitialized:
835 return false;
836 case APValue::Int:
837 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000838 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000839 case APValue::Float:
840 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000841 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000842 case APValue::ComplexInt:
843 Result = Val.getComplexIntReal().getBoolValue() ||
844 Val.getComplexIntImag().getBoolValue();
845 return true;
846 case APValue::ComplexFloat:
847 Result = !Val.getComplexFloatReal().isZero() ||
848 !Val.getComplexFloatImag().isZero();
849 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000850 case APValue::LValue:
851 return EvalPointerValueAsBool(Val, Result);
852 case APValue::MemberPointer:
853 Result = Val.getMemberPointerDecl();
854 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000855 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000856 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000857 case APValue::Struct:
858 case APValue::Union:
Richard Smith11562c52011-10-28 17:51:58 +0000859 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000860 }
861
Richard Smith11562c52011-10-28 17:51:58 +0000862 llvm_unreachable("unknown APValue kind");
863}
864
865static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
866 EvalInfo &Info) {
867 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000868 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000869 if (!Evaluate(Val, Info, E))
870 return false;
871 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000872}
873
Richard Smith357362d2011-12-13 06:39:58 +0000874template<typename T>
875static bool HandleOverflow(EvalInfo &Info, const Expr *E,
876 const T &SrcValue, QualType DestType) {
877 llvm::SmallVector<char, 32> Buffer;
878 SrcValue.toString(Buffer);
879 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
880 << StringRef(Buffer.data(), Buffer.size()) << DestType;
881 return false;
882}
883
884static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
885 QualType SrcType, const APFloat &Value,
886 QualType DestType, APSInt &Result) {
887 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000888 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000889 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000890
Richard Smith357362d2011-12-13 06:39:58 +0000891 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000892 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000893 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
894 & APFloat::opInvalidOp)
895 return HandleOverflow(Info, E, Value, DestType);
896 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000897}
898
Richard Smith357362d2011-12-13 06:39:58 +0000899static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
900 QualType SrcType, QualType DestType,
901 APFloat &Result) {
902 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000903 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000904 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
905 APFloat::rmNearestTiesToEven, &ignored)
906 & APFloat::opOverflow)
907 return HandleOverflow(Info, E, Value, DestType);
908 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000909}
910
Mike Stump11289f42009-09-09 15:08:12 +0000911static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000912 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000913 unsigned DestWidth = Ctx.getIntWidth(DestType);
914 APSInt Result = Value;
915 // Figure out if this is a truncate, extend or noop cast.
916 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000917 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000918 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000919 return Result;
920}
921
Richard Smith357362d2011-12-13 06:39:58 +0000922static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
923 QualType SrcType, const APSInt &Value,
924 QualType DestType, APFloat &Result) {
925 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
926 if (Result.convertFromAPInt(Value, Value.isSigned(),
927 APFloat::rmNearestTiesToEven)
928 & APFloat::opOverflow)
929 return HandleOverflow(Info, E, Value, DestType);
930 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000931}
932
Eli Friedman803acb32011-12-22 03:51:45 +0000933static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
934 llvm::APInt &Res) {
935 CCValue SVal;
936 if (!Evaluate(SVal, Info, E))
937 return false;
938 if (SVal.isInt()) {
939 Res = SVal.getInt();
940 return true;
941 }
942 if (SVal.isFloat()) {
943 Res = SVal.getFloat().bitcastToAPInt();
944 return true;
945 }
946 if (SVal.isVector()) {
947 QualType VecTy = E->getType();
948 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
949 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
950 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
951 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
952 Res = llvm::APInt::getNullValue(VecSize);
953 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
954 APValue &Elt = SVal.getVectorElt(i);
955 llvm::APInt EltAsInt;
956 if (Elt.isInt()) {
957 EltAsInt = Elt.getInt();
958 } else if (Elt.isFloat()) {
959 EltAsInt = Elt.getFloat().bitcastToAPInt();
960 } else {
961 // Don't try to handle vectors of anything other than int or float
962 // (not sure if it's possible to hit this case).
963 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
964 return false;
965 }
966 unsigned BaseEltSize = EltAsInt.getBitWidth();
967 if (BigEndian)
968 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
969 else
970 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
971 }
972 return true;
973 }
974 // Give up if the input isn't an int, float, or vector. For example, we
975 // reject "(v4i16)(intptr_t)&a".
976 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
977 return false;
978}
979
Richard Smith027bf112011-11-17 22:56:20 +0000980static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
981 const CXXRecordDecl *&MostDerivedType,
982 unsigned &MostDerivedPathLength,
983 bool &MostDerivedIsArrayElement) {
984 const SubobjectDesignator &D = LVal.Designator;
985 if (D.Invalid || !LVal.Base)
Richard Smithd62306a2011-11-10 06:34:14 +0000986 return false;
987
Richard Smith027bf112011-11-17 22:56:20 +0000988 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smithd62306a2011-11-10 06:34:14 +0000989
990 // Find path prefix which leads to the most-derived subobject.
Richard Smithd62306a2011-11-10 06:34:14 +0000991 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smith027bf112011-11-17 22:56:20 +0000992 MostDerivedPathLength = 0;
993 MostDerivedIsArrayElement = false;
Richard Smithd62306a2011-11-10 06:34:14 +0000994
995 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
996 bool IsArray = T && T->isArrayType();
997 if (IsArray)
998 T = T->getBaseElementTypeUnsafe();
999 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
1000 T = FD->getType().getTypePtr();
1001 else
1002 T = 0;
1003
1004 if (T) {
1005 MostDerivedType = T->getAsCXXRecordDecl();
1006 MostDerivedPathLength = I + 1;
1007 MostDerivedIsArrayElement = IsArray;
1008 }
1009 }
1010
Richard Smithd62306a2011-11-10 06:34:14 +00001011 // (B*)&d + 1 has no most-derived object.
1012 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
1013 return false;
1014
Richard Smith027bf112011-11-17 22:56:20 +00001015 return MostDerivedType != 0;
1016}
1017
1018static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
1019 const RecordDecl *TruncatedType,
1020 unsigned TruncatedElements,
1021 bool IsArrayElement) {
1022 SubobjectDesignator &D = Result.Designator;
1023 const RecordDecl *RD = TruncatedType;
1024 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +00001025 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1026 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001027 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001028 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001029 else
Richard Smithd62306a2011-11-10 06:34:14 +00001030 Result.Offset -= Layout.getBaseClassOffset(Base);
1031 RD = Base;
1032 }
Richard Smith027bf112011-11-17 22:56:20 +00001033 D.Entries.resize(TruncatedElements);
1034 D.ArrayElement = IsArrayElement;
1035}
1036
1037/// If the given LValue refers to a base subobject of some object, find the most
1038/// derived object and the corresponding complete record type. This is necessary
1039/// in order to find the offset of a virtual base class.
1040static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
1041 const CXXRecordDecl *&MostDerivedType) {
1042 unsigned MostDerivedPathLength;
1043 bool MostDerivedIsArrayElement;
1044 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1045 MostDerivedPathLength, MostDerivedIsArrayElement))
1046 return false;
1047
1048 // Remove the trailing base class path entries and their offsets.
1049 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
1050 MostDerivedIsArrayElement);
Richard Smithd62306a2011-11-10 06:34:14 +00001051 return true;
1052}
1053
1054static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
1055 const CXXRecordDecl *Derived,
1056 const CXXRecordDecl *Base,
1057 const ASTRecordLayout *RL = 0) {
1058 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1059 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1060 Obj.Designator.addDecl(Base, /*Virtual*/ false);
1061}
1062
1063static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
1064 const CXXRecordDecl *DerivedDecl,
1065 const CXXBaseSpecifier *Base) {
1066 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1067
1068 if (!Base->isVirtual()) {
1069 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
1070 return true;
1071 }
1072
1073 // Extract most-derived object and corresponding type.
1074 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
1075 return false;
1076
1077 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1078 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1079 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
1080 return true;
1081}
1082
1083/// Update LVal to refer to the given field, which must be a member of the type
1084/// currently described by LVal.
1085static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
1086 const FieldDecl *FD,
1087 const ASTRecordLayout *RL = 0) {
1088 if (!RL)
1089 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1090
1091 unsigned I = FD->getFieldIndex();
1092 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1093 LVal.Designator.addDecl(FD);
1094}
1095
1096/// Get the size of the given type in char units.
1097static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1098 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1099 // extension.
1100 if (Type->isVoidType() || Type->isFunctionType()) {
1101 Size = CharUnits::One();
1102 return true;
1103 }
1104
1105 if (!Type->isConstantSizeType()) {
1106 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1107 return false;
1108 }
1109
1110 Size = Info.Ctx.getTypeSizeInChars(Type);
1111 return true;
1112}
1113
1114/// Update a pointer value to model pointer arithmetic.
1115/// \param Info - Information about the ongoing evaluation.
1116/// \param LVal - The pointer value to be updated.
1117/// \param EltTy - The pointee type represented by LVal.
1118/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1119static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
1120 QualType EltTy, int64_t Adjustment) {
1121 CharUnits SizeOfPointee;
1122 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1123 return false;
1124
1125 // Compute the new offset in the appropriate width.
1126 LVal.Offset += Adjustment * SizeOfPointee;
1127 LVal.Designator.adjustIndex(Adjustment);
1128 return true;
1129}
1130
Richard Smith27908702011-10-24 17:54:18 +00001131/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001132static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1133 const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +00001134 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001135 // If this is a parameter to an active constexpr function call, perform
1136 // argument substitution.
1137 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001138 if (!Frame || !Frame->Arguments) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001139 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001140 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001141 }
Richard Smithfec09922011-11-01 16:57:24 +00001142 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1143 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001144 }
Richard Smith27908702011-10-24 17:54:18 +00001145
Richard Smithd0b4dd62011-12-19 06:19:21 +00001146 // Dig out the initializer, and use the declaration which it's attached to.
1147 const Expr *Init = VD->getAnyInitializer(VD);
1148 if (!Init || Init->isValueDependent()) {
1149 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1150 return false;
1151 }
1152
Richard Smithd62306a2011-11-10 06:34:14 +00001153 // If we're currently evaluating the initializer of this declaration, use that
1154 // in-flight value.
1155 if (Info.EvaluatingDecl == VD) {
1156 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
1157 return !Result.isUninit();
1158 }
1159
Richard Smithcecf1842011-11-01 21:06:14 +00001160 // Never evaluate the initializer of a weak variable. We can't be sure that
1161 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001162 if (VD->isWeak()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001163 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001164 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001165 }
Richard Smithcecf1842011-11-01 21:06:14 +00001166
Richard Smithd0b4dd62011-12-19 06:19:21 +00001167 // Check that we can fold the initializer. In C++, we will have already done
1168 // this in the cases where it matters for conformance.
1169 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1170 if (!VD->evaluateValue(Notes)) {
1171 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1172 Notes.size() + 1) << VD;
1173 Info.Note(VD->getLocation(), diag::note_declared_at);
1174 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001175 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001176 } else if (!VD->checkInitIsICE()) {
1177 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1178 Notes.size() + 1) << VD;
1179 Info.Note(VD->getLocation(), diag::note_declared_at);
1180 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001181 }
Richard Smith27908702011-10-24 17:54:18 +00001182
Richard Smithd0b4dd62011-12-19 06:19:21 +00001183 Result = CCValue(*VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +00001184 return true;
Richard Smith27908702011-10-24 17:54:18 +00001185}
1186
Richard Smith11562c52011-10-28 17:51:58 +00001187static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001188 Qualifiers Quals = T.getQualifiers();
1189 return Quals.hasConst() && !Quals.hasVolatile();
1190}
1191
Richard Smithe97cbd72011-11-11 04:05:33 +00001192/// Get the base index of the given base class within an APValue representing
1193/// the given derived class.
1194static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1195 const CXXRecordDecl *Base) {
1196 Base = Base->getCanonicalDecl();
1197 unsigned Index = 0;
1198 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1199 E = Derived->bases_end(); I != E; ++I, ++Index) {
1200 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1201 return Index;
1202 }
1203
1204 llvm_unreachable("base class missing from derived class's bases list");
1205}
1206
Richard Smithf3e9e432011-11-07 09:22:26 +00001207/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001208static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1209 CCValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001210 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001211 if (Sub.Invalid) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001212 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001213 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001214 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001215 if (Sub.OnePastTheEnd) {
1216 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001217 (unsigned)diag::note_constexpr_read_past_end :
1218 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001219 return false;
1220 }
Richard Smith6804be52011-11-11 08:28:03 +00001221 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001222 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +00001223
1224 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1225 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001226 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001227 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001228 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001229 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001230 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001231 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001232 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001233 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001234 // Note, it should not be possible to form a pointer with a valid
1235 // designator which points more than one past the end of the array.
1236 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001237 (unsigned)diag::note_constexpr_read_past_end :
1238 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001239 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001240 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001241 if (O->getArrayInitializedElts() > Index)
1242 O = &O->getArrayInitializedElt(Index);
1243 else
1244 O = &O->getArrayFiller();
1245 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +00001246 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1247 // Next subobject is a class, struct or union field.
1248 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1249 if (RD->isUnion()) {
1250 const FieldDecl *UnionField = O->getUnionField();
1251 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001252 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001253 Info.Diag(E->getExprLoc(),
1254 diag::note_constexpr_read_inactive_union_member)
1255 << Field << !UnionField << UnionField;
Richard Smithd62306a2011-11-10 06:34:14 +00001256 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001257 }
Richard Smithd62306a2011-11-10 06:34:14 +00001258 O = &O->getUnionValue();
1259 } else
1260 O = &O->getStructField(Field->getFieldIndex());
1261 ObjType = Field->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001262
1263 if (ObjType.isVolatileQualified()) {
1264 if (Info.getLangOpts().CPlusPlus) {
1265 // FIXME: Include a description of the path to the volatile subobject.
1266 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1267 << 2 << Field;
1268 Info.Note(Field->getLocation(), diag::note_declared_at);
1269 } else {
1270 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1271 }
1272 return false;
1273 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001274 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001275 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001276 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1277 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1278 O = &O->getStructBase(getBaseIndex(Derived, Base));
1279 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001280 }
Richard Smithd62306a2011-11-10 06:34:14 +00001281
Richard Smithf57d8cb2011-12-09 22:58:01 +00001282 if (O->isUninit()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001283 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smithd62306a2011-11-10 06:34:14 +00001284 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001285 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001286 }
1287
Richard Smithf3e9e432011-11-07 09:22:26 +00001288 Obj = CCValue(*O, CCValue::GlobalValue());
1289 return true;
1290}
1291
Richard Smithd62306a2011-11-10 06:34:14 +00001292/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1293/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1294/// for looking up the glvalue referred to by an entity of reference type.
1295///
1296/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001297/// \param Conv - The expression for which we are performing the conversion.
1298/// Used for diagnostics.
Richard Smithd62306a2011-11-10 06:34:14 +00001299/// \param Type - The type we expect this conversion to produce.
1300/// \param LVal - The glvalue on which we are attempting to perform this action.
1301/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001302static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1303 QualType Type,
Richard Smithf3e9e432011-11-07 09:22:26 +00001304 const LValue &LVal, CCValue &RVal) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001305 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1306 if (!Info.getLangOpts().CPlusPlus)
1307 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1308
Richard Smithce40ad62011-11-12 22:28:03 +00001309 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001310 CallStackFrame *Frame = LVal.Frame;
Richard Smithf2b681b2011-12-21 05:04:46 +00001311 SourceLocation Loc = Conv->getExprLoc();
Richard Smith11562c52011-10-28 17:51:58 +00001312
Richard Smithf57d8cb2011-12-09 22:58:01 +00001313 if (!LVal.Base) {
1314 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithf2b681b2011-12-21 05:04:46 +00001315 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1316 return false;
1317 }
1318
1319 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1320 // is not a constant expression (even if the object is non-volatile). We also
1321 // apply this rule to C++98, in order to conform to the expected 'volatile'
1322 // semantics.
1323 if (Type.isVolatileQualified()) {
1324 if (Info.getLangOpts().CPlusPlus)
1325 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1326 else
1327 Info.Diag(Loc);
Richard Smith11562c52011-10-28 17:51:58 +00001328 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001329 }
Richard Smith11562c52011-10-28 17:51:58 +00001330
Richard Smithce40ad62011-11-12 22:28:03 +00001331 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001332 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1333 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001334 // expressions are constant expressions too. Inside constexpr functions,
1335 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001336 // In C, such things can also be folded, although they are not ICEs.
Richard Smith11562c52011-10-28 17:51:58 +00001337 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001338 if (!VD || VD->isInvalidDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001339 Info.Diag(Loc);
Richard Smith96e0c102011-11-04 02:25:55 +00001340 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001341 }
1342
Richard Smithf2b681b2011-12-21 05:04:46 +00001343 // DR1313: If the object is volatile-qualified but the glvalue was not,
1344 // behavior is undefined so the result is not a constant expression.
Richard Smithce40ad62011-11-12 22:28:03 +00001345 QualType VT = VD->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001346 if (VT.isVolatileQualified()) {
1347 if (Info.getLangOpts().CPlusPlus) {
1348 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1349 Info.Note(VD->getLocation(), diag::note_declared_at);
1350 } else {
1351 Info.Diag(Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001352 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001353 return false;
1354 }
1355
1356 if (!isa<ParmVarDecl>(VD)) {
1357 if (VD->isConstexpr()) {
1358 // OK, we can read this variable.
1359 } else if (VT->isIntegralOrEnumerationType()) {
1360 if (!VT.isConstQualified()) {
1361 if (Info.getLangOpts().CPlusPlus) {
1362 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1363 Info.Note(VD->getLocation(), diag::note_declared_at);
1364 } else {
1365 Info.Diag(Loc);
1366 }
1367 return false;
1368 }
1369 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1370 // We support folding of const floating-point types, in order to make
1371 // static const data members of such types (supported as an extension)
1372 // more useful.
1373 if (Info.getLangOpts().CPlusPlus0x) {
1374 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1375 Info.Note(VD->getLocation(), diag::note_declared_at);
1376 } else {
1377 Info.CCEDiag(Loc);
1378 }
1379 } else {
1380 // FIXME: Allow folding of values of any literal type in all languages.
1381 if (Info.getLangOpts().CPlusPlus0x) {
1382 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1383 Info.Note(VD->getLocation(), diag::note_declared_at);
1384 } else {
1385 Info.Diag(Loc);
1386 }
Richard Smith96e0c102011-11-04 02:25:55 +00001387 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001388 }
Richard Smith96e0c102011-11-04 02:25:55 +00001389 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001390
Richard Smithf57d8cb2011-12-09 22:58:01 +00001391 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001392 return false;
1393
Richard Smith0b0a0b62011-10-29 20:57:55 +00001394 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001395 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001396
1397 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1398 // conversion. This happens when the declaration and the lvalue should be
1399 // considered synonymous, for instance when initializing an array of char
1400 // from a string literal. Continue as if the initializer lvalue was the
1401 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001402 assert(RVal.getLValueOffset().isZero() &&
1403 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001404 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001405 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001406 }
1407
Richard Smithf2b681b2011-12-21 05:04:46 +00001408 // Volatile temporary objects cannot be read in constant expressions.
1409 if (Base->getType().isVolatileQualified()) {
1410 if (Info.getLangOpts().CPlusPlus) {
1411 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1412 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1413 } else {
1414 Info.Diag(Loc);
1415 }
1416 return false;
1417 }
1418
Richard Smith96e0c102011-11-04 02:25:55 +00001419 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1420 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1421 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001422 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001423 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001424 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001425 }
Richard Smith96e0c102011-11-04 02:25:55 +00001426
1427 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001428 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf2b681b2011-12-21 05:04:46 +00001429 const ConstantArrayType *CAT =
1430 Info.Ctx.getAsConstantArrayType(S->getType());
1431 if (Index >= CAT->getSize().getZExtValue()) {
1432 // Note, it should not be possible to form a pointer which points more
1433 // than one past the end of the array without producing a prior const expr
1434 // diagnostic.
1435 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith96e0c102011-11-04 02:25:55 +00001436 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001437 }
Richard Smith96e0c102011-11-04 02:25:55 +00001438 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1439 Type->isUnsignedIntegerType());
1440 if (Index < S->getLength())
1441 Value = S->getCodeUnit(Index);
1442 RVal = CCValue(Value);
1443 return true;
1444 }
1445
Richard Smithf3e9e432011-11-07 09:22:26 +00001446 if (Frame) {
1447 // If this is a temporary expression with a nontrivial initializer, grab the
1448 // value from the relevant stack frame.
1449 RVal = Frame->Temporaries[Base];
1450 } else if (const CompoundLiteralExpr *CLE
1451 = dyn_cast<CompoundLiteralExpr>(Base)) {
1452 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1453 // initializer until now for such expressions. Such an expression can't be
1454 // an ICE in C, so this only matters for fold.
1455 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1456 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1457 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001458 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00001459 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001460 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001461 }
Richard Smith96e0c102011-11-04 02:25:55 +00001462
Richard Smithf57d8cb2011-12-09 22:58:01 +00001463 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1464 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001465}
1466
Richard Smithe97cbd72011-11-11 04:05:33 +00001467/// Build an lvalue for the object argument of a member function call.
1468static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1469 LValue &This) {
1470 if (Object->getType()->isPointerType())
1471 return EvaluatePointer(Object, This, Info);
1472
1473 if (Object->isGLValue())
1474 return EvaluateLValue(Object, This, Info);
1475
Richard Smith027bf112011-11-17 22:56:20 +00001476 if (Object->getType()->isLiteralType())
1477 return EvaluateTemporary(Object, This, Info);
1478
1479 return false;
1480}
1481
1482/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1483/// lvalue referring to the result.
1484///
1485/// \param Info - Information about the ongoing evaluation.
1486/// \param BO - The member pointer access operation.
1487/// \param LV - Filled in with a reference to the resulting object.
1488/// \param IncludeMember - Specifies whether the member itself is included in
1489/// the resulting LValue subobject designator. This is not possible when
1490/// creating a bound member function.
1491/// \return The field or method declaration to which the member pointer refers,
1492/// or 0 if evaluation fails.
1493static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1494 const BinaryOperator *BO,
1495 LValue &LV,
1496 bool IncludeMember = true) {
1497 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1498
1499 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1500 return 0;
1501
1502 MemberPtr MemPtr;
1503 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1504 return 0;
1505
1506 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1507 // member value, the behavior is undefined.
1508 if (!MemPtr.getDecl())
1509 return 0;
1510
1511 if (MemPtr.isDerivedMember()) {
1512 // This is a member of some derived class. Truncate LV appropriately.
1513 const CXXRecordDecl *MostDerivedType;
1514 unsigned MostDerivedPathLength;
1515 bool MostDerivedIsArrayElement;
1516 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1517 MostDerivedIsArrayElement))
1518 return 0;
1519
1520 // The end of the derived-to-base path for the base object must match the
1521 // derived-to-base path for the member pointer.
1522 if (MostDerivedPathLength + MemPtr.Path.size() >
1523 LV.Designator.Entries.size())
1524 return 0;
1525 unsigned PathLengthToMember =
1526 LV.Designator.Entries.size() - MemPtr.Path.size();
1527 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1528 const CXXRecordDecl *LVDecl = getAsBaseClass(
1529 LV.Designator.Entries[PathLengthToMember + I]);
1530 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1531 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1532 return 0;
1533 }
1534
1535 // Truncate the lvalue to the appropriate derived class.
1536 bool ResultIsArray = false;
1537 if (PathLengthToMember == MostDerivedPathLength)
1538 ResultIsArray = MostDerivedIsArrayElement;
1539 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1540 PathLengthToMember, ResultIsArray);
1541 } else if (!MemPtr.Path.empty()) {
1542 // Extend the LValue path with the member pointer's path.
1543 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1544 MemPtr.Path.size() + IncludeMember);
1545
1546 // Walk down to the appropriate base class.
1547 QualType LVType = BO->getLHS()->getType();
1548 if (const PointerType *PT = LVType->getAs<PointerType>())
1549 LVType = PT->getPointeeType();
1550 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1551 assert(RD && "member pointer access on non-class-type expression");
1552 // The first class in the path is that of the lvalue.
1553 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1554 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1555 HandleLValueDirectBase(Info, LV, RD, Base);
1556 RD = Base;
1557 }
1558 // Finally cast to the class containing the member.
1559 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1560 }
1561
1562 // Add the member. Note that we cannot build bound member functions here.
1563 if (IncludeMember) {
1564 // FIXME: Deal with IndirectFieldDecls.
1565 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1566 if (!FD) return 0;
1567 HandleLValueMember(Info, LV, FD);
1568 }
1569
1570 return MemPtr.getDecl();
1571}
1572
1573/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1574/// the provided lvalue, which currently refers to the base object.
1575static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1576 LValue &Result) {
1577 const CXXRecordDecl *MostDerivedType;
1578 unsigned MostDerivedPathLength;
1579 bool MostDerivedIsArrayElement;
1580
1581 // Check this cast doesn't take us outside the object.
1582 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1583 MostDerivedPathLength,
1584 MostDerivedIsArrayElement))
1585 return false;
1586 SubobjectDesignator &D = Result.Designator;
1587 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1588 return false;
1589
1590 // Check the type of the final cast. We don't need to check the path,
1591 // since a cast can only be formed if the path is unique.
1592 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1593 bool ResultIsArray = false;
1594 QualType TargetQT = E->getType();
1595 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1596 TargetQT = PT->getPointeeType();
1597 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1598 const CXXRecordDecl *FinalType;
1599 if (NewEntriesSize == MostDerivedPathLength) {
1600 ResultIsArray = MostDerivedIsArrayElement;
1601 FinalType = MostDerivedType;
1602 } else
1603 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1604 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1605 return false;
1606
1607 // Truncate the lvalue to the appropriate derived class.
1608 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1609 ResultIsArray);
1610 return true;
Richard Smithe97cbd72011-11-11 04:05:33 +00001611}
1612
Mike Stump876387b2009-10-27 22:09:17 +00001613namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001614enum EvalStmtResult {
1615 /// Evaluation failed.
1616 ESR_Failed,
1617 /// Hit a 'return' statement.
1618 ESR_Returned,
1619 /// Evaluation succeeded.
1620 ESR_Succeeded
1621};
1622}
1623
1624// Evaluate a statement.
Richard Smith357362d2011-12-13 06:39:58 +00001625static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001626 const Stmt *S) {
1627 switch (S->getStmtClass()) {
1628 default:
1629 return ESR_Failed;
1630
1631 case Stmt::NullStmtClass:
1632 case Stmt::DeclStmtClass:
1633 return ESR_Succeeded;
1634
Richard Smith357362d2011-12-13 06:39:58 +00001635 case Stmt::ReturnStmtClass: {
1636 CCValue CCResult;
1637 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1638 if (!Evaluate(CCResult, Info, RetExpr) ||
1639 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1640 CCEK_ReturnValue))
1641 return ESR_Failed;
1642 return ESR_Returned;
1643 }
Richard Smith254a73d2011-10-28 22:34:42 +00001644
1645 case Stmt::CompoundStmtClass: {
1646 const CompoundStmt *CS = cast<CompoundStmt>(S);
1647 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1648 BE = CS->body_end(); BI != BE; ++BI) {
1649 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1650 if (ESR != ESR_Succeeded)
1651 return ESR;
1652 }
1653 return ESR_Succeeded;
1654 }
1655 }
1656}
1657
Richard Smithcc36f692011-12-22 02:22:31 +00001658/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1659/// default constructor. If so, we'll fold it whether or not it's marked as
1660/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1661/// so we need special handling.
1662static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith771c4a12011-12-25 20:00:17 +00001663 const CXXConstructorDecl *CD,
1664 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00001665 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1666 return false;
1667
1668 if (!CD->isConstexpr()) {
1669 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith771c4a12011-12-25 20:00:17 +00001670 // Value-initialization does not call a trivial default constructor, so
1671 // such a call is a core constant expression whether or not the
1672 // constructor is constexpr.
1673 if (!IsValueInitialization) {
1674 // FIXME: If DiagDecl is an implicitly-declared special member function,
1675 // we should be much more explicit about why it's not constexpr.
1676 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1677 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1678 Info.Note(CD->getLocation(), diag::note_declared_at);
1679 }
Richard Smithcc36f692011-12-22 02:22:31 +00001680 } else {
1681 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1682 }
1683 }
1684 return true;
1685}
1686
Richard Smith357362d2011-12-13 06:39:58 +00001687/// CheckConstexprFunction - Check that a function can be called in a constant
1688/// expression.
1689static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1690 const FunctionDecl *Declaration,
1691 const FunctionDecl *Definition) {
1692 // Can we evaluate this function call?
1693 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1694 return true;
1695
1696 if (Info.getLangOpts().CPlusPlus0x) {
1697 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001698 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1699 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00001700 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1701 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1702 << DiagDecl;
1703 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1704 } else {
1705 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1706 }
1707 return false;
1708}
1709
Richard Smithd62306a2011-11-10 06:34:14 +00001710namespace {
Richard Smith60494462011-11-11 05:48:57 +00001711typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001712}
1713
1714/// EvaluateArgs - Evaluate the arguments to a function call.
1715static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1716 EvalInfo &Info) {
1717 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1718 I != E; ++I)
1719 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1720 return false;
1721 return true;
1722}
1723
Richard Smith254a73d2011-10-28 22:34:42 +00001724/// Evaluate a function call.
Richard Smithf6f003a2011-12-16 19:06:07 +00001725static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1726 const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00001727 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith357362d2011-12-13 06:39:58 +00001728 EvalInfo &Info, APValue &Result) {
1729 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith254a73d2011-10-28 22:34:42 +00001730 return false;
1731
Richard Smithd62306a2011-11-10 06:34:14 +00001732 ArgVector ArgValues(Args.size());
1733 if (!EvaluateArgs(Args, ArgValues, Info))
1734 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001735
Richard Smithf6f003a2011-12-16 19:06:07 +00001736 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1737 ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001738 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1739}
1740
Richard Smithd62306a2011-11-10 06:34:14 +00001741/// Evaluate a constructor call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001742static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00001743 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001744 const CXXConstructorDecl *Definition,
Richard Smith771c4a12011-12-25 20:00:17 +00001745 EvalInfo &Info, APValue &Result) {
Richard Smith357362d2011-12-13 06:39:58 +00001746 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd62306a2011-11-10 06:34:14 +00001747 return false;
1748
1749 ArgVector ArgValues(Args.size());
1750 if (!EvaluateArgs(Args, ArgValues, Info))
1751 return false;
1752
Richard Smithf6f003a2011-12-16 19:06:07 +00001753 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1754 &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00001755
1756 // If it's a delegating constructor, just delegate.
1757 if (Definition->isDelegatingConstructor()) {
1758 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1759 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1760 }
1761
1762 // Reserve space for the struct members.
1763 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith771c4a12011-12-25 20:00:17 +00001764 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00001765 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1766 std::distance(RD->field_begin(), RD->field_end()));
1767
1768 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1769
1770 unsigned BasesSeen = 0;
1771#ifndef NDEBUG
1772 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1773#endif
1774 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1775 E = Definition->init_end(); I != E; ++I) {
1776 if ((*I)->isBaseInitializer()) {
1777 QualType BaseType((*I)->getBaseClass(), 0);
1778#ifndef NDEBUG
1779 // Non-virtual base classes are initialized in the order in the class
1780 // definition. We cannot have a virtual base class for a literal type.
1781 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1782 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1783 "base class initializers not in expected order");
1784 ++BaseIt;
1785#endif
1786 LValue Subobject = This;
1787 HandleLValueDirectBase(Info, Subobject, RD,
1788 BaseType->getAsCXXRecordDecl(), &Layout);
1789 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1790 Subobject, (*I)->getInit()))
1791 return false;
1792 } else if (FieldDecl *FD = (*I)->getMember()) {
1793 LValue Subobject = This;
1794 HandleLValueMember(Info, Subobject, FD, &Layout);
1795 if (RD->isUnion()) {
1796 Result = APValue(FD);
Richard Smith357362d2011-12-13 06:39:58 +00001797 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1798 (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001799 return false;
1800 } else if (!EvaluateConstantExpression(
1801 Result.getStructField(FD->getFieldIndex()),
Richard Smith357362d2011-12-13 06:39:58 +00001802 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001803 return false;
1804 } else {
1805 // FIXME: handle indirect field initializers
Richard Smith92b1ce02011-12-12 09:28:41 +00001806 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf57d8cb2011-12-09 22:58:01 +00001807 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001808 return false;
1809 }
1810 }
1811
1812 return true;
1813}
1814
Richard Smith254a73d2011-10-28 22:34:42 +00001815namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001816class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001817 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001818 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001819public:
1820
Richard Smith725810a2011-10-16 21:26:27 +00001821 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001822
1823 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001824 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001825 return true;
1826 }
1827
Peter Collingbournee9200682011-05-13 03:29:01 +00001828 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1829 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001830 return Visit(E->getResultExpr());
1831 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001832 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001833 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001834 return true;
1835 return false;
1836 }
John McCall31168b02011-06-15 23:02:42 +00001837 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001838 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001839 return true;
1840 return false;
1841 }
1842 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001843 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001844 return true;
1845 return false;
1846 }
1847
Mike Stump876387b2009-10-27 22:09:17 +00001848 // We don't want to evaluate BlockExprs multiple times, as they generate
1849 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001850 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1851 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1852 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001853 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001854 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1855 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1856 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1857 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1858 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1859 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001860 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001861 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001862 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001863 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001864 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001865 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1866 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1867 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1868 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001869 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001870 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1871 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1872 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1873 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1874 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001875 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001876 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001877 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001878 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001879 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001880
1881 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001882 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001883 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1884 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001885 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001886 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001887 return false;
1888 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001889
Peter Collingbournee9200682011-05-13 03:29:01 +00001890 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001891};
1892
John McCallc07a0c72011-02-17 10:25:35 +00001893class OpaqueValueEvaluation {
1894 EvalInfo &info;
1895 OpaqueValueExpr *opaqueValue;
1896
1897public:
1898 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1899 Expr *value)
1900 : info(info), opaqueValue(opaqueValue) {
1901
1902 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00001903 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00001904 this->opaqueValue = 0;
1905 return;
1906 }
John McCallc07a0c72011-02-17 10:25:35 +00001907 }
1908
1909 bool hasError() const { return opaqueValue == 0; }
1910
1911 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00001912 // FIXME: This will not work for recursive constexpr functions using opaque
1913 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00001914 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1915 }
1916};
1917
Mike Stump876387b2009-10-27 22:09:17 +00001918} // end anonymous namespace
1919
Eli Friedman9a156e52008-11-12 09:44:48 +00001920//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00001921// Generic Evaluation
1922//===----------------------------------------------------------------------===//
1923namespace {
1924
Richard Smithf57d8cb2011-12-09 22:58:01 +00001925// FIXME: RetTy is always bool. Remove it.
1926template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00001927class ExprEvaluatorBase
1928 : public ConstStmtVisitor<Derived, RetTy> {
1929private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001930 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001931 return static_cast<Derived*>(this)->Success(V, E);
1932 }
Richard Smith771c4a12011-12-25 20:00:17 +00001933 RetTy DerivedZeroInitialization(const Expr *E) {
1934 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00001935 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001936
1937protected:
1938 EvalInfo &Info;
1939 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1940 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1941
Richard Smith92b1ce02011-12-12 09:28:41 +00001942 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith187ef012011-12-12 09:41:58 +00001943 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001944 }
1945
1946 /// Report an evaluation error. This should only be called when an error is
1947 /// first discovered. When propagating an error, just return false.
1948 bool Error(const Expr *E, diag::kind D) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001949 Info.Diag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001950 return false;
1951 }
1952 bool Error(const Expr *E) {
1953 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1954 }
1955
Richard Smith771c4a12011-12-25 20:00:17 +00001956 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00001957
Peter Collingbournee9200682011-05-13 03:29:01 +00001958public:
1959 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1960
1961 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00001962 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00001963 }
1964 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001965 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001966 }
1967
1968 RetTy VisitParenExpr(const ParenExpr *E)
1969 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1970 RetTy VisitUnaryExtension(const UnaryOperator *E)
1971 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1972 RetTy VisitUnaryPlus(const UnaryOperator *E)
1973 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1974 RetTy VisitChooseExpr(const ChooseExpr *E)
1975 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1976 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1977 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00001978 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1979 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00001980 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1981 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00001982 // We cannot create any objects for which cleanups are required, so there is
1983 // nothing to do here; all cleanups must come from unevaluated subexpressions.
1984 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
1985 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001986
Richard Smith6d6ecc32011-12-12 12:46:16 +00001987 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1988 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1989 return static_cast<Derived*>(this)->VisitCastExpr(E);
1990 }
1991 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1992 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1993 return static_cast<Derived*>(this)->VisitCastExpr(E);
1994 }
1995
Richard Smith027bf112011-11-17 22:56:20 +00001996 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1997 switch (E->getOpcode()) {
1998 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00001999 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002000
2001 case BO_Comma:
2002 VisitIgnoredValue(E->getLHS());
2003 return StmtVisitorTy::Visit(E->getRHS());
2004
2005 case BO_PtrMemD:
2006 case BO_PtrMemI: {
2007 LValue Obj;
2008 if (!HandleMemberPointerAccess(Info, E, Obj))
2009 return false;
2010 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002011 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00002012 return false;
2013 return DerivedSuccess(Result, E);
2014 }
2015 }
2016 }
2017
Peter Collingbournee9200682011-05-13 03:29:01 +00002018 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2019 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2020 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002021 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002022
2023 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00002024 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002025 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002026
2027 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2028 }
2029
2030 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2031 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002032 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002033 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002034
Richard Smith11562c52011-10-28 17:51:58 +00002035 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00002036 return StmtVisitorTy::Visit(EvalExpr);
2037 }
2038
2039 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002040 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002041 if (!Value) {
2042 const Expr *Source = E->getSourceExpr();
2043 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002044 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002045 if (Source == E) { // sanity checking.
2046 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00002047 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002048 }
2049 return StmtVisitorTy::Visit(Source);
2050 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00002051 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002052 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002053
Richard Smith254a73d2011-10-28 22:34:42 +00002054 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002055 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00002056 QualType CalleeType = Callee->getType();
2057
Richard Smith254a73d2011-10-28 22:34:42 +00002058 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00002059 LValue *This = 0, ThisVal;
2060 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00002061
Richard Smithe97cbd72011-11-11 04:05:33 +00002062 // Extract function decl and 'this' pointer from the callee.
2063 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002064 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00002065 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2066 // Explicit bound member calls, such as x.f() or p->g();
2067 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002068 return false;
2069 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002070 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002071 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2072 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00002073 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2074 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00002075 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002076 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002077 return Error(Callee);
2078
2079 FD = dyn_cast<FunctionDecl>(Member);
2080 if (!FD)
2081 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002082 } else if (CalleeType->isFunctionPointerType()) {
2083 CCValue Call;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002084 if (!Evaluate(Call, Info, Callee))
2085 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00002086
Richard Smithf57d8cb2011-12-09 22:58:01 +00002087 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
2088 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00002089 FD = dyn_cast_or_null<FunctionDecl>(
2090 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00002091 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002092 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002093
2094 // Overloaded operator calls to member functions are represented as normal
2095 // calls with '*this' as the first argument.
2096 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2097 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002098 // FIXME: When selecting an implicit conversion for an overloaded
2099 // operator delete, we sometimes try to evaluate calls to conversion
2100 // operators without a 'this' parameter!
2101 if (Args.empty())
2102 return Error(E);
2103
Richard Smithe97cbd72011-11-11 04:05:33 +00002104 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2105 return false;
2106 This = &ThisVal;
2107 Args = Args.slice(1);
2108 }
2109
2110 // Don't call function pointers which have been cast to some other type.
2111 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002112 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002113 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002114 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002115
Richard Smith357362d2011-12-13 06:39:58 +00002116 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002117 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00002118 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002119
Richard Smith357362d2011-12-13 06:39:58 +00002120 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smithf6f003a2011-12-16 19:06:07 +00002121 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002122 return false;
2123
2124 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00002125 }
2126
Richard Smith11562c52011-10-28 17:51:58 +00002127 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2128 return StmtVisitorTy::Visit(E->getInitializer());
2129 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002130 RetTy VisitInitListExpr(const InitListExpr *E) {
2131 if (Info.getLangOpts().CPlusPlus0x) {
2132 if (E->getNumInits() == 0)
Richard Smith771c4a12011-12-25 20:00:17 +00002133 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002134 if (E->getNumInits() == 1)
2135 return StmtVisitorTy::Visit(E->getInit(0));
2136 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00002137 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002138 }
2139 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith771c4a12011-12-25 20:00:17 +00002140 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002141 }
2142 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith771c4a12011-12-25 20:00:17 +00002143 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002144 }
Richard Smith027bf112011-11-17 22:56:20 +00002145 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith771c4a12011-12-25 20:00:17 +00002146 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002147 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002148
Richard Smithd62306a2011-11-10 06:34:14 +00002149 /// A member expression where the object is a prvalue is itself a prvalue.
2150 RetTy VisitMemberExpr(const MemberExpr *E) {
2151 assert(!E->isArrow() && "missing call to bound member function?");
2152
2153 CCValue Val;
2154 if (!Evaluate(Val, Info, E->getBase()))
2155 return false;
2156
2157 QualType BaseTy = E->getBase()->getType();
2158
2159 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002160 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002161 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2162 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2163 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2164
2165 SubobjectDesignator Designator;
2166 Designator.addDecl(FD);
2167
Richard Smithf57d8cb2011-12-09 22:58:01 +00002168 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002169 DerivedSuccess(Val, E);
2170 }
2171
Richard Smith11562c52011-10-28 17:51:58 +00002172 RetTy VisitCastExpr(const CastExpr *E) {
2173 switch (E->getCastKind()) {
2174 default:
2175 break;
2176
2177 case CK_NoOp:
2178 return StmtVisitorTy::Visit(E->getSubExpr());
2179
2180 case CK_LValueToRValue: {
2181 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002182 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2183 return false;
2184 CCValue RVal;
2185 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2186 return false;
2187 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002188 }
2189 }
2190
Richard Smithf57d8cb2011-12-09 22:58:01 +00002191 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002192 }
2193
Richard Smith4a678122011-10-24 18:44:57 +00002194 /// Visit a value which is evaluated, but whose value is ignored.
2195 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002196 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002197 if (!Evaluate(Scratch, Info, E))
2198 Info.EvalStatus.HasSideEffects = true;
2199 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002200};
2201
2202}
2203
2204//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002205// Common base class for lvalue and temporary evaluation.
2206//===----------------------------------------------------------------------===//
2207namespace {
2208template<class Derived>
2209class LValueExprEvaluatorBase
2210 : public ExprEvaluatorBase<Derived, bool> {
2211protected:
2212 LValue &Result;
2213 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2214 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2215
2216 bool Success(APValue::LValueBase B) {
2217 Result.set(B);
2218 return true;
2219 }
2220
2221public:
2222 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2223 ExprEvaluatorBaseTy(Info), Result(Result) {}
2224
2225 bool Success(const CCValue &V, const Expr *E) {
2226 Result.setFrom(V);
2227 return true;
2228 }
Richard Smith027bf112011-11-17 22:56:20 +00002229
2230 bool CheckValidLValue() {
2231 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
2232 // there are no null references, nor once-past-the-end references.
2233 // FIXME: Check for one-past-the-end array indices
2234 return Result.Base && !Result.Designator.Invalid &&
2235 !Result.Designator.OnePastTheEnd;
2236 }
2237
2238 bool VisitMemberExpr(const MemberExpr *E) {
2239 // Handle non-static data members.
2240 QualType BaseTy;
2241 if (E->isArrow()) {
2242 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2243 return false;
2244 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002245 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002246 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002247 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2248 return false;
2249 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002250 } else {
2251 if (!this->Visit(E->getBase()))
2252 return false;
2253 BaseTy = E->getBase()->getType();
2254 }
2255 // FIXME: In C++11, require the result to be a valid lvalue.
2256
2257 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2258 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00002259 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002260 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2261 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2262 (void)BaseTy;
2263
2264 HandleLValueMember(this->Info, Result, FD);
2265
2266 if (FD->getType()->isReferenceType()) {
2267 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002268 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002269 RefValue))
2270 return false;
2271 return Success(RefValue, E);
2272 }
2273 return true;
2274 }
2275
2276 bool VisitBinaryOperator(const BinaryOperator *E) {
2277 switch (E->getOpcode()) {
2278 default:
2279 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2280
2281 case BO_PtrMemD:
2282 case BO_PtrMemI:
2283 return HandleMemberPointerAccess(this->Info, E, Result);
2284 }
2285 }
2286
2287 bool VisitCastExpr(const CastExpr *E) {
2288 switch (E->getCastKind()) {
2289 default:
2290 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2291
2292 case CK_DerivedToBase:
2293 case CK_UncheckedDerivedToBase: {
2294 if (!this->Visit(E->getSubExpr()))
2295 return false;
2296 if (!CheckValidLValue())
2297 return false;
2298
2299 // Now figure out the necessary offset to add to the base LV to get from
2300 // the derived class to the base class.
2301 QualType Type = E->getSubExpr()->getType();
2302
2303 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2304 PathE = E->path_end(); PathI != PathE; ++PathI) {
2305 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2306 *PathI))
2307 return false;
2308 Type = (*PathI)->getType();
2309 }
2310
2311 return true;
2312 }
2313 }
2314 }
2315};
2316}
2317
2318//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002319// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002320//
2321// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2322// function designators (in C), decl references to void objects (in C), and
2323// temporaries (if building with -Wno-address-of-temporary).
2324//
2325// LValue evaluation produces values comprising a base expression of one of the
2326// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002327// - Declarations
2328// * VarDecl
2329// * FunctionDecl
2330// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002331// * CompoundLiteralExpr in C
2332// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00002333// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00002334// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002335// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002336// * ObjCEncodeExpr
2337// * AddrLabelExpr
2338// * BlockExpr
2339// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002340// - Locals and temporaries
2341// * Any Expr, with a Frame indicating the function in which the temporary was
2342// evaluated.
2343// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002344//===----------------------------------------------------------------------===//
2345namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002346class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002347 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002348public:
Richard Smith027bf112011-11-17 22:56:20 +00002349 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2350 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002351
Richard Smith11562c52011-10-28 17:51:58 +00002352 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2353
Peter Collingbournee9200682011-05-13 03:29:01 +00002354 bool VisitDeclRefExpr(const DeclRefExpr *E);
2355 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002356 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002357 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2358 bool VisitMemberExpr(const MemberExpr *E);
2359 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2360 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00002361 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002362 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2363 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002364
Peter Collingbournee9200682011-05-13 03:29:01 +00002365 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002366 switch (E->getCastKind()) {
2367 default:
Richard Smith027bf112011-11-17 22:56:20 +00002368 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002369
Eli Friedmance3e02a2011-10-11 00:13:24 +00002370 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002371 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002372 if (!Visit(E->getSubExpr()))
2373 return false;
2374 Result.Designator.setInvalid();
2375 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002376
Richard Smith027bf112011-11-17 22:56:20 +00002377 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002378 if (!Visit(E->getSubExpr()))
2379 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002380 if (!CheckValidLValue())
2381 return false;
2382 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002383 }
2384 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00002385
Eli Friedman449fe542009-03-23 04:56:01 +00002386 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00002387
Eli Friedman9a156e52008-11-12 09:44:48 +00002388};
2389} // end anonymous namespace
2390
Richard Smith11562c52011-10-28 17:51:58 +00002391/// Evaluate an expression as an lvalue. This can be legitimately called on
2392/// expressions which are not glvalues, in a few cases:
2393/// * function designators in C,
2394/// * "extern void" objects,
2395/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002396static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002397 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2398 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2399 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002400 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002401}
2402
Peter Collingbournee9200682011-05-13 03:29:01 +00002403bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002404 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2405 return Success(FD);
2406 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002407 return VisitVarDecl(E, VD);
2408 return Error(E);
2409}
Richard Smith733237d2011-10-24 23:14:33 +00002410
Richard Smith11562c52011-10-28 17:51:58 +00002411bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002412 if (!VD->getType()->isReferenceType()) {
2413 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002414 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002415 return true;
2416 }
Richard Smithce40ad62011-11-12 22:28:03 +00002417 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002418 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002419
Richard Smith0b0a0b62011-10-29 20:57:55 +00002420 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002421 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2422 return false;
2423 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002424}
2425
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002426bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2427 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002428 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002429 if (E->getType()->isRecordType())
Richard Smith027bf112011-11-17 22:56:20 +00002430 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2431
2432 Result.set(E, Info.CurrentCall);
2433 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2434 Result, E->GetTemporaryExpr());
2435 }
2436
2437 // Materialization of an lvalue temporary occurs when we need to force a copy
2438 // (for instance, if it's a bitfield).
2439 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2440 if (!Visit(E->GetTemporaryExpr()))
2441 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002442 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002443 Info.CurrentCall->Temporaries[E]))
2444 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002445 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002446 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002447}
2448
Peter Collingbournee9200682011-05-13 03:29:01 +00002449bool
2450LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002451 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2452 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2453 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002454 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002455}
2456
Richard Smith6e525142011-12-27 12:18:28 +00002457bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2458 if (E->isTypeOperand())
2459 return Success(E);
2460 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2461 if (RD && RD->isPolymorphic()) {
2462 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2463 << E->getExprOperand()->getType()
2464 << E->getExprOperand()->getSourceRange();
2465 return false;
2466 }
2467 return Success(E);
2468}
2469
Peter Collingbournee9200682011-05-13 03:29:01 +00002470bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002471 // Handle static data members.
2472 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2473 VisitIgnoredValue(E->getBase());
2474 return VisitVarDecl(E, VD);
2475 }
2476
Richard Smith254a73d2011-10-28 22:34:42 +00002477 // Handle static member functions.
2478 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2479 if (MD->isStatic()) {
2480 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002481 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002482 }
2483 }
2484
Richard Smithd62306a2011-11-10 06:34:14 +00002485 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002486 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002487}
2488
Peter Collingbournee9200682011-05-13 03:29:01 +00002489bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002490 // FIXME: Deal with vectors as array subscript bases.
2491 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002492 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002493
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002494 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002495 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002496
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002497 APSInt Index;
2498 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002499 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002500 int64_t IndexValue
2501 = Index.isSigned() ? Index.getSExtValue()
2502 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002503
Richard Smith027bf112011-11-17 22:56:20 +00002504 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002505 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002506}
Eli Friedman9a156e52008-11-12 09:44:48 +00002507
Peter Collingbournee9200682011-05-13 03:29:01 +00002508bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002509 // FIXME: In C++11, require the result to be a valid lvalue.
John McCall45d55e42010-05-07 21:00:08 +00002510 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002511}
2512
Eli Friedman9a156e52008-11-12 09:44:48 +00002513//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002514// Pointer Evaluation
2515//===----------------------------------------------------------------------===//
2516
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002517namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002518class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002519 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002520 LValue &Result;
2521
Peter Collingbournee9200682011-05-13 03:29:01 +00002522 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002523 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002524 return true;
2525 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002526public:
Mike Stump11289f42009-09-09 15:08:12 +00002527
John McCall45d55e42010-05-07 21:00:08 +00002528 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002529 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002530
Richard Smith0b0a0b62011-10-29 20:57:55 +00002531 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002532 Result.setFrom(V);
2533 return true;
2534 }
Richard Smith771c4a12011-12-25 20:00:17 +00002535 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002536 return Success((Expr*)0);
2537 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002538
John McCall45d55e42010-05-07 21:00:08 +00002539 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002540 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002541 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002542 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002543 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002544 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002545 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002546 bool VisitCallExpr(const CallExpr *E);
2547 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002548 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002549 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002550 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002551 }
Richard Smithd62306a2011-11-10 06:34:14 +00002552 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2553 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002554 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002555 Result = *Info.CurrentCall->This;
2556 return true;
2557 }
John McCallc07a0c72011-02-17 10:25:35 +00002558
Eli Friedman449fe542009-03-23 04:56:01 +00002559 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002560};
Chris Lattner05706e882008-07-11 18:11:29 +00002561} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002562
John McCall45d55e42010-05-07 21:00:08 +00002563static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002564 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002565 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002566}
2567
John McCall45d55e42010-05-07 21:00:08 +00002568bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002569 if (E->getOpcode() != BO_Add &&
2570 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002571 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002572
Chris Lattner05706e882008-07-11 18:11:29 +00002573 const Expr *PExp = E->getLHS();
2574 const Expr *IExp = E->getRHS();
2575 if (IExp->getType()->isPointerType())
2576 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002577
John McCall45d55e42010-05-07 21:00:08 +00002578 if (!EvaluatePointer(PExp, Result, Info))
2579 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002580
John McCall45d55e42010-05-07 21:00:08 +00002581 llvm::APSInt Offset;
2582 if (!EvaluateInteger(IExp, Offset, Info))
2583 return false;
2584 int64_t AdditionalOffset
2585 = Offset.isSigned() ? Offset.getSExtValue()
2586 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002587 if (E->getOpcode() == BO_Sub)
2588 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002589
Richard Smithd62306a2011-11-10 06:34:14 +00002590 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith027bf112011-11-17 22:56:20 +00002591 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002592 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002593}
Eli Friedman9a156e52008-11-12 09:44:48 +00002594
John McCall45d55e42010-05-07 21:00:08 +00002595bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2596 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002597}
Mike Stump11289f42009-09-09 15:08:12 +00002598
Peter Collingbournee9200682011-05-13 03:29:01 +00002599bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2600 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002601
Eli Friedman847a2bc2009-12-27 05:43:15 +00002602 switch (E->getCastKind()) {
2603 default:
2604 break;
2605
John McCalle3027922010-08-25 11:45:40 +00002606 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002607 case CK_CPointerToObjCPointerCast:
2608 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002609 case CK_AnyPointerToBlockPointerCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002610 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2611 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2612 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00002613 if (!E->getType()->isVoidPointerType()) {
2614 if (SubExpr->getType()->isVoidPointerType())
2615 CCEDiag(E, diag::note_constexpr_invalid_cast)
2616 << 3 << SubExpr->getType();
2617 else
2618 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2619 }
Richard Smith96e0c102011-11-04 02:25:55 +00002620 if (!Visit(SubExpr))
2621 return false;
2622 Result.Designator.setInvalid();
2623 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002624
Anders Carlsson18275092010-10-31 20:41:46 +00002625 case CK_DerivedToBase:
2626 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002627 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002628 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002629 if (!Result.Base && Result.Offset.isZero())
2630 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002631
Richard Smithd62306a2011-11-10 06:34:14 +00002632 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002633 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002634 QualType Type =
2635 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002636
Richard Smithd62306a2011-11-10 06:34:14 +00002637 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002638 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithd62306a2011-11-10 06:34:14 +00002639 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002640 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002641 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002642 }
2643
Anders Carlsson18275092010-10-31 20:41:46 +00002644 return true;
2645 }
2646
Richard Smith027bf112011-11-17 22:56:20 +00002647 case CK_BaseToDerived:
2648 if (!Visit(E->getSubExpr()))
2649 return false;
2650 if (!Result.Base && Result.Offset.isZero())
2651 return true;
2652 return HandleBaseToDerivedCast(Info, E, Result);
2653
Richard Smith0b0a0b62011-10-29 20:57:55 +00002654 case CK_NullToPointer:
Richard Smith771c4a12011-12-25 20:00:17 +00002655 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002656
John McCalle3027922010-08-25 11:45:40 +00002657 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00002658 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2659
Richard Smith0b0a0b62011-10-29 20:57:55 +00002660 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002661 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002662 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002663
John McCall45d55e42010-05-07 21:00:08 +00002664 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002665 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2666 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002667 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002668 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002669 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002670 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002671 return true;
2672 } else {
2673 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002674 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002675 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002676 }
2677 }
John McCalle3027922010-08-25 11:45:40 +00002678 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002679 if (SubExpr->isGLValue()) {
2680 if (!EvaluateLValue(SubExpr, Result, Info))
2681 return false;
2682 } else {
2683 Result.set(SubExpr, Info.CurrentCall);
2684 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2685 Info, Result, SubExpr))
2686 return false;
2687 }
Richard Smith96e0c102011-11-04 02:25:55 +00002688 // The result is a pointer to the first element of the array.
2689 Result.Designator.addIndex(0);
2690 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002691
John McCalle3027922010-08-25 11:45:40 +00002692 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002693 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002694 }
2695
Richard Smith11562c52011-10-28 17:51:58 +00002696 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002697}
Chris Lattner05706e882008-07-11 18:11:29 +00002698
Peter Collingbournee9200682011-05-13 03:29:01 +00002699bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002700 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002701 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002702
Peter Collingbournee9200682011-05-13 03:29:01 +00002703 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002704}
Chris Lattner05706e882008-07-11 18:11:29 +00002705
2706//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002707// Member Pointer Evaluation
2708//===----------------------------------------------------------------------===//
2709
2710namespace {
2711class MemberPointerExprEvaluator
2712 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2713 MemberPtr &Result;
2714
2715 bool Success(const ValueDecl *D) {
2716 Result = MemberPtr(D);
2717 return true;
2718 }
2719public:
2720
2721 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2722 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2723
2724 bool Success(const CCValue &V, const Expr *E) {
2725 Result.setFrom(V);
2726 return true;
2727 }
Richard Smith771c4a12011-12-25 20:00:17 +00002728 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002729 return Success((const ValueDecl*)0);
2730 }
2731
2732 bool VisitCastExpr(const CastExpr *E);
2733 bool VisitUnaryAddrOf(const UnaryOperator *E);
2734};
2735} // end anonymous namespace
2736
2737static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2738 EvalInfo &Info) {
2739 assert(E->isRValue() && E->getType()->isMemberPointerType());
2740 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2741}
2742
2743bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2744 switch (E->getCastKind()) {
2745 default:
2746 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2747
2748 case CK_NullToMemberPointer:
Richard Smith771c4a12011-12-25 20:00:17 +00002749 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002750
2751 case CK_BaseToDerivedMemberPointer: {
2752 if (!Visit(E->getSubExpr()))
2753 return false;
2754 if (E->path_empty())
2755 return true;
2756 // Base-to-derived member pointer casts store the path in derived-to-base
2757 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2758 // the wrong end of the derived->base arc, so stagger the path by one class.
2759 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2760 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2761 PathI != PathE; ++PathI) {
2762 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2763 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2764 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002765 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002766 }
2767 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2768 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002769 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002770 return true;
2771 }
2772
2773 case CK_DerivedToBaseMemberPointer:
2774 if (!Visit(E->getSubExpr()))
2775 return false;
2776 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2777 PathE = E->path_end(); PathI != PathE; ++PathI) {
2778 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2779 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2780 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002781 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002782 }
2783 return true;
2784 }
2785}
2786
2787bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2788 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2789 // member can be formed.
2790 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2791}
2792
2793//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002794// Record Evaluation
2795//===----------------------------------------------------------------------===//
2796
2797namespace {
2798 class RecordExprEvaluator
2799 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2800 const LValue &This;
2801 APValue &Result;
2802 public:
2803
2804 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2805 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2806
2807 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002808 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002809 }
Richard Smith771c4a12011-12-25 20:00:17 +00002810 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002811
Richard Smithe97cbd72011-11-11 04:05:33 +00002812 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002813 bool VisitInitListExpr(const InitListExpr *E);
2814 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2815 };
2816}
2817
Richard Smith771c4a12011-12-25 20:00:17 +00002818/// Perform zero-initialization on an object of non-union class type.
2819/// C++11 [dcl.init]p5:
2820/// To zero-initialize an object or reference of type T means:
2821/// [...]
2822/// -- if T is a (possibly cv-qualified) non-union class type,
2823/// each non-static data member and each base-class subobject is
2824/// zero-initialized
2825static bool HandleClassZeroInitialization(EvalInfo &Info, const RecordDecl *RD,
2826 const LValue &This, APValue &Result) {
2827 assert(!RD->isUnion() && "Expected non-union class type");
2828 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
2829 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
2830 std::distance(RD->field_begin(), RD->field_end()));
2831
2832 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2833
2834 if (CD) {
2835 unsigned Index = 0;
2836 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
2837 E = CD->bases_end(); I != E; ++I, ++Index) {
2838 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
2839 LValue Subobject = This;
2840 HandleLValueDirectBase(Info, Subobject, CD, Base, &Layout);
2841 if (!HandleClassZeroInitialization(Info, Base, Subobject,
2842 Result.getStructBase(Index)))
2843 return false;
2844 }
2845 }
2846
2847 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2848 I != E; ++I) {
2849 // -- if T is a reference type, no initialization is performed.
2850 if ((*I)->getType()->isReferenceType())
2851 continue;
2852
2853 LValue Subobject = This;
2854 HandleLValueMember(Info, Subobject, *I, &Layout);
2855
2856 ImplicitValueInitExpr VIE((*I)->getType());
2857 if (!EvaluateConstantExpression(
2858 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
2859 return false;
2860 }
2861
2862 return true;
2863}
2864
2865bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
2866 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2867 if (RD->isUnion()) {
2868 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
2869 // object's first non-static named data member is zero-initialized
2870 RecordDecl::field_iterator I = RD->field_begin();
2871 if (I == RD->field_end()) {
2872 Result = APValue((const FieldDecl*)0);
2873 return true;
2874 }
2875
2876 LValue Subobject = This;
2877 HandleLValueMember(Info, Subobject, *I);
2878 Result = APValue(*I);
2879 ImplicitValueInitExpr VIE((*I)->getType());
2880 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2881 Subobject, &VIE);
2882 }
2883
2884 return HandleClassZeroInitialization(Info, RD, This, Result);
2885}
2886
Richard Smithe97cbd72011-11-11 04:05:33 +00002887bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2888 switch (E->getCastKind()) {
2889 default:
2890 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2891
2892 case CK_ConstructorConversion:
2893 return Visit(E->getSubExpr());
2894
2895 case CK_DerivedToBase:
2896 case CK_UncheckedDerivedToBase: {
2897 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002898 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002899 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002900 if (!DerivedObject.isStruct())
2901 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00002902
2903 // Derived-to-base rvalue conversion: just slice off the derived part.
2904 APValue *Value = &DerivedObject;
2905 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2906 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2907 PathE = E->path_end(); PathI != PathE; ++PathI) {
2908 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2909 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2910 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2911 RD = Base;
2912 }
2913 Result = *Value;
2914 return true;
2915 }
2916 }
2917}
2918
Richard Smithd62306a2011-11-10 06:34:14 +00002919bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2920 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2921 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2922
2923 if (RD->isUnion()) {
2924 Result = APValue(E->getInitializedFieldInUnion());
2925 if (!E->getNumInits())
2926 return true;
2927 LValue Subobject = This;
2928 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2929 &Layout);
2930 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2931 Subobject, E->getInit(0));
2932 }
2933
2934 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2935 "initializer list for class with base classes");
2936 Result = APValue(APValue::UninitStruct(), 0,
2937 std::distance(RD->field_begin(), RD->field_end()));
2938 unsigned ElementNo = 0;
2939 for (RecordDecl::field_iterator Field = RD->field_begin(),
2940 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2941 // Anonymous bit-fields are not considered members of the class for
2942 // purposes of aggregate initialization.
2943 if (Field->isUnnamedBitfield())
2944 continue;
2945
2946 LValue Subobject = This;
2947 HandleLValueMember(Info, Subobject, *Field, &Layout);
2948
2949 if (ElementNo < E->getNumInits()) {
2950 if (!EvaluateConstantExpression(
2951 Result.getStructField((*Field)->getFieldIndex()),
2952 Info, Subobject, E->getInit(ElementNo++)))
2953 return false;
2954 } else {
2955 // Perform an implicit value-initialization for members beyond the end of
2956 // the initializer list.
2957 ImplicitValueInitExpr VIE(Field->getType());
2958 if (!EvaluateConstantExpression(
2959 Result.getStructField((*Field)->getFieldIndex()),
2960 Info, Subobject, &VIE))
2961 return false;
2962 }
2963 }
2964
2965 return true;
2966}
2967
2968bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2969 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith771c4a12011-12-25 20:00:17 +00002970 bool ZeroInit = E->requiresZeroInitialization();
2971 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
2972 if (ZeroInit)
2973 return ZeroInitialization(E);
2974
Richard Smithcc36f692011-12-22 02:22:31 +00002975 const CXXRecordDecl *RD = FD->getParent();
2976 if (RD->isUnion())
2977 Result = APValue((FieldDecl*)0);
2978 else
2979 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2980 std::distance(RD->field_begin(), RD->field_end()));
2981 return true;
2982 }
2983
Richard Smithd62306a2011-11-10 06:34:14 +00002984 const FunctionDecl *Definition = 0;
2985 FD->getBody(Definition);
2986
Richard Smith357362d2011-12-13 06:39:58 +00002987 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2988 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002989
2990 // FIXME: Elide the copy/move construction wherever we can.
Richard Smith771c4a12011-12-25 20:00:17 +00002991 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00002992 if (const MaterializeTemporaryExpr *ME
2993 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2994 return Visit(ME->GetTemporaryExpr());
2995
Richard Smith771c4a12011-12-25 20:00:17 +00002996 if (ZeroInit && !ZeroInitialization(E))
2997 return false;
2998
Richard Smithd62306a2011-11-10 06:34:14 +00002999 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003000 return HandleConstructorCall(E, This, Args,
3001 cast<CXXConstructorDecl>(Definition), Info,
3002 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00003003}
3004
3005static bool EvaluateRecord(const Expr *E, const LValue &This,
3006 APValue &Result, EvalInfo &Info) {
3007 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00003008 "can't evaluate expression as a record rvalue");
3009 return RecordExprEvaluator(Info, This, Result).Visit(E);
3010}
3011
3012//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003013// Temporary Evaluation
3014//
3015// Temporaries are represented in the AST as rvalues, but generally behave like
3016// lvalues. The full-object of which the temporary is a subobject is implicitly
3017// materialized so that a reference can bind to it.
3018//===----------------------------------------------------------------------===//
3019namespace {
3020class TemporaryExprEvaluator
3021 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3022public:
3023 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3024 LValueExprEvaluatorBaseTy(Info, Result) {}
3025
3026 /// Visit an expression which constructs the value of this temporary.
3027 bool VisitConstructExpr(const Expr *E) {
3028 Result.set(E, Info.CurrentCall);
3029 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3030 Result, E);
3031 }
3032
3033 bool VisitCastExpr(const CastExpr *E) {
3034 switch (E->getCastKind()) {
3035 default:
3036 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3037
3038 case CK_ConstructorConversion:
3039 return VisitConstructExpr(E->getSubExpr());
3040 }
3041 }
3042 bool VisitInitListExpr(const InitListExpr *E) {
3043 return VisitConstructExpr(E);
3044 }
3045 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3046 return VisitConstructExpr(E);
3047 }
3048 bool VisitCallExpr(const CallExpr *E) {
3049 return VisitConstructExpr(E);
3050 }
3051};
3052} // end anonymous namespace
3053
3054/// Evaluate an expression of record type as a temporary.
3055static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003056 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00003057 return TemporaryExprEvaluator(Info, Result).Visit(E);
3058}
3059
3060//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003061// Vector Evaluation
3062//===----------------------------------------------------------------------===//
3063
3064namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003065 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00003066 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3067 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003068 public:
Mike Stump11289f42009-09-09 15:08:12 +00003069
Richard Smith2d406342011-10-22 21:10:00 +00003070 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3071 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003072
Richard Smith2d406342011-10-22 21:10:00 +00003073 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3074 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3075 // FIXME: remove this APValue copy.
3076 Result = APValue(V.data(), V.size());
3077 return true;
3078 }
Richard Smithed5165f2011-11-04 05:33:44 +00003079 bool Success(const CCValue &V, const Expr *E) {
3080 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00003081 Result = V;
3082 return true;
3083 }
Richard Smith771c4a12011-12-25 20:00:17 +00003084 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003085
Richard Smith2d406342011-10-22 21:10:00 +00003086 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00003087 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00003088 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00003089 bool VisitInitListExpr(const InitListExpr *E);
3090 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003091 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00003092 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00003093 // shufflevector, ExtVectorElementExpr
3094 // (Note that these require implementing conversions
3095 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003096 };
3097} // end anonymous namespace
3098
3099static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003100 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00003101 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003102}
3103
Richard Smith2d406342011-10-22 21:10:00 +00003104bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3105 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003106 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003107
Richard Smith161f09a2011-12-06 22:44:34 +00003108 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00003109 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003110
Eli Friedmanc757de22011-03-25 00:43:55 +00003111 switch (E->getCastKind()) {
3112 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00003113 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00003114 if (SETy->isIntegerType()) {
3115 APSInt IntResult;
3116 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003117 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003118 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00003119 } else if (SETy->isRealFloatingType()) {
3120 APFloat F(0.0);
3121 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003122 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003123 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00003124 } else {
Richard Smith2d406342011-10-22 21:10:00 +00003125 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003126 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003127
3128 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00003129 SmallVector<APValue, 4> Elts(NElts, Val);
3130 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00003131 }
Eli Friedman803acb32011-12-22 03:51:45 +00003132 case CK_BitCast: {
3133 // Evaluate the operand into an APInt we can extract from.
3134 llvm::APInt SValInt;
3135 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3136 return false;
3137 // Extract the elements
3138 QualType EltTy = VTy->getElementType();
3139 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3140 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3141 SmallVector<APValue, 4> Elts;
3142 if (EltTy->isRealFloatingType()) {
3143 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3144 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3145 unsigned FloatEltSize = EltSize;
3146 if (&Sem == &APFloat::x87DoubleExtended)
3147 FloatEltSize = 80;
3148 for (unsigned i = 0; i < NElts; i++) {
3149 llvm::APInt Elt;
3150 if (BigEndian)
3151 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3152 else
3153 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3154 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3155 }
3156 } else if (EltTy->isIntegerType()) {
3157 for (unsigned i = 0; i < NElts; i++) {
3158 llvm::APInt Elt;
3159 if (BigEndian)
3160 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3161 else
3162 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3163 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3164 }
3165 } else {
3166 return Error(E);
3167 }
3168 return Success(Elts, E);
3169 }
Eli Friedmanc757de22011-03-25 00:43:55 +00003170 default:
Richard Smith11562c52011-10-28 17:51:58 +00003171 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003172 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003173}
3174
Richard Smith2d406342011-10-22 21:10:00 +00003175bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003176VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003177 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003178 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00003179 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003180
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003181 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003182 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003183
John McCall875679e2010-06-11 17:54:15 +00003184 // If a vector is initialized with a single element, that value
3185 // becomes every element of the vector, not just the first.
3186 // This is the behavior described in the IBM AltiVec documentation.
3187 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00003188
3189 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00003190 // vector (OpenCL 6.1.6).
3191 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00003192 return Visit(E->getInit(0));
3193
John McCall875679e2010-06-11 17:54:15 +00003194 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003195 if (EltTy->isIntegerType()) {
3196 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00003197 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003198 return false;
John McCall875679e2010-06-11 17:54:15 +00003199 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003200 } else {
3201 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00003202 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003203 return false;
John McCall875679e2010-06-11 17:54:15 +00003204 InitValue = APValue(f);
3205 }
3206 for (unsigned i = 0; i < NumElements; i++) {
3207 Elements.push_back(InitValue);
3208 }
3209 } else {
3210 for (unsigned i = 0; i < NumElements; i++) {
3211 if (EltTy->isIntegerType()) {
3212 llvm::APSInt sInt(32);
3213 if (i < NumInits) {
3214 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003215 return false;
John McCall875679e2010-06-11 17:54:15 +00003216 } else {
3217 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3218 }
3219 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00003220 } else {
John McCall875679e2010-06-11 17:54:15 +00003221 llvm::APFloat f(0.0);
3222 if (i < NumInits) {
3223 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003224 return false;
John McCall875679e2010-06-11 17:54:15 +00003225 } else {
3226 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3227 }
3228 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00003229 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003230 }
3231 }
Richard Smith2d406342011-10-22 21:10:00 +00003232 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003233}
3234
Richard Smith2d406342011-10-22 21:10:00 +00003235bool
Richard Smith771c4a12011-12-25 20:00:17 +00003236VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003237 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00003238 QualType EltTy = VT->getElementType();
3239 APValue ZeroElement;
3240 if (EltTy->isIntegerType())
3241 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3242 else
3243 ZeroElement =
3244 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3245
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003246 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00003247 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003248}
3249
Richard Smith2d406342011-10-22 21:10:00 +00003250bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00003251 VisitIgnoredValue(E->getSubExpr());
Richard Smith771c4a12011-12-25 20:00:17 +00003252 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003253}
3254
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003255//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00003256// Array Evaluation
3257//===----------------------------------------------------------------------===//
3258
3259namespace {
3260 class ArrayExprEvaluator
3261 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00003262 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00003263 APValue &Result;
3264 public:
3265
Richard Smithd62306a2011-11-10 06:34:14 +00003266 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3267 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00003268
3269 bool Success(const APValue &V, const Expr *E) {
3270 assert(V.isArray() && "Expected array type");
3271 Result = V;
3272 return true;
3273 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003274
Richard Smith771c4a12011-12-25 20:00:17 +00003275 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003276 const ConstantArrayType *CAT =
3277 Info.Ctx.getAsConstantArrayType(E->getType());
3278 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003279 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003280
3281 Result = APValue(APValue::UninitArray(), 0,
3282 CAT->getSize().getZExtValue());
3283 if (!Result.hasArrayFiller()) return true;
3284
Richard Smith771c4a12011-12-25 20:00:17 +00003285 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00003286 LValue Subobject = This;
3287 Subobject.Designator.addIndex(0);
3288 ImplicitValueInitExpr VIE(CAT->getElementType());
3289 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3290 Subobject, &VIE);
3291 }
3292
Richard Smithf3e9e432011-11-07 09:22:26 +00003293 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00003294 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003295 };
3296} // end anonymous namespace
3297
Richard Smithd62306a2011-11-10 06:34:14 +00003298static bool EvaluateArray(const Expr *E, const LValue &This,
3299 APValue &Result, EvalInfo &Info) {
Richard Smith771c4a12011-12-25 20:00:17 +00003300 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00003301 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003302}
3303
3304bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3305 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3306 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003307 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003308
Richard Smithca2cfbf2011-12-22 01:07:19 +00003309 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3310 // an appropriately-typed string literal enclosed in braces.
3311 if (E->getNumInits() == 1 && CAT->getElementType()->isAnyCharacterType() &&
3312 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3313 LValue LV;
3314 if (!EvaluateLValue(E->getInit(0), LV, Info))
3315 return false;
3316 uint64_t NumElements = CAT->getSize().getZExtValue();
3317 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3318
3319 // Copy the string literal into the array. FIXME: Do this better.
3320 LV.Designator.addIndex(0);
3321 for (uint64_t I = 0; I < NumElements; ++I) {
3322 CCValue Char;
3323 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3324 CAT->getElementType(), LV, Char))
3325 return false;
3326 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3327 Result.getArrayInitializedElt(I)))
3328 return false;
3329 if (!HandleLValueArrayAdjustment(Info, LV, CAT->getElementType(), 1))
3330 return false;
3331 }
3332 return true;
3333 }
3334
Richard Smithf3e9e432011-11-07 09:22:26 +00003335 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3336 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00003337 LValue Subobject = This;
3338 Subobject.Designator.addIndex(0);
3339 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00003340 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00003341 I != End; ++I, ++Index) {
3342 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3343 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00003344 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003345 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
3346 return false;
3347 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003348
3349 if (!Result.hasArrayFiller()) return true;
3350 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00003351 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3352 // but sometimes does:
3353 // struct S { constexpr S() : p(&p) {} void *p; };
3354 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00003355 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00003356 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00003357}
3358
Richard Smith027bf112011-11-17 22:56:20 +00003359bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3360 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3361 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003362 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003363
3364 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3365 if (!Result.hasArrayFiller())
3366 return true;
3367
3368 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00003369
Richard Smith771c4a12011-12-25 20:00:17 +00003370 bool ZeroInit = E->requiresZeroInitialization();
3371 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3372 if (ZeroInit) {
3373 LValue Subobject = This;
3374 Subobject.Designator.addIndex(0);
3375 ImplicitValueInitExpr VIE(CAT->getElementType());
3376 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3377 Subobject, &VIE);
3378 }
3379
Richard Smithcc36f692011-12-22 02:22:31 +00003380 const CXXRecordDecl *RD = FD->getParent();
3381 if (RD->isUnion())
3382 Result.getArrayFiller() = APValue((FieldDecl*)0);
3383 else
3384 Result.getArrayFiller() =
3385 APValue(APValue::UninitStruct(), RD->getNumBases(),
3386 std::distance(RD->field_begin(), RD->field_end()));
3387 return true;
3388 }
3389
Richard Smith027bf112011-11-17 22:56:20 +00003390 const FunctionDecl *Definition = 0;
3391 FD->getBody(Definition);
3392
Richard Smith357362d2011-12-13 06:39:58 +00003393 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3394 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003395
3396 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3397 // but sometimes does:
3398 // struct S { constexpr S() : p(&p) {} void *p; };
3399 // S s[10];
3400 LValue Subobject = This;
3401 Subobject.Designator.addIndex(0);
Richard Smith771c4a12011-12-25 20:00:17 +00003402
3403 if (ZeroInit) {
3404 ImplicitValueInitExpr VIE(CAT->getElementType());
3405 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3406 &VIE))
3407 return false;
3408 }
3409
Richard Smith027bf112011-11-17 22:56:20 +00003410 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003411 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003412 cast<CXXConstructorDecl>(Definition),
3413 Info, Result.getArrayFiller());
3414}
3415
Richard Smithf3e9e432011-11-07 09:22:26 +00003416//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003417// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003418//
3419// As a GNU extension, we support casting pointers to sufficiently-wide integer
3420// types and back in constant folding. Integer values are thus represented
3421// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003422//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003423
3424namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003425class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003426 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003427 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003428public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00003429 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003430 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003431
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003432 bool Success(const llvm::APSInt &SI, const Expr *E) {
3433 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003434 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003435 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003436 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003437 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003438 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003439 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003440 return true;
3441 }
3442
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003443 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003444 assert(E->getType()->isIntegralOrEnumerationType() &&
3445 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003446 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003447 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003448 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003449 Result.getInt().setIsUnsigned(
3450 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003451 return true;
3452 }
3453
3454 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003455 assert(E->getType()->isIntegralOrEnumerationType() &&
3456 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003457 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003458 return true;
3459 }
3460
Ken Dyckdbc01912011-03-11 02:13:43 +00003461 bool Success(CharUnits Size, const Expr *E) {
3462 return Success(Size.getQuantity(), E);
3463 }
3464
Richard Smith0b0a0b62011-10-29 20:57:55 +00003465 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00003466 if (V.isLValue()) {
3467 Result = V;
3468 return true;
3469 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003470 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003471 }
Mike Stump11289f42009-09-09 15:08:12 +00003472
Richard Smith771c4a12011-12-25 20:00:17 +00003473 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00003474
Peter Collingbournee9200682011-05-13 03:29:01 +00003475 //===--------------------------------------------------------------------===//
3476 // Visitor Methods
3477 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003478
Chris Lattner7174bf32008-07-12 00:38:25 +00003479 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003480 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003481 }
3482 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003483 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003484 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003485
3486 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3487 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003488 if (CheckReferencedDecl(E, E->getDecl()))
3489 return true;
3490
3491 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003492 }
3493 bool VisitMemberExpr(const MemberExpr *E) {
3494 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00003495 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003496 return true;
3497 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003498
3499 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003500 }
3501
Peter Collingbournee9200682011-05-13 03:29:01 +00003502 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003503 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00003504 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003505 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00003506
Peter Collingbournee9200682011-05-13 03:29:01 +00003507 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003508 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00003509
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003510 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003511 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003512 }
Mike Stump11289f42009-09-09 15:08:12 +00003513
Richard Smith4ce706a2011-10-11 21:43:33 +00003514 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00003515 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith771c4a12011-12-25 20:00:17 +00003516 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003517 }
3518
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003519 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003520 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003521 }
3522
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003523 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3524 return Success(E->getValue(), E);
3525 }
3526
John Wiegley6242b6a2011-04-28 00:16:57 +00003527 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3528 return Success(E->getValue(), E);
3529 }
3530
John Wiegleyf9f65842011-04-25 06:54:41 +00003531 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3532 return Success(E->getValue(), E);
3533 }
3534
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003535 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003536 bool VisitUnaryImag(const UnaryOperator *E);
3537
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003538 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003539 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00003540
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003541private:
Ken Dyck160146e2010-01-27 17:10:57 +00003542 CharUnits GetAlignOfExpr(const Expr *E);
3543 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00003544 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00003545 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003546 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00003547};
Chris Lattner05706e882008-07-11 18:11:29 +00003548} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003549
Richard Smith11562c52011-10-28 17:51:58 +00003550/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3551/// produce either the integer value or a pointer.
3552///
3553/// GCC has a heinous extension which folds casts between pointer types and
3554/// pointer-sized integral types. We support this by allowing the evaluation of
3555/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3556/// Some simple arithmetic on such values is supported (they are treated much
3557/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00003558static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00003559 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003560 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003561 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00003562}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003563
Richard Smithf57d8cb2011-12-09 22:58:01 +00003564static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003565 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003566 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00003567 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003568 if (!Val.isInt()) {
3569 // FIXME: It would be better to produce the diagnostic for casting
3570 // a pointer to an integer.
Richard Smith92b1ce02011-12-12 09:28:41 +00003571 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003572 return false;
3573 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003574 Result = Val.getInt();
3575 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003576}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003577
Richard Smithf57d8cb2011-12-09 22:58:01 +00003578/// Check whether the given declaration can be directly converted to an integral
3579/// rvalue. If not, no diagnostic is produced; there are other things we can
3580/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003581bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003582 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003583 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003584 // Check for signedness/width mismatches between E type and ECD value.
3585 bool SameSign = (ECD->getInitVal().isSigned()
3586 == E->getType()->isSignedIntegerOrEnumerationType());
3587 bool SameWidth = (ECD->getInitVal().getBitWidth()
3588 == Info.Ctx.getIntWidth(E->getType()));
3589 if (SameSign && SameWidth)
3590 return Success(ECD->getInitVal(), E);
3591 else {
3592 // Get rid of mismatch (otherwise Success assertions will fail)
3593 // by computing a new value matching the type of E.
3594 llvm::APSInt Val = ECD->getInitVal();
3595 if (!SameSign)
3596 Val.setIsSigned(!ECD->getInitVal().isSigned());
3597 if (!SameWidth)
3598 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3599 return Success(Val, E);
3600 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003601 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003602 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003603}
3604
Chris Lattner86ee2862008-10-06 06:40:35 +00003605/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3606/// as GCC.
3607static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3608 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003609 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003610 enum gcc_type_class {
3611 no_type_class = -1,
3612 void_type_class, integer_type_class, char_type_class,
3613 enumeral_type_class, boolean_type_class,
3614 pointer_type_class, reference_type_class, offset_type_class,
3615 real_type_class, complex_type_class,
3616 function_type_class, method_type_class,
3617 record_type_class, union_type_class,
3618 array_type_class, string_type_class,
3619 lang_type_class
3620 };
Mike Stump11289f42009-09-09 15:08:12 +00003621
3622 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003623 // ideal, however it is what gcc does.
3624 if (E->getNumArgs() == 0)
3625 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003626
Chris Lattner86ee2862008-10-06 06:40:35 +00003627 QualType ArgTy = E->getArg(0)->getType();
3628 if (ArgTy->isVoidType())
3629 return void_type_class;
3630 else if (ArgTy->isEnumeralType())
3631 return enumeral_type_class;
3632 else if (ArgTy->isBooleanType())
3633 return boolean_type_class;
3634 else if (ArgTy->isCharType())
3635 return string_type_class; // gcc doesn't appear to use char_type_class
3636 else if (ArgTy->isIntegerType())
3637 return integer_type_class;
3638 else if (ArgTy->isPointerType())
3639 return pointer_type_class;
3640 else if (ArgTy->isReferenceType())
3641 return reference_type_class;
3642 else if (ArgTy->isRealType())
3643 return real_type_class;
3644 else if (ArgTy->isComplexType())
3645 return complex_type_class;
3646 else if (ArgTy->isFunctionType())
3647 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003648 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003649 return record_type_class;
3650 else if (ArgTy->isUnionType())
3651 return union_type_class;
3652 else if (ArgTy->isArrayType())
3653 return array_type_class;
3654 else if (ArgTy->isUnionType())
3655 return union_type_class;
3656 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003657 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003658 return -1;
3659}
3660
John McCall95007602010-05-10 23:27:23 +00003661/// Retrieves the "underlying object type" of the given expression,
3662/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003663QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3664 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3665 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003666 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003667 } else if (const Expr *E = B.get<const Expr*>()) {
3668 if (isa<CompoundLiteralExpr>(E))
3669 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003670 }
3671
3672 return QualType();
3673}
3674
Peter Collingbournee9200682011-05-13 03:29:01 +00003675bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003676 // TODO: Perhaps we should let LLVM lower this?
3677 LValue Base;
3678 if (!EvaluatePointer(E->getArg(0), Base, Info))
3679 return false;
3680
3681 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003682 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003683
Richard Smithce40ad62011-11-12 22:28:03 +00003684 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003685 if (T.isNull() ||
3686 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003687 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003688 T->isVariablyModifiedType() ||
3689 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003690 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003691
3692 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3693 CharUnits Offset = Base.getLValueOffset();
3694
3695 if (!Offset.isNegative() && Offset <= Size)
3696 Size -= Offset;
3697 else
3698 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003699 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003700}
3701
Peter Collingbournee9200682011-05-13 03:29:01 +00003702bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003703 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003704 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003705 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003706
3707 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003708 if (TryEvaluateBuiltinObjectSize(E))
3709 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003710
Eric Christopher99469702010-01-19 22:58:35 +00003711 // If evaluating the argument has side-effects we can't determine
3712 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003713 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003714 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003715 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003716 return Success(0, E);
3717 }
Mike Stump876387b2009-10-27 22:09:17 +00003718
Richard Smithf57d8cb2011-12-09 22:58:01 +00003719 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003720 }
3721
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003722 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003723 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003724
Richard Smith10c7c902011-12-09 02:04:48 +00003725 case Builtin::BI__builtin_constant_p: {
3726 const Expr *Arg = E->getArg(0);
3727 QualType ArgType = Arg->getType();
3728 // __builtin_constant_p always has one operand. The rules which gcc follows
3729 // are not precisely documented, but are as follows:
3730 //
3731 // - If the operand is of integral, floating, complex or enumeration type,
3732 // and can be folded to a known value of that type, it returns 1.
3733 // - If the operand and can be folded to a pointer to the first character
3734 // of a string literal (or such a pointer cast to an integral type), it
3735 // returns 1.
3736 //
3737 // Otherwise, it returns 0.
3738 //
3739 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3740 // its support for this does not currently work.
3741 int IsConstant = 0;
3742 if (ArgType->isIntegralOrEnumerationType()) {
3743 // Note, a pointer cast to an integral type is only a constant if it is
3744 // a pointer to the first character of a string literal.
3745 Expr::EvalResult Result;
3746 if (Arg->EvaluateAsRValue(Result, Info.Ctx) && !Result.HasSideEffects) {
3747 APValue &V = Result.Val;
3748 if (V.getKind() == APValue::LValue) {
3749 if (const Expr *E = V.getLValueBase().dyn_cast<const Expr*>())
3750 IsConstant = isa<StringLiteral>(E) && V.getLValueOffset().isZero();
3751 } else {
3752 IsConstant = 1;
3753 }
3754 }
3755 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3756 IsConstant = Arg->isEvaluatable(Info.Ctx);
3757 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3758 LValue LV;
3759 // Use a separate EvalInfo: ignore constexpr parameter and 'this' bindings
3760 // during the check.
3761 Expr::EvalStatus Status;
3762 EvalInfo SubInfo(Info.Ctx, Status);
3763 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, SubInfo)
3764 : EvaluatePointer(Arg, LV, SubInfo)) &&
3765 !Status.HasSideEffects)
3766 if (const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>())
3767 IsConstant = isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3768 }
3769
3770 return Success(IsConstant, E);
3771 }
Chris Lattnerd545ad12009-09-23 06:06:36 +00003772 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003773 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003774 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003775 return Success(Operand, E);
3776 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003777
3778 case Builtin::BI__builtin_expect:
3779 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003780
3781 case Builtin::BIstrlen:
3782 case Builtin::BI__builtin_strlen:
3783 // As an extension, we support strlen() and __builtin_strlen() as constant
3784 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003785 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003786 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3787 // The string literal may have embedded null characters. Find the first
3788 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003789 StringRef Str = S->getString();
3790 StringRef::size_type Pos = Str.find(0);
3791 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003792 Str = Str.substr(0, Pos);
3793
3794 return Success(Str.size(), E);
3795 }
3796
Richard Smithf57d8cb2011-12-09 22:58:01 +00003797 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003798
3799 case Builtin::BI__atomic_is_lock_free: {
3800 APSInt SizeVal;
3801 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3802 return false;
3803
3804 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3805 // of two less than the maximum inline atomic width, we know it is
3806 // lock-free. If the size isn't a power of two, or greater than the
3807 // maximum alignment where we promote atomics, we know it is not lock-free
3808 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3809 // the answer can only be determined at runtime; for example, 16-byte
3810 // atomics have lock-free implementations on some, but not all,
3811 // x86-64 processors.
3812
3813 // Check power-of-two.
3814 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3815 if (!Size.isPowerOfTwo())
3816#if 0
3817 // FIXME: Suppress this folding until the ABI for the promotion width
3818 // settles.
3819 return Success(0, E);
3820#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003821 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003822#endif
3823
3824#if 0
3825 // Check against promotion width.
3826 // FIXME: Suppress this folding until the ABI for the promotion width
3827 // settles.
3828 unsigned PromoteWidthBits =
3829 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3830 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3831 return Success(0, E);
3832#endif
3833
3834 // Check against inlining width.
3835 unsigned InlineWidthBits =
3836 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3837 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3838 return Success(1, E);
3839
Richard Smithf57d8cb2011-12-09 22:58:01 +00003840 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003841 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003842 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003843}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003844
Richard Smith8b3497e2011-10-31 01:37:14 +00003845static bool HasSameBase(const LValue &A, const LValue &B) {
3846 if (!A.getLValueBase())
3847 return !B.getLValueBase();
3848 if (!B.getLValueBase())
3849 return false;
3850
Richard Smithce40ad62011-11-12 22:28:03 +00003851 if (A.getLValueBase().getOpaqueValue() !=
3852 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003853 const Decl *ADecl = GetLValueBaseDecl(A);
3854 if (!ADecl)
3855 return false;
3856 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003857 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003858 return false;
3859 }
3860
3861 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003862 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003863}
3864
Chris Lattnere13042c2008-07-11 19:10:17 +00003865bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003866 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003867 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003868
John McCalle3027922010-08-25 11:45:40 +00003869 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003870 VisitIgnoredValue(E->getLHS());
3871 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003872 }
3873
3874 if (E->isLogicalOp()) {
3875 // These need to be handled specially because the operands aren't
3876 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003877 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003878
Richard Smith11562c52011-10-28 17:51:58 +00003879 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003880 // We were able to evaluate the LHS, see if we can get away with not
3881 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003882 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003883 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003884
Richard Smith11562c52011-10-28 17:51:58 +00003885 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003886 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003887 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003888 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003889 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003890 }
3891 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003892 // FIXME: If both evaluations fail, we should produce the diagnostic from
3893 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3894 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003895 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003896 // We can't evaluate the LHS; however, sometimes the result
3897 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003898 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003899 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003900 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00003901 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003902
3903 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003904 }
3905 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00003906 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00003907
Eli Friedman5a332ea2008-11-13 06:09:17 +00003908 return false;
3909 }
3910
Anders Carlssonacc79812008-11-16 07:17:21 +00003911 QualType LHSTy = E->getLHS()->getType();
3912 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003913
3914 if (LHSTy->isAnyComplexType()) {
3915 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00003916 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003917
3918 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3919 return false;
3920
3921 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3922 return false;
3923
3924 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00003925 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003926 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00003927 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003928 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3929
John McCalle3027922010-08-25 11:45:40 +00003930 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003931 return Success((CR_r == APFloat::cmpEqual &&
3932 CR_i == APFloat::cmpEqual), E);
3933 else {
John McCalle3027922010-08-25 11:45:40 +00003934 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003935 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00003936 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003937 CR_r == APFloat::cmpLessThan ||
3938 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00003939 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003940 CR_i == APFloat::cmpLessThan ||
3941 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003942 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003943 } else {
John McCalle3027922010-08-25 11:45:40 +00003944 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003945 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3946 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3947 else {
John McCalle3027922010-08-25 11:45:40 +00003948 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003949 "Invalid compex comparison.");
3950 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3951 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3952 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003953 }
3954 }
Mike Stump11289f42009-09-09 15:08:12 +00003955
Anders Carlssonacc79812008-11-16 07:17:21 +00003956 if (LHSTy->isRealFloatingType() &&
3957 RHSTy->isRealFloatingType()) {
3958 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00003959
Anders Carlssonacc79812008-11-16 07:17:21 +00003960 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3961 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003962
Anders Carlssonacc79812008-11-16 07:17:21 +00003963 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3964 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003965
Anders Carlssonacc79812008-11-16 07:17:21 +00003966 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00003967
Anders Carlssonacc79812008-11-16 07:17:21 +00003968 switch (E->getOpcode()) {
3969 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003970 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00003971 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003972 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00003973 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003974 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00003975 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003976 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003977 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00003978 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003979 E);
John McCalle3027922010-08-25 11:45:40 +00003980 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003981 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003982 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00003983 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00003984 || CR == APFloat::cmpLessThan
3985 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00003986 }
Anders Carlssonacc79812008-11-16 07:17:21 +00003987 }
Mike Stump11289f42009-09-09 15:08:12 +00003988
Eli Friedmana38da572009-04-28 19:17:36 +00003989 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003990 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00003991 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003992 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3993 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003994
John McCall45d55e42010-05-07 21:00:08 +00003995 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003996 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3997 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003998
Richard Smith8b3497e2011-10-31 01:37:14 +00003999 // Reject differing bases from the normal codepath; we special-case
4000 // comparisons to null.
4001 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00004002 // Inequalities and subtractions between unrelated pointers have
4003 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00004004 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004005 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004006 // A constant address may compare equal to the address of a symbol.
4007 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00004008 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004009 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4010 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004011 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004012 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00004013 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00004014 // distinct. However, we do know that the address of a literal will be
4015 // non-null.
4016 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4017 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004018 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004019 // We can't tell whether weak symbols will end up pointing to the same
4020 // object.
4021 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004022 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004023 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00004024 // (Note that clang defaults to -fmerge-all-constants, which can
4025 // lead to inconsistent results for comparisons involving the address
4026 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00004027 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00004028 }
Eli Friedman64004332009-03-23 04:38:34 +00004029
Richard Smithf3e9e432011-11-07 09:22:26 +00004030 // FIXME: Implement the C++11 restrictions:
4031 // - Pointer subtractions must be on elements of the same array.
4032 // - Pointer comparisons must be between members with the same access.
4033
John McCalle3027922010-08-25 11:45:40 +00004034 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00004035 QualType Type = E->getLHS()->getType();
4036 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004037
Richard Smithd62306a2011-11-10 06:34:14 +00004038 CharUnits ElementSize;
4039 if (!HandleSizeof(Info, ElementType, ElementSize))
4040 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004041
Richard Smithd62306a2011-11-10 06:34:14 +00004042 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00004043 RHSValue.getLValueOffset();
4044 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00004045 }
Richard Smith8b3497e2011-10-31 01:37:14 +00004046
4047 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4048 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4049 switch (E->getOpcode()) {
4050 default: llvm_unreachable("missing comparison operator");
4051 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4052 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4053 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4054 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4055 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4056 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00004057 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004058 }
4059 }
Douglas Gregorb90df602010-06-16 00:17:44 +00004060 if (!LHSTy->isIntegralOrEnumerationType() ||
4061 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004062 // We can't continue from here for non-integral types.
4063 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004064 }
4065
Anders Carlsson9c181652008-07-08 14:35:21 +00004066 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00004067 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00004068 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004069 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00004070
Richard Smith11562c52011-10-28 17:51:58 +00004071 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004072 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004073 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00004074
4075 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00004076 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00004077 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4078 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00004079 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00004080 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00004081 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00004082 LHSVal.getLValueOffset() -= AdditionalOffset;
4083 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00004084 return true;
4085 }
4086
4087 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00004088 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00004089 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004090 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4091 LHSVal.getInt().getZExtValue());
4092 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00004093 return true;
4094 }
4095
4096 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00004097 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004098 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004099
Richard Smith11562c52011-10-28 17:51:58 +00004100 APSInt &LHS = LHSVal.getInt();
4101 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00004102
Anders Carlsson9c181652008-07-08 14:35:21 +00004103 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004104 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004105 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004106 case BO_Mul: return Success(LHS * RHS, E);
4107 case BO_Add: return Success(LHS + RHS, E);
4108 case BO_Sub: return Success(LHS - RHS, E);
4109 case BO_And: return Success(LHS & RHS, E);
4110 case BO_Xor: return Success(LHS ^ RHS, E);
4111 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004112 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00004113 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004114 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004115 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004116 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00004117 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004118 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004119 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004120 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00004121 // During constant-folding, a negative shift is an opposite shift.
4122 if (RHS.isSigned() && RHS.isNegative()) {
4123 RHS = -RHS;
4124 goto shift_right;
4125 }
4126
4127 shift_left:
4128 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00004129 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4130 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004131 }
John McCalle3027922010-08-25 11:45:40 +00004132 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00004133 // During constant-folding, a negative shift is an opposite shift.
4134 if (RHS.isSigned() && RHS.isNegative()) {
4135 RHS = -RHS;
4136 goto shift_left;
4137 }
4138
4139 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00004140 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00004141 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4142 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004143 }
Mike Stump11289f42009-09-09 15:08:12 +00004144
Richard Smith11562c52011-10-28 17:51:58 +00004145 case BO_LT: return Success(LHS < RHS, E);
4146 case BO_GT: return Success(LHS > RHS, E);
4147 case BO_LE: return Success(LHS <= RHS, E);
4148 case BO_GE: return Success(LHS >= RHS, E);
4149 case BO_EQ: return Success(LHS == RHS, E);
4150 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00004151 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004152}
4153
Ken Dyck160146e2010-01-27 17:10:57 +00004154CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00004155 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4156 // the result is the size of the referenced type."
4157 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4158 // result shall be the alignment of the referenced type."
4159 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4160 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00004161
4162 // __alignof is defined to return the preferred alignment.
4163 return Info.Ctx.toCharUnitsFromBits(
4164 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00004165}
4166
Ken Dyck160146e2010-01-27 17:10:57 +00004167CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00004168 E = E->IgnoreParens();
4169
4170 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00004171 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00004172 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004173 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4174 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00004175
Chris Lattner68061312009-01-24 21:53:27 +00004176 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004177 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4178 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00004179
Chris Lattner24aeeab2009-01-24 21:09:06 +00004180 return GetAlignOfType(E->getType());
4181}
4182
4183
Peter Collingbournee190dee2011-03-11 19:24:49 +00004184/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4185/// a result as the expression's type.
4186bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4187 const UnaryExprOrTypeTraitExpr *E) {
4188 switch(E->getKind()) {
4189 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00004190 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00004191 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004192 else
Ken Dyckdbc01912011-03-11 02:13:43 +00004193 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004194 }
Eli Friedman64004332009-03-23 04:38:34 +00004195
Peter Collingbournee190dee2011-03-11 19:24:49 +00004196 case UETT_VecStep: {
4197 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00004198
Peter Collingbournee190dee2011-03-11 19:24:49 +00004199 if (Ty->isVectorType()) {
4200 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00004201
Peter Collingbournee190dee2011-03-11 19:24:49 +00004202 // The vec_step built-in functions that take a 3-component
4203 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4204 if (n == 3)
4205 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00004206
Peter Collingbournee190dee2011-03-11 19:24:49 +00004207 return Success(n, E);
4208 } else
4209 return Success(1, E);
4210 }
4211
4212 case UETT_SizeOf: {
4213 QualType SrcTy = E->getTypeOfArgument();
4214 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4215 // the result is the size of the referenced type."
4216 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4217 // result shall be the alignment of the referenced type."
4218 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4219 SrcTy = Ref->getPointeeType();
4220
Richard Smithd62306a2011-11-10 06:34:14 +00004221 CharUnits Sizeof;
4222 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00004223 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004224 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004225 }
4226 }
4227
4228 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004229 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004230}
4231
Peter Collingbournee9200682011-05-13 03:29:01 +00004232bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00004233 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00004234 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00004235 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004236 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00004237 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00004238 for (unsigned i = 0; i != n; ++i) {
4239 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4240 switch (ON.getKind()) {
4241 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00004242 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00004243 APSInt IdxResult;
4244 if (!EvaluateInteger(Idx, IdxResult, Info))
4245 return false;
4246 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4247 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004248 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004249 CurrentType = AT->getElementType();
4250 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4251 Result += IdxResult.getSExtValue() * ElementSize;
4252 break;
4253 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004254
Douglas Gregor882211c2010-04-28 22:16:22 +00004255 case OffsetOfExpr::OffsetOfNode::Field: {
4256 FieldDecl *MemberDecl = ON.getField();
4257 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004258 if (!RT)
4259 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004260 RecordDecl *RD = RT->getDecl();
4261 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00004262 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00004263 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00004264 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00004265 CurrentType = MemberDecl->getType().getNonReferenceType();
4266 break;
4267 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004268
Douglas Gregor882211c2010-04-28 22:16:22 +00004269 case OffsetOfExpr::OffsetOfNode::Identifier:
4270 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004271 return Error(OOE);
4272
Douglas Gregord1702062010-04-29 00:18:15 +00004273 case OffsetOfExpr::OffsetOfNode::Base: {
4274 CXXBaseSpecifier *BaseSpec = ON.getBase();
4275 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004276 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004277
4278 // Find the layout of the class whose base we are looking into.
4279 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004280 if (!RT)
4281 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004282 RecordDecl *RD = RT->getDecl();
4283 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4284
4285 // Find the base class itself.
4286 CurrentType = BaseSpec->getType();
4287 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4288 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004289 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004290
4291 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00004292 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00004293 break;
4294 }
Douglas Gregor882211c2010-04-28 22:16:22 +00004295 }
4296 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004297 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004298}
4299
Chris Lattnere13042c2008-07-11 19:10:17 +00004300bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004301 switch (E->getOpcode()) {
4302 default:
4303 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4304 // See C99 6.6p3.
4305 return Error(E);
4306 case UO_Extension:
4307 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4308 // If so, we could clear the diagnostic ID.
4309 return Visit(E->getSubExpr());
4310 case UO_Plus:
4311 // The result is just the value.
4312 return Visit(E->getSubExpr());
4313 case UO_Minus: {
4314 if (!Visit(E->getSubExpr()))
4315 return false;
4316 if (!Result.isInt()) return Error(E);
4317 return Success(-Result.getInt(), E);
4318 }
4319 case UO_Not: {
4320 if (!Visit(E->getSubExpr()))
4321 return false;
4322 if (!Result.isInt()) return Error(E);
4323 return Success(~Result.getInt(), E);
4324 }
4325 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00004326 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00004327 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00004328 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004329 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004330 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004331 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004332}
Mike Stump11289f42009-09-09 15:08:12 +00004333
Chris Lattner477c4be2008-07-12 01:15:53 +00004334/// HandleCast - This is used to evaluate implicit or explicit casts where the
4335/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00004336bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4337 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004338 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00004339 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004340
Eli Friedmanc757de22011-03-25 00:43:55 +00004341 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00004342 case CK_BaseToDerived:
4343 case CK_DerivedToBase:
4344 case CK_UncheckedDerivedToBase:
4345 case CK_Dynamic:
4346 case CK_ToUnion:
4347 case CK_ArrayToPointerDecay:
4348 case CK_FunctionToPointerDecay:
4349 case CK_NullToPointer:
4350 case CK_NullToMemberPointer:
4351 case CK_BaseToDerivedMemberPointer:
4352 case CK_DerivedToBaseMemberPointer:
4353 case CK_ConstructorConversion:
4354 case CK_IntegralToPointer:
4355 case CK_ToVoid:
4356 case CK_VectorSplat:
4357 case CK_IntegralToFloating:
4358 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004359 case CK_CPointerToObjCPointerCast:
4360 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004361 case CK_AnyPointerToBlockPointerCast:
4362 case CK_ObjCObjectLValueCast:
4363 case CK_FloatingRealToComplex:
4364 case CK_FloatingComplexToReal:
4365 case CK_FloatingComplexCast:
4366 case CK_FloatingComplexToIntegralComplex:
4367 case CK_IntegralRealToComplex:
4368 case CK_IntegralComplexCast:
4369 case CK_IntegralComplexToFloatingComplex:
4370 llvm_unreachable("invalid cast kind for integral value");
4371
Eli Friedman9faf2f92011-03-25 19:07:11 +00004372 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004373 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004374 case CK_LValueBitCast:
4375 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00004376 case CK_ARCProduceObject:
4377 case CK_ARCConsumeObject:
4378 case CK_ARCReclaimReturnedObject:
4379 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004380 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004381
4382 case CK_LValueToRValue:
4383 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004384 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004385
4386 case CK_MemberPointerToBoolean:
4387 case CK_PointerToBoolean:
4388 case CK_IntegralToBoolean:
4389 case CK_FloatingToBoolean:
4390 case CK_FloatingComplexToBoolean:
4391 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004392 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00004393 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004394 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004395 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004396 }
4397
Eli Friedmanc757de22011-03-25 00:43:55 +00004398 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00004399 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00004400 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004401
Eli Friedman742421e2009-02-20 01:15:07 +00004402 if (!Result.isInt()) {
4403 // Only allow casts of lvalues if they are lossless.
4404 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4405 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004406
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004407 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004408 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00004409 }
Mike Stump11289f42009-09-09 15:08:12 +00004410
Eli Friedmanc757de22011-03-25 00:43:55 +00004411 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004412 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4413
John McCall45d55e42010-05-07 21:00:08 +00004414 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00004415 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00004416 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00004417
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004418 if (LV.getLValueBase()) {
4419 // Only allow based lvalue casts if they are lossless.
4420 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004421 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004422
Richard Smithcf74da72011-11-16 07:18:12 +00004423 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004424 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004425 return true;
4426 }
4427
Ken Dyck02990832010-01-15 12:37:54 +00004428 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4429 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004430 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004431 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004432
Eli Friedmanc757de22011-03-25 00:43:55 +00004433 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00004434 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004435 if (!EvaluateComplex(SubExpr, C, Info))
4436 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00004437 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004438 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00004439
Eli Friedmanc757de22011-03-25 00:43:55 +00004440 case CK_FloatingToIntegral: {
4441 APFloat F(0.0);
4442 if (!EvaluateFloat(SubExpr, F, Info))
4443 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00004444
Richard Smith357362d2011-12-13 06:39:58 +00004445 APSInt Value;
4446 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4447 return false;
4448 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004449 }
4450 }
Mike Stump11289f42009-09-09 15:08:12 +00004451
Eli Friedmanc757de22011-03-25 00:43:55 +00004452 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004453 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00004454}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004455
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004456bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4457 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004458 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004459 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4460 return false;
4461 if (!LV.isComplexInt())
4462 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004463 return Success(LV.getComplexIntReal(), E);
4464 }
4465
4466 return Visit(E->getSubExpr());
4467}
4468
Eli Friedman4e7a2412009-02-27 04:45:43 +00004469bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004470 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004471 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004472 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4473 return false;
4474 if (!LV.isComplexInt())
4475 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004476 return Success(LV.getComplexIntImag(), E);
4477 }
4478
Richard Smith4a678122011-10-24 18:44:57 +00004479 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00004480 return Success(0, E);
4481}
4482
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004483bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4484 return Success(E->getPackLength(), E);
4485}
4486
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004487bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4488 return Success(E->getValue(), E);
4489}
4490
Chris Lattner05706e882008-07-11 18:11:29 +00004491//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00004492// Float Evaluation
4493//===----------------------------------------------------------------------===//
4494
4495namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004496class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004497 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00004498 APFloat &Result;
4499public:
4500 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004501 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00004502
Richard Smith0b0a0b62011-10-29 20:57:55 +00004503 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004504 Result = V.getFloat();
4505 return true;
4506 }
Eli Friedman24c01542008-08-22 00:06:13 +00004507
Richard Smith771c4a12011-12-25 20:00:17 +00004508 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004509 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4510 return true;
4511 }
4512
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004513 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004514
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004515 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004516 bool VisitBinaryOperator(const BinaryOperator *E);
4517 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004518 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00004519
John McCallb1fb0d32010-05-07 22:08:54 +00004520 bool VisitUnaryReal(const UnaryOperator *E);
4521 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00004522
Richard Smith771c4a12011-12-25 20:00:17 +00004523 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00004524};
4525} // end anonymous namespace
4526
4527static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004528 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004529 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00004530}
4531
Jay Foad39c79802011-01-12 09:06:06 +00004532static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00004533 QualType ResultTy,
4534 const Expr *Arg,
4535 bool SNaN,
4536 llvm::APFloat &Result) {
4537 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4538 if (!S) return false;
4539
4540 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4541
4542 llvm::APInt fill;
4543
4544 // Treat empty strings as if they were zero.
4545 if (S->getString().empty())
4546 fill = llvm::APInt(32, 0);
4547 else if (S->getString().getAsInteger(0, fill))
4548 return false;
4549
4550 if (SNaN)
4551 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4552 else
4553 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4554 return true;
4555}
4556
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004557bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004558 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004559 default:
4560 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4561
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004562 case Builtin::BI__builtin_huge_val:
4563 case Builtin::BI__builtin_huge_valf:
4564 case Builtin::BI__builtin_huge_vall:
4565 case Builtin::BI__builtin_inf:
4566 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004567 case Builtin::BI__builtin_infl: {
4568 const llvm::fltSemantics &Sem =
4569 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00004570 Result = llvm::APFloat::getInf(Sem);
4571 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004572 }
Mike Stump11289f42009-09-09 15:08:12 +00004573
John McCall16291492010-02-28 13:00:19 +00004574 case Builtin::BI__builtin_nans:
4575 case Builtin::BI__builtin_nansf:
4576 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004577 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4578 true, Result))
4579 return Error(E);
4580 return true;
John McCall16291492010-02-28 13:00:19 +00004581
Chris Lattner0b7282e2008-10-06 06:31:58 +00004582 case Builtin::BI__builtin_nan:
4583 case Builtin::BI__builtin_nanf:
4584 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00004585 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00004586 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004587 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4588 false, Result))
4589 return Error(E);
4590 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004591
4592 case Builtin::BI__builtin_fabs:
4593 case Builtin::BI__builtin_fabsf:
4594 case Builtin::BI__builtin_fabsl:
4595 if (!EvaluateFloat(E->getArg(0), Result, Info))
4596 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004597
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004598 if (Result.isNegative())
4599 Result.changeSign();
4600 return true;
4601
Mike Stump11289f42009-09-09 15:08:12 +00004602 case Builtin::BI__builtin_copysign:
4603 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004604 case Builtin::BI__builtin_copysignl: {
4605 APFloat RHS(0.);
4606 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4607 !EvaluateFloat(E->getArg(1), RHS, Info))
4608 return false;
4609 Result.copySign(RHS);
4610 return true;
4611 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004612 }
4613}
4614
John McCallb1fb0d32010-05-07 22:08:54 +00004615bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004616 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4617 ComplexValue CV;
4618 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4619 return false;
4620 Result = CV.FloatReal;
4621 return true;
4622 }
4623
4624 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004625}
4626
4627bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004628 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4629 ComplexValue CV;
4630 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4631 return false;
4632 Result = CV.FloatImag;
4633 return true;
4634 }
4635
Richard Smith4a678122011-10-24 18:44:57 +00004636 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004637 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4638 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004639 return true;
4640}
4641
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004642bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004643 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004644 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004645 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004646 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004647 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004648 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4649 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004650 Result.changeSign();
4651 return true;
4652 }
4653}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004654
Eli Friedman24c01542008-08-22 00:06:13 +00004655bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004656 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4657 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004658
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004659 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004660 if (!EvaluateFloat(E->getLHS(), Result, Info))
4661 return false;
4662 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4663 return false;
4664
4665 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004666 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004667 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004668 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4669 return true;
John McCalle3027922010-08-25 11:45:40 +00004670 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004671 Result.add(RHS, APFloat::rmNearestTiesToEven);
4672 return true;
John McCalle3027922010-08-25 11:45:40 +00004673 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004674 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4675 return true;
John McCalle3027922010-08-25 11:45:40 +00004676 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004677 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4678 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004679 }
4680}
4681
4682bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4683 Result = E->getValue();
4684 return true;
4685}
4686
Peter Collingbournee9200682011-05-13 03:29:01 +00004687bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4688 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004689
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004690 switch (E->getCastKind()) {
4691 default:
Richard Smith11562c52011-10-28 17:51:58 +00004692 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004693
4694 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004695 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00004696 return EvaluateInteger(SubExpr, IntResult, Info) &&
4697 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4698 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004699 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004700
4701 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004702 if (!Visit(SubExpr))
4703 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004704 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4705 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004706 }
John McCalld7646252010-11-14 08:17:51 +00004707
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004708 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004709 ComplexValue V;
4710 if (!EvaluateComplex(SubExpr, V, Info))
4711 return false;
4712 Result = V.getComplexFloatReal();
4713 return true;
4714 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004715 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004716
Richard Smithf57d8cb2011-12-09 22:58:01 +00004717 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004718}
4719
Eli Friedman24c01542008-08-22 00:06:13 +00004720//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004721// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004722//===----------------------------------------------------------------------===//
4723
4724namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004725class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004726 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004727 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004728
Anders Carlsson537969c2008-11-16 20:27:53 +00004729public:
John McCall93d91dc2010-05-07 17:22:02 +00004730 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004731 : ExprEvaluatorBaseTy(info), Result(Result) {}
4732
Richard Smith0b0a0b62011-10-29 20:57:55 +00004733 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004734 Result.setFrom(V);
4735 return true;
4736 }
Mike Stump11289f42009-09-09 15:08:12 +00004737
Anders Carlsson537969c2008-11-16 20:27:53 +00004738 //===--------------------------------------------------------------------===//
4739 // Visitor Methods
4740 //===--------------------------------------------------------------------===//
4741
Peter Collingbournee9200682011-05-13 03:29:01 +00004742 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00004743
Peter Collingbournee9200682011-05-13 03:29:01 +00004744 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004745
John McCall93d91dc2010-05-07 17:22:02 +00004746 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004747 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004748 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00004749};
4750} // end anonymous namespace
4751
John McCall93d91dc2010-05-07 17:22:02 +00004752static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4753 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004754 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004755 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004756}
4757
Peter Collingbournee9200682011-05-13 03:29:01 +00004758bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4759 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004760
4761 if (SubExpr->getType()->isRealFloatingType()) {
4762 Result.makeComplexFloat();
4763 APFloat &Imag = Result.FloatImag;
4764 if (!EvaluateFloat(SubExpr, Imag, Info))
4765 return false;
4766
4767 Result.FloatReal = APFloat(Imag.getSemantics());
4768 return true;
4769 } else {
4770 assert(SubExpr->getType()->isIntegerType() &&
4771 "Unexpected imaginary literal.");
4772
4773 Result.makeComplexInt();
4774 APSInt &Imag = Result.IntImag;
4775 if (!EvaluateInteger(SubExpr, Imag, Info))
4776 return false;
4777
4778 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4779 return true;
4780 }
4781}
4782
Peter Collingbournee9200682011-05-13 03:29:01 +00004783bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004784
John McCallfcef3cf2010-12-14 17:51:41 +00004785 switch (E->getCastKind()) {
4786 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004787 case CK_BaseToDerived:
4788 case CK_DerivedToBase:
4789 case CK_UncheckedDerivedToBase:
4790 case CK_Dynamic:
4791 case CK_ToUnion:
4792 case CK_ArrayToPointerDecay:
4793 case CK_FunctionToPointerDecay:
4794 case CK_NullToPointer:
4795 case CK_NullToMemberPointer:
4796 case CK_BaseToDerivedMemberPointer:
4797 case CK_DerivedToBaseMemberPointer:
4798 case CK_MemberPointerToBoolean:
4799 case CK_ConstructorConversion:
4800 case CK_IntegralToPointer:
4801 case CK_PointerToIntegral:
4802 case CK_PointerToBoolean:
4803 case CK_ToVoid:
4804 case CK_VectorSplat:
4805 case CK_IntegralCast:
4806 case CK_IntegralToBoolean:
4807 case CK_IntegralToFloating:
4808 case CK_FloatingToIntegral:
4809 case CK_FloatingToBoolean:
4810 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004811 case CK_CPointerToObjCPointerCast:
4812 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004813 case CK_AnyPointerToBlockPointerCast:
4814 case CK_ObjCObjectLValueCast:
4815 case CK_FloatingComplexToReal:
4816 case CK_FloatingComplexToBoolean:
4817 case CK_IntegralComplexToReal:
4818 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004819 case CK_ARCProduceObject:
4820 case CK_ARCConsumeObject:
4821 case CK_ARCReclaimReturnedObject:
4822 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004823 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004824
John McCallfcef3cf2010-12-14 17:51:41 +00004825 case CK_LValueToRValue:
4826 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004827 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004828
4829 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004830 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004831 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004832 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004833
4834 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004835 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004836 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004837 return false;
4838
John McCallfcef3cf2010-12-14 17:51:41 +00004839 Result.makeComplexFloat();
4840 Result.FloatImag = APFloat(Real.getSemantics());
4841 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004842 }
4843
John McCallfcef3cf2010-12-14 17:51:41 +00004844 case CK_FloatingComplexCast: {
4845 if (!Visit(E->getSubExpr()))
4846 return false;
4847
4848 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4849 QualType From
4850 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4851
Richard Smith357362d2011-12-13 06:39:58 +00004852 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4853 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004854 }
4855
4856 case CK_FloatingComplexToIntegralComplex: {
4857 if (!Visit(E->getSubExpr()))
4858 return false;
4859
4860 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4861 QualType From
4862 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4863 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00004864 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4865 To, Result.IntReal) &&
4866 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4867 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004868 }
4869
4870 case CK_IntegralRealToComplex: {
4871 APSInt &Real = Result.IntReal;
4872 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4873 return false;
4874
4875 Result.makeComplexInt();
4876 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4877 return true;
4878 }
4879
4880 case CK_IntegralComplexCast: {
4881 if (!Visit(E->getSubExpr()))
4882 return false;
4883
4884 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4885 QualType From
4886 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4887
4888 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4889 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4890 return true;
4891 }
4892
4893 case CK_IntegralComplexToFloatingComplex: {
4894 if (!Visit(E->getSubExpr()))
4895 return false;
4896
4897 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4898 QualType From
4899 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4900 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00004901 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4902 To, Result.FloatReal) &&
4903 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4904 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004905 }
4906 }
4907
4908 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004909 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004910}
4911
John McCall93d91dc2010-05-07 17:22:02 +00004912bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004913 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00004914 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4915
John McCall93d91dc2010-05-07 17:22:02 +00004916 if (!Visit(E->getLHS()))
4917 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004918
John McCall93d91dc2010-05-07 17:22:02 +00004919 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004920 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00004921 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004922
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004923 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4924 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004925 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004926 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004927 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004928 if (Result.isComplexFloat()) {
4929 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4930 APFloat::rmNearestTiesToEven);
4931 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4932 APFloat::rmNearestTiesToEven);
4933 } else {
4934 Result.getComplexIntReal() += RHS.getComplexIntReal();
4935 Result.getComplexIntImag() += RHS.getComplexIntImag();
4936 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004937 break;
John McCalle3027922010-08-25 11:45:40 +00004938 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004939 if (Result.isComplexFloat()) {
4940 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4941 APFloat::rmNearestTiesToEven);
4942 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4943 APFloat::rmNearestTiesToEven);
4944 } else {
4945 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4946 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4947 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004948 break;
John McCalle3027922010-08-25 11:45:40 +00004949 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004950 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00004951 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004952 APFloat &LHS_r = LHS.getComplexFloatReal();
4953 APFloat &LHS_i = LHS.getComplexFloatImag();
4954 APFloat &RHS_r = RHS.getComplexFloatReal();
4955 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00004956
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004957 APFloat Tmp = LHS_r;
4958 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4959 Result.getComplexFloatReal() = Tmp;
4960 Tmp = LHS_i;
4961 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4962 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4963
4964 Tmp = LHS_r;
4965 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4966 Result.getComplexFloatImag() = Tmp;
4967 Tmp = LHS_i;
4968 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4969 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4970 } else {
John McCall93d91dc2010-05-07 17:22:02 +00004971 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00004972 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004973 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4974 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00004975 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004976 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4977 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4978 }
4979 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004980 case BO_Div:
4981 if (Result.isComplexFloat()) {
4982 ComplexValue LHS = Result;
4983 APFloat &LHS_r = LHS.getComplexFloatReal();
4984 APFloat &LHS_i = LHS.getComplexFloatImag();
4985 APFloat &RHS_r = RHS.getComplexFloatReal();
4986 APFloat &RHS_i = RHS.getComplexFloatImag();
4987 APFloat &Res_r = Result.getComplexFloatReal();
4988 APFloat &Res_i = Result.getComplexFloatImag();
4989
4990 APFloat Den = RHS_r;
4991 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4992 APFloat Tmp = RHS_i;
4993 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4994 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4995
4996 Res_r = LHS_r;
4997 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4998 Tmp = LHS_i;
4999 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5000 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5001 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5002
5003 Res_i = LHS_i;
5004 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5005 Tmp = LHS_r;
5006 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5007 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5008 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5009 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005010 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5011 return Error(E, diag::note_expr_divide_by_zero);
5012
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005013 ComplexValue LHS = Result;
5014 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5015 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5016 Result.getComplexIntReal() =
5017 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5018 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5019 Result.getComplexIntImag() =
5020 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5021 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5022 }
5023 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005024 }
5025
John McCall93d91dc2010-05-07 17:22:02 +00005026 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005027}
5028
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005029bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5030 // Get the operand value into 'Result'.
5031 if (!Visit(E->getSubExpr()))
5032 return false;
5033
5034 switch (E->getOpcode()) {
5035 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005036 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005037 case UO_Extension:
5038 return true;
5039 case UO_Plus:
5040 // The result is always just the subexpr.
5041 return true;
5042 case UO_Minus:
5043 if (Result.isComplexFloat()) {
5044 Result.getComplexFloatReal().changeSign();
5045 Result.getComplexFloatImag().changeSign();
5046 }
5047 else {
5048 Result.getComplexIntReal() = -Result.getComplexIntReal();
5049 Result.getComplexIntImag() = -Result.getComplexIntImag();
5050 }
5051 return true;
5052 case UO_Not:
5053 if (Result.isComplexFloat())
5054 Result.getComplexFloatImag().changeSign();
5055 else
5056 Result.getComplexIntImag() = -Result.getComplexIntImag();
5057 return true;
5058 }
5059}
5060
Anders Carlsson537969c2008-11-16 20:27:53 +00005061//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00005062// Void expression evaluation, primarily for a cast to void on the LHS of a
5063// comma operator
5064//===----------------------------------------------------------------------===//
5065
5066namespace {
5067class VoidExprEvaluator
5068 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5069public:
5070 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5071
5072 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00005073
5074 bool VisitCastExpr(const CastExpr *E) {
5075 switch (E->getCastKind()) {
5076 default:
5077 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5078 case CK_ToVoid:
5079 VisitIgnoredValue(E->getSubExpr());
5080 return true;
5081 }
5082 }
5083};
5084} // end anonymous namespace
5085
5086static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5087 assert(E->isRValue() && E->getType()->isVoidType());
5088 return VoidExprEvaluator(Info).Visit(E);
5089}
5090
5091//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00005092// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00005093//===----------------------------------------------------------------------===//
5094
Richard Smith0b0a0b62011-10-29 20:57:55 +00005095static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005096 // In C, function designators are not lvalues, but we evaluate them as if they
5097 // are.
5098 if (E->isGLValue() || E->getType()->isFunctionType()) {
5099 LValue LV;
5100 if (!EvaluateLValue(E, LV, Info))
5101 return false;
5102 LV.moveInto(Result);
5103 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005104 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005105 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005106 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005107 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005108 return false;
John McCall45d55e42010-05-07 21:00:08 +00005109 } else if (E->getType()->hasPointerRepresentation()) {
5110 LValue LV;
5111 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005112 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005113 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00005114 } else if (E->getType()->isRealFloatingType()) {
5115 llvm::APFloat F(0.0);
5116 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005117 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005118 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00005119 } else if (E->getType()->isAnyComplexType()) {
5120 ComplexValue C;
5121 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005122 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005123 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00005124 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00005125 MemberPtr P;
5126 if (!EvaluateMemberPointer(E, P, Info))
5127 return false;
5128 P.moveInto(Result);
5129 return true;
Richard Smith771c4a12011-12-25 20:00:17 +00005130 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005131 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005132 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005133 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00005134 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005135 Result = Info.CurrentCall->Temporaries[E];
Richard Smith771c4a12011-12-25 20:00:17 +00005136 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005137 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005138 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005139 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5140 return false;
5141 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00005142 } else if (E->getType()->isVoidType()) {
Richard Smith357362d2011-12-13 06:39:58 +00005143 if (Info.getLangOpts().CPlusPlus0x)
5144 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5145 << E->getType();
5146 else
5147 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith42d3af92011-12-07 00:43:50 +00005148 if (!EvaluateVoid(E, Info))
5149 return false;
Richard Smith357362d2011-12-13 06:39:58 +00005150 } else if (Info.getLangOpts().CPlusPlus0x) {
5151 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5152 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005153 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00005154 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00005155 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005156 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005157
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00005158 return true;
5159}
5160
Richard Smithed5165f2011-11-04 05:33:44 +00005161/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5162/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5163/// since later initializers for an object can indirectly refer to subobjects
5164/// which were initialized earlier.
5165static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +00005166 const LValue &This, const Expr *E,
5167 CheckConstantExpressionKind CCEK) {
Richard Smith771c4a12011-12-25 20:00:17 +00005168 if (!CheckLiteralType(Info, E))
5169 return false;
5170
5171 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00005172 // Evaluate arrays and record types in-place, so that later initializers can
5173 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00005174 if (E->getType()->isArrayType())
5175 return EvaluateArray(E, This, Result, Info);
5176 else if (E->getType()->isRecordType())
5177 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00005178 }
5179
5180 // For any other type, in-place evaluation is unimportant.
5181 CCValue CoreConstResult;
5182 return Evaluate(CoreConstResult, Info, E) &&
Richard Smith357362d2011-12-13 06:39:58 +00005183 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smithed5165f2011-11-04 05:33:44 +00005184}
5185
Richard Smithf57d8cb2011-12-09 22:58:01 +00005186/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5187/// lvalue-to-rvalue cast if it is an lvalue.
5188static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith771c4a12011-12-25 20:00:17 +00005189 if (!CheckLiteralType(Info, E))
5190 return false;
5191
Richard Smithf57d8cb2011-12-09 22:58:01 +00005192 CCValue Value;
5193 if (!::Evaluate(Value, Info, E))
5194 return false;
5195
5196 if (E->isGLValue()) {
5197 LValue LV;
5198 LV.setFrom(Value);
5199 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5200 return false;
5201 }
5202
5203 // Check this core constant expression is a constant expression, and if so,
5204 // convert it to one.
5205 return CheckConstantExpression(Info, E, Value, Result);
5206}
Richard Smith11562c52011-10-28 17:51:58 +00005207
Richard Smith7b553f12011-10-29 00:50:52 +00005208/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00005209/// any crazy technique (that has nothing to do with language standards) that
5210/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00005211/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5212/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00005213bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00005214 // Fast-path evaluations of integer literals, since we sometimes see files
5215 // containing vast quantities of these.
5216 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5217 Result.Val = APValue(APSInt(L->getValue(),
5218 L->getType()->isUnsignedIntegerType()));
5219 return true;
5220 }
5221
Richard Smith5686e752011-11-10 03:30:42 +00005222 // FIXME: Evaluating initializers for large arrays can cause performance
5223 // problems, and we don't use such values yet. Once we have a more efficient
5224 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00005225 // The same problem affects large records.
5226 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5227 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00005228 return false;
5229
Richard Smithd62306a2011-11-10 06:34:14 +00005230 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005231 EvalInfo Info(Ctx, Result);
5232 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00005233}
5234
Jay Foad39c79802011-01-12 09:06:06 +00005235bool Expr::EvaluateAsBooleanCondition(bool &Result,
5236 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00005237 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00005238 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00005239 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00005240 Result);
John McCall1be1c632010-01-05 23:42:56 +00005241}
5242
Richard Smithcaf33902011-10-10 18:28:20 +00005243bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00005244 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005245 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00005246 !ExprResult.Val.isInt())
Richard Smith11562c52011-10-28 17:51:58 +00005247 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005248
Richard Smith11562c52011-10-28 17:51:58 +00005249 Result = ExprResult.Val.getInt();
5250 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00005251}
5252
Jay Foad39c79802011-01-12 09:06:06 +00005253bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00005254 EvalInfo Info(Ctx, Result);
5255
John McCall45d55e42010-05-07 21:00:08 +00005256 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00005257 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smith357362d2011-12-13 06:39:58 +00005258 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5259 CCEK_Constant);
Eli Friedman7d45c482009-09-13 10:17:44 +00005260}
5261
Richard Smithd0b4dd62011-12-19 06:19:21 +00005262bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5263 const VarDecl *VD,
5264 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
5265 Expr::EvalStatus EStatus;
5266 EStatus.Diag = &Notes;
5267
5268 EvalInfo InitInfo(Ctx, EStatus);
5269 InitInfo.setEvaluatingDecl(VD, Value);
5270
Richard Smith771c4a12011-12-25 20:00:17 +00005271 if (!CheckLiteralType(InitInfo, this))
5272 return false;
5273
Richard Smithd0b4dd62011-12-19 06:19:21 +00005274 LValue LVal;
5275 LVal.set(VD);
5276
Richard Smith771c4a12011-12-25 20:00:17 +00005277 // C++11 [basic.start.init]p2:
5278 // Variables with static storage duration or thread storage duration shall be
5279 // zero-initialized before any other initialization takes place.
5280 // This behavior is not present in C.
5281 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5282 !VD->getType()->isReferenceType()) {
5283 ImplicitValueInitExpr VIE(VD->getType());
5284 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5285 return false;
5286 }
5287
Richard Smithd0b4dd62011-12-19 06:19:21 +00005288 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5289 !EStatus.HasSideEffects;
5290}
5291
Richard Smith7b553f12011-10-29 00:50:52 +00005292/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5293/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00005294bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00005295 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00005296 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00005297}
Anders Carlsson59689ed2008-11-22 21:04:56 +00005298
Jay Foad39c79802011-01-12 09:06:06 +00005299bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00005300 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005301}
5302
Richard Smithcaf33902011-10-10 18:28:20 +00005303APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005304 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005305 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00005306 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00005307 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005308 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00005309
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005310 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00005311}
John McCall864e3962010-05-07 05:32:02 +00005312
Abramo Bagnaraf8199452010-05-14 17:07:14 +00005313 bool Expr::EvalResult::isGlobalLValue() const {
5314 assert(Val.isLValue());
5315 return IsGlobalLValue(Val.getLValueBase());
5316 }
5317
5318
John McCall864e3962010-05-07 05:32:02 +00005319/// isIntegerConstantExpr - this recursive routine will test if an expression is
5320/// an integer constant expression.
5321
5322/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5323/// comma, etc
5324///
5325/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5326/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5327/// cast+dereference.
5328
5329// CheckICE - This function does the fundamental ICE checking: the returned
5330// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5331// Note that to reduce code duplication, this helper does no evaluation
5332// itself; the caller checks whether the expression is evaluatable, and
5333// in the rare cases where CheckICE actually cares about the evaluated
5334// value, it calls into Evalute.
5335//
5336// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00005337// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00005338// 1: This expression is not an ICE, but if it isn't evaluated, it's
5339// a legal subexpression for an ICE. This return value is used to handle
5340// the comma operator in C99 mode.
5341// 2: This expression is not an ICE, and is not a legal subexpression for one.
5342
Dan Gohman28ade552010-07-26 21:25:24 +00005343namespace {
5344
John McCall864e3962010-05-07 05:32:02 +00005345struct ICEDiag {
5346 unsigned Val;
5347 SourceLocation Loc;
5348
5349 public:
5350 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5351 ICEDiag() : Val(0) {}
5352};
5353
Dan Gohman28ade552010-07-26 21:25:24 +00005354}
5355
5356static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00005357
5358static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5359 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005360 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005361 !EVResult.Val.isInt()) {
5362 return ICEDiag(2, E->getLocStart());
5363 }
5364 return NoDiag();
5365}
5366
5367static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5368 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00005369 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00005370 return ICEDiag(2, E->getLocStart());
5371 }
5372
5373 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00005374#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00005375#define STMT(Node, Base) case Expr::Node##Class:
5376#define EXPR(Node, Base)
5377#include "clang/AST/StmtNodes.inc"
5378 case Expr::PredefinedExprClass:
5379 case Expr::FloatingLiteralClass:
5380 case Expr::ImaginaryLiteralClass:
5381 case Expr::StringLiteralClass:
5382 case Expr::ArraySubscriptExprClass:
5383 case Expr::MemberExprClass:
5384 case Expr::CompoundAssignOperatorClass:
5385 case Expr::CompoundLiteralExprClass:
5386 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00005387 case Expr::DesignatedInitExprClass:
5388 case Expr::ImplicitValueInitExprClass:
5389 case Expr::ParenListExprClass:
5390 case Expr::VAArgExprClass:
5391 case Expr::AddrLabelExprClass:
5392 case Expr::StmtExprClass:
5393 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00005394 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00005395 case Expr::CXXDynamicCastExprClass:
5396 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00005397 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00005398 case Expr::CXXNullPtrLiteralExprClass:
5399 case Expr::CXXThisExprClass:
5400 case Expr::CXXThrowExprClass:
5401 case Expr::CXXNewExprClass:
5402 case Expr::CXXDeleteExprClass:
5403 case Expr::CXXPseudoDestructorExprClass:
5404 case Expr::UnresolvedLookupExprClass:
5405 case Expr::DependentScopeDeclRefExprClass:
5406 case Expr::CXXConstructExprClass:
5407 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00005408 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00005409 case Expr::CXXTemporaryObjectExprClass:
5410 case Expr::CXXUnresolvedConstructExprClass:
5411 case Expr::CXXDependentScopeMemberExprClass:
5412 case Expr::UnresolvedMemberExprClass:
5413 case Expr::ObjCStringLiteralClass:
5414 case Expr::ObjCEncodeExprClass:
5415 case Expr::ObjCMessageExprClass:
5416 case Expr::ObjCSelectorExprClass:
5417 case Expr::ObjCProtocolExprClass:
5418 case Expr::ObjCIvarRefExprClass:
5419 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00005420 case Expr::ObjCIsaExprClass:
5421 case Expr::ShuffleVectorExprClass:
5422 case Expr::BlockExprClass:
5423 case Expr::BlockDeclRefExprClass:
5424 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00005425 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005426 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00005427 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00005428 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00005429 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00005430 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00005431 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00005432 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005433 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005434 return ICEDiag(2, E->getLocStart());
5435
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005436 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00005437 case Expr::GNUNullExprClass:
5438 // GCC considers the GNU __null value to be an integral constant expression.
5439 return NoDiag();
5440
John McCall7c454bb2011-07-15 05:09:51 +00005441 case Expr::SubstNonTypeTemplateParmExprClass:
5442 return
5443 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5444
John McCall864e3962010-05-07 05:32:02 +00005445 case Expr::ParenExprClass:
5446 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00005447 case Expr::GenericSelectionExprClass:
5448 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005449 case Expr::IntegerLiteralClass:
5450 case Expr::CharacterLiteralClass:
5451 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00005452 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00005453 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005454 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00005455 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00005456 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005457 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00005458 return NoDiag();
5459 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00005460 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00005461 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5462 // constant expressions, but they can never be ICEs because an ICE cannot
5463 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00005464 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005465 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00005466 return CheckEvalInICE(E, Ctx);
5467 return ICEDiag(2, E->getLocStart());
5468 }
5469 case Expr::DeclRefExprClass:
5470 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5471 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00005472 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00005473 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5474
5475 // Parameter variables are never constants. Without this check,
5476 // getAnyInitializer() can find a default argument, which leads
5477 // to chaos.
5478 if (isa<ParmVarDecl>(D))
5479 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5480
5481 // C++ 7.1.5.1p2
5482 // A variable of non-volatile const-qualified integral or enumeration
5483 // type initialized by an ICE can be used in ICEs.
5484 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00005485 if (!Dcl->getType()->isIntegralOrEnumerationType())
5486 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5487
Richard Smithd0b4dd62011-12-19 06:19:21 +00005488 const VarDecl *VD;
5489 // Look for a declaration of this variable that has an initializer, and
5490 // check whether it is an ICE.
5491 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5492 return NoDiag();
5493 else
5494 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00005495 }
5496 }
5497 return ICEDiag(2, E->getLocStart());
5498 case Expr::UnaryOperatorClass: {
5499 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5500 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005501 case UO_PostInc:
5502 case UO_PostDec:
5503 case UO_PreInc:
5504 case UO_PreDec:
5505 case UO_AddrOf:
5506 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00005507 // C99 6.6/3 allows increment and decrement within unevaluated
5508 // subexpressions of constant expressions, but they can never be ICEs
5509 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005510 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00005511 case UO_Extension:
5512 case UO_LNot:
5513 case UO_Plus:
5514 case UO_Minus:
5515 case UO_Not:
5516 case UO_Real:
5517 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00005518 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005519 }
5520
5521 // OffsetOf falls through here.
5522 }
5523 case Expr::OffsetOfExprClass: {
5524 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00005525 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00005526 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00005527 // compliance: we should warn earlier for offsetof expressions with
5528 // array subscripts that aren't ICEs, and if the array subscripts
5529 // are ICEs, the value of the offsetof must be an integer constant.
5530 return CheckEvalInICE(E, Ctx);
5531 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00005532 case Expr::UnaryExprOrTypeTraitExprClass: {
5533 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5534 if ((Exp->getKind() == UETT_SizeOf) &&
5535 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00005536 return ICEDiag(2, E->getLocStart());
5537 return NoDiag();
5538 }
5539 case Expr::BinaryOperatorClass: {
5540 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5541 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005542 case BO_PtrMemD:
5543 case BO_PtrMemI:
5544 case BO_Assign:
5545 case BO_MulAssign:
5546 case BO_DivAssign:
5547 case BO_RemAssign:
5548 case BO_AddAssign:
5549 case BO_SubAssign:
5550 case BO_ShlAssign:
5551 case BO_ShrAssign:
5552 case BO_AndAssign:
5553 case BO_XorAssign:
5554 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00005555 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5556 // constant expressions, but they can never be ICEs because an ICE cannot
5557 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005558 return ICEDiag(2, E->getLocStart());
5559
John McCalle3027922010-08-25 11:45:40 +00005560 case BO_Mul:
5561 case BO_Div:
5562 case BO_Rem:
5563 case BO_Add:
5564 case BO_Sub:
5565 case BO_Shl:
5566 case BO_Shr:
5567 case BO_LT:
5568 case BO_GT:
5569 case BO_LE:
5570 case BO_GE:
5571 case BO_EQ:
5572 case BO_NE:
5573 case BO_And:
5574 case BO_Xor:
5575 case BO_Or:
5576 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00005577 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5578 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00005579 if (Exp->getOpcode() == BO_Div ||
5580 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00005581 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00005582 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00005583 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00005584 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005585 if (REval == 0)
5586 return ICEDiag(1, E->getLocStart());
5587 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00005588 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005589 if (LEval.isMinSignedValue())
5590 return ICEDiag(1, E->getLocStart());
5591 }
5592 }
5593 }
John McCalle3027922010-08-25 11:45:40 +00005594 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00005595 if (Ctx.getLangOptions().C99) {
5596 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5597 // if it isn't evaluated.
5598 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5599 return ICEDiag(1, E->getLocStart());
5600 } else {
5601 // In both C89 and C++, commas in ICEs are illegal.
5602 return ICEDiag(2, E->getLocStart());
5603 }
5604 }
5605 if (LHSResult.Val >= RHSResult.Val)
5606 return LHSResult;
5607 return RHSResult;
5608 }
John McCalle3027922010-08-25 11:45:40 +00005609 case BO_LAnd:
5610 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00005611 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5612 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5613 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5614 // Rare case where the RHS has a comma "side-effect"; we need
5615 // to actually check the condition to see whether the side
5616 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00005617 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00005618 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00005619 return RHSResult;
5620 return NoDiag();
5621 }
5622
5623 if (LHSResult.Val >= RHSResult.Val)
5624 return LHSResult;
5625 return RHSResult;
5626 }
5627 }
5628 }
5629 case Expr::ImplicitCastExprClass:
5630 case Expr::CStyleCastExprClass:
5631 case Expr::CXXFunctionalCastExprClass:
5632 case Expr::CXXStaticCastExprClass:
5633 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005634 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005635 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005636 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00005637 if (isa<ExplicitCastExpr>(E)) {
5638 if (const FloatingLiteral *FL
5639 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5640 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5641 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5642 APSInt IgnoredVal(DestWidth, !DestSigned);
5643 bool Ignored;
5644 // If the value does not fit in the destination type, the behavior is
5645 // undefined, so we are not required to treat it as a constant
5646 // expression.
5647 if (FL->getValue().convertToInteger(IgnoredVal,
5648 llvm::APFloat::rmTowardZero,
5649 &Ignored) & APFloat::opInvalidOp)
5650 return ICEDiag(2, E->getLocStart());
5651 return NoDiag();
5652 }
5653 }
Eli Friedman76d4e432011-09-29 21:49:34 +00005654 switch (cast<CastExpr>(E)->getCastKind()) {
5655 case CK_LValueToRValue:
5656 case CK_NoOp:
5657 case CK_IntegralToBoolean:
5658 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005659 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005660 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005661 return ICEDiag(2, E->getLocStart());
5662 }
John McCall864e3962010-05-07 05:32:02 +00005663 }
John McCallc07a0c72011-02-17 10:25:35 +00005664 case Expr::BinaryConditionalOperatorClass: {
5665 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5666 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5667 if (CommonResult.Val == 2) return CommonResult;
5668 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5669 if (FalseResult.Val == 2) return FalseResult;
5670 if (CommonResult.Val == 1) return CommonResult;
5671 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005672 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005673 return FalseResult;
5674 }
John McCall864e3962010-05-07 05:32:02 +00005675 case Expr::ConditionalOperatorClass: {
5676 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5677 // If the condition (ignoring parens) is a __builtin_constant_p call,
5678 // then only the true side is actually considered in an integer constant
5679 // expression, and it is fully evaluated. This is an important GNU
5680 // extension. See GCC PR38377 for discussion.
5681 if (const CallExpr *CallCE
5682 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smithd62306a2011-11-10 06:34:14 +00005683 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCall864e3962010-05-07 05:32:02 +00005684 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005685 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005686 !EVResult.Val.isInt()) {
5687 return ICEDiag(2, E->getLocStart());
5688 }
5689 return NoDiag();
5690 }
5691 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005692 if (CondResult.Val == 2)
5693 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005694
Richard Smithf57d8cb2011-12-09 22:58:01 +00005695 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5696 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005697
John McCall864e3962010-05-07 05:32:02 +00005698 if (TrueResult.Val == 2)
5699 return TrueResult;
5700 if (FalseResult.Val == 2)
5701 return FalseResult;
5702 if (CondResult.Val == 1)
5703 return CondResult;
5704 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5705 return NoDiag();
5706 // Rare case where the diagnostics depend on which side is evaluated
5707 // Note that if we get here, CondResult is 0, and at least one of
5708 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005709 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005710 return FalseResult;
5711 }
5712 return TrueResult;
5713 }
5714 case Expr::CXXDefaultArgExprClass:
5715 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5716 case Expr::ChooseExprClass: {
5717 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5718 }
5719 }
5720
5721 // Silence a GCC warning
5722 return ICEDiag(2, E->getLocStart());
5723}
5724
Richard Smithf57d8cb2011-12-09 22:58:01 +00005725/// Evaluate an expression as a C++11 integral constant expression.
5726static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5727 const Expr *E,
5728 llvm::APSInt *Value,
5729 SourceLocation *Loc) {
5730 if (!E->getType()->isIntegralOrEnumerationType()) {
5731 if (Loc) *Loc = E->getExprLoc();
5732 return false;
5733 }
5734
5735 Expr::EvalResult Result;
Richard Smith92b1ce02011-12-12 09:28:41 +00005736 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5737 Result.Diag = &Diags;
5738 EvalInfo Info(Ctx, Result);
5739
5740 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5741 if (!Diags.empty()) {
5742 IsICE = false;
5743 if (Loc) *Loc = Diags[0].first;
5744 } else if (!IsICE && Loc) {
5745 *Loc = E->getExprLoc();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005746 }
Richard Smith92b1ce02011-12-12 09:28:41 +00005747
5748 if (!IsICE)
5749 return false;
5750
5751 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5752 if (Value) *Value = Result.Val.getInt();
5753 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005754}
5755
Richard Smith92b1ce02011-12-12 09:28:41 +00005756bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005757 if (Ctx.getLangOptions().CPlusPlus0x)
5758 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5759
John McCall864e3962010-05-07 05:32:02 +00005760 ICEDiag d = CheckICE(this, Ctx);
5761 if (d.Val != 0) {
5762 if (Loc) *Loc = d.Loc;
5763 return false;
5764 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005765 return true;
5766}
5767
5768bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5769 SourceLocation *Loc, bool isEvaluated) const {
5770 if (Ctx.getLangOptions().CPlusPlus0x)
5771 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5772
5773 if (!isIntegerConstantExpr(Ctx, Loc))
5774 return false;
5775 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005776 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005777 return true;
5778}