blob: ba5b1f4bb6863b6a1b5641124dae04f1e1454538 [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 Smith0b0a0b62011-10-29 20:57:55 +0000770/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000771/// constant expression, and if it is, produce the corresponding constant value.
Rafael Espindolafafe4b72011-12-30 03:11:50 +0000772/// If not, report an appropriate diagnostic.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000773static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +0000774 const CCValue &CCValue, APValue &Value,
775 CheckConstantExpressionKind CCEK
776 = CCEK_Constant) {
Richard Smith80815602011-11-07 05:07:52 +0000777 if (!CCValue.isLValue()) {
778 Value = CCValue;
779 return true;
780 }
Richard Smith357362d2011-12-13 06:39:58 +0000781 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000782}
783
Richard Smith83c68212011-10-31 05:11:32 +0000784const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000785 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000786}
787
788static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000789 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000790}
791
Richard Smithcecf1842011-11-01 21:06:14 +0000792static bool IsWeakLValue(const LValue &Value) {
793 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000794 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000795}
796
Richard Smith027bf112011-11-17 22:56:20 +0000797static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000798 // A null base expression indicates a null pointer. These are always
799 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000800 if (!Value.getLValueBase()) {
801 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000802 return true;
803 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000804
John McCall95007602010-05-10 23:27:23 +0000805 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000806 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000807 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000808
Richard Smith027bf112011-11-17 22:56:20 +0000809 // We have a non-null base. These are generally known to be true, but if it's
810 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000811 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000812 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000813 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000814}
815
Richard Smith0b0a0b62011-10-29 20:57:55 +0000816static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000817 switch (Val.getKind()) {
818 case APValue::Uninitialized:
819 return false;
820 case APValue::Int:
821 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000822 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000823 case APValue::Float:
824 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000825 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000826 case APValue::ComplexInt:
827 Result = Val.getComplexIntReal().getBoolValue() ||
828 Val.getComplexIntImag().getBoolValue();
829 return true;
830 case APValue::ComplexFloat:
831 Result = !Val.getComplexFloatReal().isZero() ||
832 !Val.getComplexFloatImag().isZero();
833 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000834 case APValue::LValue:
835 return EvalPointerValueAsBool(Val, Result);
836 case APValue::MemberPointer:
837 Result = Val.getMemberPointerDecl();
838 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000839 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000840 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000841 case APValue::Struct:
842 case APValue::Union:
Richard Smith11562c52011-10-28 17:51:58 +0000843 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000844 }
845
Richard Smith11562c52011-10-28 17:51:58 +0000846 llvm_unreachable("unknown APValue kind");
847}
848
849static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
850 EvalInfo &Info) {
851 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000852 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000853 if (!Evaluate(Val, Info, E))
854 return false;
855 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000856}
857
Richard Smith357362d2011-12-13 06:39:58 +0000858template<typename T>
859static bool HandleOverflow(EvalInfo &Info, const Expr *E,
860 const T &SrcValue, QualType DestType) {
861 llvm::SmallVector<char, 32> Buffer;
862 SrcValue.toString(Buffer);
863 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
864 << StringRef(Buffer.data(), Buffer.size()) << DestType;
865 return false;
866}
867
868static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
869 QualType SrcType, const APFloat &Value,
870 QualType DestType, APSInt &Result) {
871 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000872 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000873 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000874
Richard Smith357362d2011-12-13 06:39:58 +0000875 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000876 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000877 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
878 & APFloat::opInvalidOp)
879 return HandleOverflow(Info, E, Value, DestType);
880 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000881}
882
Richard Smith357362d2011-12-13 06:39:58 +0000883static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
884 QualType SrcType, QualType DestType,
885 APFloat &Result) {
886 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000887 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +0000888 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
889 APFloat::rmNearestTiesToEven, &ignored)
890 & APFloat::opOverflow)
891 return HandleOverflow(Info, E, Value, DestType);
892 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000893}
894
Mike Stump11289f42009-09-09 15:08:12 +0000895static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000896 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000897 unsigned DestWidth = Ctx.getIntWidth(DestType);
898 APSInt Result = Value;
899 // Figure out if this is a truncate, extend or noop cast.
900 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000901 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000902 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000903 return Result;
904}
905
Richard Smith357362d2011-12-13 06:39:58 +0000906static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
907 QualType SrcType, const APSInt &Value,
908 QualType DestType, APFloat &Result) {
909 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
910 if (Result.convertFromAPInt(Value, Value.isSigned(),
911 APFloat::rmNearestTiesToEven)
912 & APFloat::opOverflow)
913 return HandleOverflow(Info, E, Value, DestType);
914 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000915}
916
Eli Friedman803acb32011-12-22 03:51:45 +0000917static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
918 llvm::APInt &Res) {
919 CCValue SVal;
920 if (!Evaluate(SVal, Info, E))
921 return false;
922 if (SVal.isInt()) {
923 Res = SVal.getInt();
924 return true;
925 }
926 if (SVal.isFloat()) {
927 Res = SVal.getFloat().bitcastToAPInt();
928 return true;
929 }
930 if (SVal.isVector()) {
931 QualType VecTy = E->getType();
932 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
933 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
934 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
935 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
936 Res = llvm::APInt::getNullValue(VecSize);
937 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
938 APValue &Elt = SVal.getVectorElt(i);
939 llvm::APInt EltAsInt;
940 if (Elt.isInt()) {
941 EltAsInt = Elt.getInt();
942 } else if (Elt.isFloat()) {
943 EltAsInt = Elt.getFloat().bitcastToAPInt();
944 } else {
945 // Don't try to handle vectors of anything other than int or float
946 // (not sure if it's possible to hit this case).
947 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
948 return false;
949 }
950 unsigned BaseEltSize = EltAsInt.getBitWidth();
951 if (BigEndian)
952 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
953 else
954 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
955 }
956 return true;
957 }
958 // Give up if the input isn't an int, float, or vector. For example, we
959 // reject "(v4i16)(intptr_t)&a".
960 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
961 return false;
962}
963
Richard Smith027bf112011-11-17 22:56:20 +0000964static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
965 const CXXRecordDecl *&MostDerivedType,
966 unsigned &MostDerivedPathLength,
967 bool &MostDerivedIsArrayElement) {
968 const SubobjectDesignator &D = LVal.Designator;
969 if (D.Invalid || !LVal.Base)
Richard Smithd62306a2011-11-10 06:34:14 +0000970 return false;
971
Richard Smith027bf112011-11-17 22:56:20 +0000972 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smithd62306a2011-11-10 06:34:14 +0000973
974 // Find path prefix which leads to the most-derived subobject.
Richard Smithd62306a2011-11-10 06:34:14 +0000975 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smith027bf112011-11-17 22:56:20 +0000976 MostDerivedPathLength = 0;
977 MostDerivedIsArrayElement = false;
Richard Smithd62306a2011-11-10 06:34:14 +0000978
979 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
980 bool IsArray = T && T->isArrayType();
981 if (IsArray)
982 T = T->getBaseElementTypeUnsafe();
983 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
984 T = FD->getType().getTypePtr();
985 else
986 T = 0;
987
988 if (T) {
989 MostDerivedType = T->getAsCXXRecordDecl();
990 MostDerivedPathLength = I + 1;
991 MostDerivedIsArrayElement = IsArray;
992 }
993 }
994
Richard Smithd62306a2011-11-10 06:34:14 +0000995 // (B*)&d + 1 has no most-derived object.
996 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
997 return false;
998
Richard Smith027bf112011-11-17 22:56:20 +0000999 return MostDerivedType != 0;
1000}
1001
1002static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
1003 const RecordDecl *TruncatedType,
1004 unsigned TruncatedElements,
1005 bool IsArrayElement) {
1006 SubobjectDesignator &D = Result.Designator;
1007 const RecordDecl *RD = TruncatedType;
1008 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +00001009 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1010 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001011 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001012 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001013 else
Richard Smithd62306a2011-11-10 06:34:14 +00001014 Result.Offset -= Layout.getBaseClassOffset(Base);
1015 RD = Base;
1016 }
Richard Smith027bf112011-11-17 22:56:20 +00001017 D.Entries.resize(TruncatedElements);
1018 D.ArrayElement = IsArrayElement;
1019}
1020
1021/// If the given LValue refers to a base subobject of some object, find the most
1022/// derived object and the corresponding complete record type. This is necessary
1023/// in order to find the offset of a virtual base class.
1024static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
1025 const CXXRecordDecl *&MostDerivedType) {
1026 unsigned MostDerivedPathLength;
1027 bool MostDerivedIsArrayElement;
1028 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1029 MostDerivedPathLength, MostDerivedIsArrayElement))
1030 return false;
1031
1032 // Remove the trailing base class path entries and their offsets.
1033 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
1034 MostDerivedIsArrayElement);
Richard Smithd62306a2011-11-10 06:34:14 +00001035 return true;
1036}
1037
1038static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
1039 const CXXRecordDecl *Derived,
1040 const CXXRecordDecl *Base,
1041 const ASTRecordLayout *RL = 0) {
1042 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1043 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1044 Obj.Designator.addDecl(Base, /*Virtual*/ false);
1045}
1046
1047static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
1048 const CXXRecordDecl *DerivedDecl,
1049 const CXXBaseSpecifier *Base) {
1050 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1051
1052 if (!Base->isVirtual()) {
1053 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
1054 return true;
1055 }
1056
1057 // Extract most-derived object and corresponding type.
1058 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
1059 return false;
1060
1061 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1062 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1063 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
1064 return true;
1065}
1066
1067/// Update LVal to refer to the given field, which must be a member of the type
1068/// currently described by LVal.
1069static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
1070 const FieldDecl *FD,
1071 const ASTRecordLayout *RL = 0) {
1072 if (!RL)
1073 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1074
1075 unsigned I = FD->getFieldIndex();
1076 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1077 LVal.Designator.addDecl(FD);
1078}
1079
1080/// Get the size of the given type in char units.
1081static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1082 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1083 // extension.
1084 if (Type->isVoidType() || Type->isFunctionType()) {
1085 Size = CharUnits::One();
1086 return true;
1087 }
1088
1089 if (!Type->isConstantSizeType()) {
1090 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1091 return false;
1092 }
1093
1094 Size = Info.Ctx.getTypeSizeInChars(Type);
1095 return true;
1096}
1097
1098/// Update a pointer value to model pointer arithmetic.
1099/// \param Info - Information about the ongoing evaluation.
1100/// \param LVal - The pointer value to be updated.
1101/// \param EltTy - The pointee type represented by LVal.
1102/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1103static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
1104 QualType EltTy, int64_t Adjustment) {
1105 CharUnits SizeOfPointee;
1106 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1107 return false;
1108
1109 // Compute the new offset in the appropriate width.
1110 LVal.Offset += Adjustment * SizeOfPointee;
1111 LVal.Designator.adjustIndex(Adjustment);
1112 return true;
1113}
1114
Richard Smith27908702011-10-24 17:54:18 +00001115/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001116static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1117 const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +00001118 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001119 // If this is a parameter to an active constexpr function call, perform
1120 // argument substitution.
1121 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001122 if (!Frame || !Frame->Arguments) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001123 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001124 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001125 }
Richard Smithfec09922011-11-01 16:57:24 +00001126 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1127 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001128 }
Richard Smith27908702011-10-24 17:54:18 +00001129
Richard Smithd0b4dd62011-12-19 06:19:21 +00001130 // Dig out the initializer, and use the declaration which it's attached to.
1131 const Expr *Init = VD->getAnyInitializer(VD);
1132 if (!Init || Init->isValueDependent()) {
1133 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1134 return false;
1135 }
1136
Richard Smithd62306a2011-11-10 06:34:14 +00001137 // If we're currently evaluating the initializer of this declaration, use that
1138 // in-flight value.
1139 if (Info.EvaluatingDecl == VD) {
1140 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
1141 return !Result.isUninit();
1142 }
1143
Richard Smithcecf1842011-11-01 21:06:14 +00001144 // Never evaluate the initializer of a weak variable. We can't be sure that
1145 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001146 if (VD->isWeak()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001147 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001148 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001149 }
Richard Smithcecf1842011-11-01 21:06:14 +00001150
Richard Smithd0b4dd62011-12-19 06:19:21 +00001151 // Check that we can fold the initializer. In C++, we will have already done
1152 // this in the cases where it matters for conformance.
1153 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1154 if (!VD->evaluateValue(Notes)) {
1155 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1156 Notes.size() + 1) << VD;
1157 Info.Note(VD->getLocation(), diag::note_declared_at);
1158 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001159 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001160 } else if (!VD->checkInitIsICE()) {
1161 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1162 Notes.size() + 1) << VD;
1163 Info.Note(VD->getLocation(), diag::note_declared_at);
1164 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001165 }
Richard Smith27908702011-10-24 17:54:18 +00001166
Richard Smithd0b4dd62011-12-19 06:19:21 +00001167 Result = CCValue(*VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +00001168 return true;
Richard Smith27908702011-10-24 17:54:18 +00001169}
1170
Richard Smith11562c52011-10-28 17:51:58 +00001171static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001172 Qualifiers Quals = T.getQualifiers();
1173 return Quals.hasConst() && !Quals.hasVolatile();
1174}
1175
Richard Smithe97cbd72011-11-11 04:05:33 +00001176/// Get the base index of the given base class within an APValue representing
1177/// the given derived class.
1178static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1179 const CXXRecordDecl *Base) {
1180 Base = Base->getCanonicalDecl();
1181 unsigned Index = 0;
1182 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1183 E = Derived->bases_end(); I != E; ++I, ++Index) {
1184 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1185 return Index;
1186 }
1187
1188 llvm_unreachable("base class missing from derived class's bases list");
1189}
1190
Richard Smithf3e9e432011-11-07 09:22:26 +00001191/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001192static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1193 CCValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001194 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001195 if (Sub.Invalid) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001196 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001197 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001198 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001199 if (Sub.OnePastTheEnd) {
1200 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001201 (unsigned)diag::note_constexpr_read_past_end :
1202 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001203 return false;
1204 }
Richard Smith6804be52011-11-11 08:28:03 +00001205 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001206 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +00001207
1208 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1209 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001210 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001211 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001212 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001213 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001214 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001215 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001216 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001217 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001218 // Note, it should not be possible to form a pointer with a valid
1219 // designator which points more than one past the end of the array.
1220 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001221 (unsigned)diag::note_constexpr_read_past_end :
1222 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001223 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001224 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001225 if (O->getArrayInitializedElts() > Index)
1226 O = &O->getArrayInitializedElt(Index);
1227 else
1228 O = &O->getArrayFiller();
1229 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +00001230 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1231 // Next subobject is a class, struct or union field.
1232 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1233 if (RD->isUnion()) {
1234 const FieldDecl *UnionField = O->getUnionField();
1235 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001236 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001237 Info.Diag(E->getExprLoc(),
1238 diag::note_constexpr_read_inactive_union_member)
1239 << Field << !UnionField << UnionField;
Richard Smithd62306a2011-11-10 06:34:14 +00001240 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001241 }
Richard Smithd62306a2011-11-10 06:34:14 +00001242 O = &O->getUnionValue();
1243 } else
1244 O = &O->getStructField(Field->getFieldIndex());
1245 ObjType = Field->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001246
1247 if (ObjType.isVolatileQualified()) {
1248 if (Info.getLangOpts().CPlusPlus) {
1249 // FIXME: Include a description of the path to the volatile subobject.
1250 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1251 << 2 << Field;
1252 Info.Note(Field->getLocation(), diag::note_declared_at);
1253 } else {
1254 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1255 }
1256 return false;
1257 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001258 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001259 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001260 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1261 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1262 O = &O->getStructBase(getBaseIndex(Derived, Base));
1263 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001264 }
Richard Smithd62306a2011-11-10 06:34:14 +00001265
Richard Smithf57d8cb2011-12-09 22:58:01 +00001266 if (O->isUninit()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001267 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smithd62306a2011-11-10 06:34:14 +00001268 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001269 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001270 }
1271
Richard Smithf3e9e432011-11-07 09:22:26 +00001272 Obj = CCValue(*O, CCValue::GlobalValue());
1273 return true;
1274}
1275
Richard Smithd62306a2011-11-10 06:34:14 +00001276/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1277/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1278/// for looking up the glvalue referred to by an entity of reference type.
1279///
1280/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001281/// \param Conv - The expression for which we are performing the conversion.
1282/// Used for diagnostics.
Richard Smithd62306a2011-11-10 06:34:14 +00001283/// \param Type - The type we expect this conversion to produce.
1284/// \param LVal - The glvalue on which we are attempting to perform this action.
1285/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001286static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1287 QualType Type,
Richard Smithf3e9e432011-11-07 09:22:26 +00001288 const LValue &LVal, CCValue &RVal) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001289 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1290 if (!Info.getLangOpts().CPlusPlus)
1291 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1292
Richard Smithce40ad62011-11-12 22:28:03 +00001293 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001294 CallStackFrame *Frame = LVal.Frame;
Richard Smithf2b681b2011-12-21 05:04:46 +00001295 SourceLocation Loc = Conv->getExprLoc();
Richard Smith11562c52011-10-28 17:51:58 +00001296
Richard Smithf57d8cb2011-12-09 22:58:01 +00001297 if (!LVal.Base) {
1298 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithf2b681b2011-12-21 05:04:46 +00001299 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1300 return false;
1301 }
1302
1303 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1304 // is not a constant expression (even if the object is non-volatile). We also
1305 // apply this rule to C++98, in order to conform to the expected 'volatile'
1306 // semantics.
1307 if (Type.isVolatileQualified()) {
1308 if (Info.getLangOpts().CPlusPlus)
1309 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1310 else
1311 Info.Diag(Loc);
Richard Smith11562c52011-10-28 17:51:58 +00001312 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001313 }
Richard Smith11562c52011-10-28 17:51:58 +00001314
Richard Smithce40ad62011-11-12 22:28:03 +00001315 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001316 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1317 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001318 // expressions are constant expressions too. Inside constexpr functions,
1319 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001320 // In C, such things can also be folded, although they are not ICEs.
Richard Smith11562c52011-10-28 17:51:58 +00001321 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001322 if (!VD || VD->isInvalidDecl()) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001323 Info.Diag(Loc);
Richard Smith96e0c102011-11-04 02:25:55 +00001324 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001325 }
1326
Richard Smithf2b681b2011-12-21 05:04:46 +00001327 // DR1313: If the object is volatile-qualified but the glvalue was not,
1328 // behavior is undefined so the result is not a constant expression.
Richard Smithce40ad62011-11-12 22:28:03 +00001329 QualType VT = VD->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001330 if (VT.isVolatileQualified()) {
1331 if (Info.getLangOpts().CPlusPlus) {
1332 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1333 Info.Note(VD->getLocation(), diag::note_declared_at);
1334 } else {
1335 Info.Diag(Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001336 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001337 return false;
1338 }
1339
1340 if (!isa<ParmVarDecl>(VD)) {
1341 if (VD->isConstexpr()) {
1342 // OK, we can read this variable.
1343 } else if (VT->isIntegralOrEnumerationType()) {
1344 if (!VT.isConstQualified()) {
1345 if (Info.getLangOpts().CPlusPlus) {
1346 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1347 Info.Note(VD->getLocation(), diag::note_declared_at);
1348 } else {
1349 Info.Diag(Loc);
1350 }
1351 return false;
1352 }
1353 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1354 // We support folding of const floating-point types, in order to make
1355 // static const data members of such types (supported as an extension)
1356 // more useful.
1357 if (Info.getLangOpts().CPlusPlus0x) {
1358 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1359 Info.Note(VD->getLocation(), diag::note_declared_at);
1360 } else {
1361 Info.CCEDiag(Loc);
1362 }
1363 } else {
1364 // FIXME: Allow folding of values of any literal type in all languages.
1365 if (Info.getLangOpts().CPlusPlus0x) {
1366 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1367 Info.Note(VD->getLocation(), diag::note_declared_at);
1368 } else {
1369 Info.Diag(Loc);
1370 }
Richard Smith96e0c102011-11-04 02:25:55 +00001371 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001372 }
Richard Smith96e0c102011-11-04 02:25:55 +00001373 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001374
Richard Smithf57d8cb2011-12-09 22:58:01 +00001375 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001376 return false;
1377
Richard Smith0b0a0b62011-10-29 20:57:55 +00001378 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001379 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001380
1381 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1382 // conversion. This happens when the declaration and the lvalue should be
1383 // considered synonymous, for instance when initializing an array of char
1384 // from a string literal. Continue as if the initializer lvalue was the
1385 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001386 assert(RVal.getLValueOffset().isZero() &&
1387 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001388 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001389 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001390 }
1391
Richard Smithf2b681b2011-12-21 05:04:46 +00001392 // Volatile temporary objects cannot be read in constant expressions.
1393 if (Base->getType().isVolatileQualified()) {
1394 if (Info.getLangOpts().CPlusPlus) {
1395 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1396 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1397 } else {
1398 Info.Diag(Loc);
1399 }
1400 return false;
1401 }
1402
Richard Smith96e0c102011-11-04 02:25:55 +00001403 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1404 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1405 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001406 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001407 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001408 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001409 }
Richard Smith96e0c102011-11-04 02:25:55 +00001410
1411 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001412 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf2b681b2011-12-21 05:04:46 +00001413 const ConstantArrayType *CAT =
1414 Info.Ctx.getAsConstantArrayType(S->getType());
1415 if (Index >= CAT->getSize().getZExtValue()) {
1416 // Note, it should not be possible to form a pointer which points more
1417 // than one past the end of the array without producing a prior const expr
1418 // diagnostic.
1419 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith96e0c102011-11-04 02:25:55 +00001420 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001421 }
Richard Smith96e0c102011-11-04 02:25:55 +00001422 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1423 Type->isUnsignedIntegerType());
1424 if (Index < S->getLength())
1425 Value = S->getCodeUnit(Index);
1426 RVal = CCValue(Value);
1427 return true;
1428 }
1429
Richard Smithf3e9e432011-11-07 09:22:26 +00001430 if (Frame) {
1431 // If this is a temporary expression with a nontrivial initializer, grab the
1432 // value from the relevant stack frame.
1433 RVal = Frame->Temporaries[Base];
1434 } else if (const CompoundLiteralExpr *CLE
1435 = dyn_cast<CompoundLiteralExpr>(Base)) {
1436 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1437 // initializer until now for such expressions. Such an expression can't be
1438 // an ICE in C, so this only matters for fold.
1439 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1440 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1441 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001442 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00001443 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001444 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001445 }
Richard Smith96e0c102011-11-04 02:25:55 +00001446
Richard Smithf57d8cb2011-12-09 22:58:01 +00001447 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1448 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001449}
1450
Richard Smithe97cbd72011-11-11 04:05:33 +00001451/// Build an lvalue for the object argument of a member function call.
1452static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1453 LValue &This) {
1454 if (Object->getType()->isPointerType())
1455 return EvaluatePointer(Object, This, Info);
1456
1457 if (Object->isGLValue())
1458 return EvaluateLValue(Object, This, Info);
1459
Richard Smith027bf112011-11-17 22:56:20 +00001460 if (Object->getType()->isLiteralType())
1461 return EvaluateTemporary(Object, This, Info);
1462
1463 return false;
1464}
1465
1466/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1467/// lvalue referring to the result.
1468///
1469/// \param Info - Information about the ongoing evaluation.
1470/// \param BO - The member pointer access operation.
1471/// \param LV - Filled in with a reference to the resulting object.
1472/// \param IncludeMember - Specifies whether the member itself is included in
1473/// the resulting LValue subobject designator. This is not possible when
1474/// creating a bound member function.
1475/// \return The field or method declaration to which the member pointer refers,
1476/// or 0 if evaluation fails.
1477static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1478 const BinaryOperator *BO,
1479 LValue &LV,
1480 bool IncludeMember = true) {
1481 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1482
1483 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1484 return 0;
1485
1486 MemberPtr MemPtr;
1487 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1488 return 0;
1489
1490 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1491 // member value, the behavior is undefined.
1492 if (!MemPtr.getDecl())
1493 return 0;
1494
1495 if (MemPtr.isDerivedMember()) {
1496 // This is a member of some derived class. Truncate LV appropriately.
1497 const CXXRecordDecl *MostDerivedType;
1498 unsigned MostDerivedPathLength;
1499 bool MostDerivedIsArrayElement;
1500 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1501 MostDerivedIsArrayElement))
1502 return 0;
1503
1504 // The end of the derived-to-base path for the base object must match the
1505 // derived-to-base path for the member pointer.
1506 if (MostDerivedPathLength + MemPtr.Path.size() >
1507 LV.Designator.Entries.size())
1508 return 0;
1509 unsigned PathLengthToMember =
1510 LV.Designator.Entries.size() - MemPtr.Path.size();
1511 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1512 const CXXRecordDecl *LVDecl = getAsBaseClass(
1513 LV.Designator.Entries[PathLengthToMember + I]);
1514 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1515 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1516 return 0;
1517 }
1518
1519 // Truncate the lvalue to the appropriate derived class.
1520 bool ResultIsArray = false;
1521 if (PathLengthToMember == MostDerivedPathLength)
1522 ResultIsArray = MostDerivedIsArrayElement;
1523 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1524 PathLengthToMember, ResultIsArray);
1525 } else if (!MemPtr.Path.empty()) {
1526 // Extend the LValue path with the member pointer's path.
1527 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1528 MemPtr.Path.size() + IncludeMember);
1529
1530 // Walk down to the appropriate base class.
1531 QualType LVType = BO->getLHS()->getType();
1532 if (const PointerType *PT = LVType->getAs<PointerType>())
1533 LVType = PT->getPointeeType();
1534 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1535 assert(RD && "member pointer access on non-class-type expression");
1536 // The first class in the path is that of the lvalue.
1537 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1538 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1539 HandleLValueDirectBase(Info, LV, RD, Base);
1540 RD = Base;
1541 }
1542 // Finally cast to the class containing the member.
1543 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1544 }
1545
1546 // Add the member. Note that we cannot build bound member functions here.
1547 if (IncludeMember) {
1548 // FIXME: Deal with IndirectFieldDecls.
1549 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1550 if (!FD) return 0;
1551 HandleLValueMember(Info, LV, FD);
1552 }
1553
1554 return MemPtr.getDecl();
1555}
1556
1557/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1558/// the provided lvalue, which currently refers to the base object.
1559static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1560 LValue &Result) {
1561 const CXXRecordDecl *MostDerivedType;
1562 unsigned MostDerivedPathLength;
1563 bool MostDerivedIsArrayElement;
1564
1565 // Check this cast doesn't take us outside the object.
1566 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1567 MostDerivedPathLength,
1568 MostDerivedIsArrayElement))
1569 return false;
1570 SubobjectDesignator &D = Result.Designator;
1571 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1572 return false;
1573
1574 // Check the type of the final cast. We don't need to check the path,
1575 // since a cast can only be formed if the path is unique.
1576 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1577 bool ResultIsArray = false;
1578 QualType TargetQT = E->getType();
1579 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1580 TargetQT = PT->getPointeeType();
1581 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1582 const CXXRecordDecl *FinalType;
1583 if (NewEntriesSize == MostDerivedPathLength) {
1584 ResultIsArray = MostDerivedIsArrayElement;
1585 FinalType = MostDerivedType;
1586 } else
1587 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1588 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1589 return false;
1590
1591 // Truncate the lvalue to the appropriate derived class.
1592 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1593 ResultIsArray);
1594 return true;
Richard Smithe97cbd72011-11-11 04:05:33 +00001595}
1596
Mike Stump876387b2009-10-27 22:09:17 +00001597namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001598enum EvalStmtResult {
1599 /// Evaluation failed.
1600 ESR_Failed,
1601 /// Hit a 'return' statement.
1602 ESR_Returned,
1603 /// Evaluation succeeded.
1604 ESR_Succeeded
1605};
1606}
1607
1608// Evaluate a statement.
Richard Smith357362d2011-12-13 06:39:58 +00001609static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001610 const Stmt *S) {
1611 switch (S->getStmtClass()) {
1612 default:
1613 return ESR_Failed;
1614
1615 case Stmt::NullStmtClass:
1616 case Stmt::DeclStmtClass:
1617 return ESR_Succeeded;
1618
Richard Smith357362d2011-12-13 06:39:58 +00001619 case Stmt::ReturnStmtClass: {
1620 CCValue CCResult;
1621 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1622 if (!Evaluate(CCResult, Info, RetExpr) ||
1623 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1624 CCEK_ReturnValue))
1625 return ESR_Failed;
1626 return ESR_Returned;
1627 }
Richard Smith254a73d2011-10-28 22:34:42 +00001628
1629 case Stmt::CompoundStmtClass: {
1630 const CompoundStmt *CS = cast<CompoundStmt>(S);
1631 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1632 BE = CS->body_end(); BI != BE; ++BI) {
1633 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1634 if (ESR != ESR_Succeeded)
1635 return ESR;
1636 }
1637 return ESR_Succeeded;
1638 }
1639 }
1640}
1641
Richard Smithcc36f692011-12-22 02:22:31 +00001642/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1643/// default constructor. If so, we'll fold it whether or not it's marked as
1644/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1645/// so we need special handling.
1646static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Rafael Espindolafafe4b72011-12-30 03:11:50 +00001647 const CXXConstructorDecl *CD) {
Richard Smithcc36f692011-12-22 02:22:31 +00001648 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1649 return false;
1650
1651 if (!CD->isConstexpr()) {
1652 if (Info.getLangOpts().CPlusPlus0x) {
Rafael Espindolafafe4b72011-12-30 03:11:50 +00001653 // FIXME: If DiagDecl is an implicitly-declared special member function,
1654 // we should be much more explicit about why it's not constexpr.
1655 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1656 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1657 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00001658 } else {
1659 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1660 }
1661 }
1662 return true;
1663}
1664
Richard Smith357362d2011-12-13 06:39:58 +00001665/// CheckConstexprFunction - Check that a function can be called in a constant
1666/// expression.
1667static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1668 const FunctionDecl *Declaration,
1669 const FunctionDecl *Definition) {
1670 // Can we evaluate this function call?
1671 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1672 return true;
1673
1674 if (Info.getLangOpts().CPlusPlus0x) {
1675 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001676 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1677 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00001678 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1679 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1680 << DiagDecl;
1681 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1682 } else {
1683 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1684 }
1685 return false;
1686}
1687
Richard Smithd62306a2011-11-10 06:34:14 +00001688namespace {
Richard Smith60494462011-11-11 05:48:57 +00001689typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001690}
1691
1692/// EvaluateArgs - Evaluate the arguments to a function call.
1693static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1694 EvalInfo &Info) {
1695 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1696 I != E; ++I)
1697 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1698 return false;
1699 return true;
1700}
1701
Richard Smith254a73d2011-10-28 22:34:42 +00001702/// Evaluate a function call.
Richard Smithf6f003a2011-12-16 19:06:07 +00001703static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1704 const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00001705 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith357362d2011-12-13 06:39:58 +00001706 EvalInfo &Info, APValue &Result) {
1707 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith254a73d2011-10-28 22:34:42 +00001708 return false;
1709
Richard Smithd62306a2011-11-10 06:34:14 +00001710 ArgVector ArgValues(Args.size());
1711 if (!EvaluateArgs(Args, ArgValues, Info))
1712 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001713
Richard Smithf6f003a2011-12-16 19:06:07 +00001714 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1715 ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001716 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1717}
1718
Richard Smithd62306a2011-11-10 06:34:14 +00001719/// Evaluate a constructor call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001720static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00001721 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001722 const CXXConstructorDecl *Definition,
Rafael Espindolafafe4b72011-12-30 03:11:50 +00001723 EvalInfo &Info,
1724 APValue &Result) {
Richard Smith357362d2011-12-13 06:39:58 +00001725 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd62306a2011-11-10 06:34:14 +00001726 return false;
1727
1728 ArgVector ArgValues(Args.size());
1729 if (!EvaluateArgs(Args, ArgValues, Info))
1730 return false;
1731
Richard Smithf6f003a2011-12-16 19:06:07 +00001732 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1733 &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00001734
1735 // If it's a delegating constructor, just delegate.
1736 if (Definition->isDelegatingConstructor()) {
1737 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1738 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1739 }
1740
1741 // Reserve space for the struct members.
1742 const CXXRecordDecl *RD = Definition->getParent();
Rafael Espindolafafe4b72011-12-30 03:11:50 +00001743 if (!RD->isUnion())
Richard Smithd62306a2011-11-10 06:34:14 +00001744 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1745 std::distance(RD->field_begin(), RD->field_end()));
1746
1747 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1748
1749 unsigned BasesSeen = 0;
1750#ifndef NDEBUG
1751 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1752#endif
1753 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1754 E = Definition->init_end(); I != E; ++I) {
1755 if ((*I)->isBaseInitializer()) {
1756 QualType BaseType((*I)->getBaseClass(), 0);
1757#ifndef NDEBUG
1758 // Non-virtual base classes are initialized in the order in the class
1759 // definition. We cannot have a virtual base class for a literal type.
1760 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1761 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1762 "base class initializers not in expected order");
1763 ++BaseIt;
1764#endif
1765 LValue Subobject = This;
1766 HandleLValueDirectBase(Info, Subobject, RD,
1767 BaseType->getAsCXXRecordDecl(), &Layout);
1768 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1769 Subobject, (*I)->getInit()))
1770 return false;
1771 } else if (FieldDecl *FD = (*I)->getMember()) {
1772 LValue Subobject = This;
1773 HandleLValueMember(Info, Subobject, FD, &Layout);
1774 if (RD->isUnion()) {
1775 Result = APValue(FD);
Richard Smith357362d2011-12-13 06:39:58 +00001776 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1777 (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001778 return false;
1779 } else if (!EvaluateConstantExpression(
1780 Result.getStructField(FD->getFieldIndex()),
Richard Smith357362d2011-12-13 06:39:58 +00001781 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smithd62306a2011-11-10 06:34:14 +00001782 return false;
1783 } else {
1784 // FIXME: handle indirect field initializers
Richard Smith92b1ce02011-12-12 09:28:41 +00001785 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf57d8cb2011-12-09 22:58:01 +00001786 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001787 return false;
1788 }
1789 }
1790
1791 return true;
1792}
1793
Richard Smith254a73d2011-10-28 22:34:42 +00001794namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001795class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001796 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001797 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001798public:
1799
Richard Smith725810a2011-10-16 21:26:27 +00001800 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001801
1802 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001803 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001804 return true;
1805 }
1806
Peter Collingbournee9200682011-05-13 03:29:01 +00001807 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1808 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001809 return Visit(E->getResultExpr());
1810 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001811 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001812 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001813 return true;
1814 return false;
1815 }
John McCall31168b02011-06-15 23:02:42 +00001816 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001817 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001818 return true;
1819 return false;
1820 }
1821 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001822 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001823 return true;
1824 return false;
1825 }
1826
Mike Stump876387b2009-10-27 22:09:17 +00001827 // We don't want to evaluate BlockExprs multiple times, as they generate
1828 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001829 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1830 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1831 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001832 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001833 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1834 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1835 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1836 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1837 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1838 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001839 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001840 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001841 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001842 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001843 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001844 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1845 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1846 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1847 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001848 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001849 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1850 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1851 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1852 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1853 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001854 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001855 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001856 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001857 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001858 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001859
1860 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001861 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001862 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1863 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001864 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001865 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001866 return false;
1867 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001868
Peter Collingbournee9200682011-05-13 03:29:01 +00001869 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001870};
1871
John McCallc07a0c72011-02-17 10:25:35 +00001872class OpaqueValueEvaluation {
1873 EvalInfo &info;
1874 OpaqueValueExpr *opaqueValue;
1875
1876public:
1877 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1878 Expr *value)
1879 : info(info), opaqueValue(opaqueValue) {
1880
1881 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00001882 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00001883 this->opaqueValue = 0;
1884 return;
1885 }
John McCallc07a0c72011-02-17 10:25:35 +00001886 }
1887
1888 bool hasError() const { return opaqueValue == 0; }
1889
1890 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00001891 // FIXME: This will not work for recursive constexpr functions using opaque
1892 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00001893 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1894 }
1895};
1896
Mike Stump876387b2009-10-27 22:09:17 +00001897} // end anonymous namespace
1898
Eli Friedman9a156e52008-11-12 09:44:48 +00001899//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00001900// Generic Evaluation
1901//===----------------------------------------------------------------------===//
1902namespace {
1903
Richard Smithf57d8cb2011-12-09 22:58:01 +00001904// FIXME: RetTy is always bool. Remove it.
1905template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00001906class ExprEvaluatorBase
1907 : public ConstStmtVisitor<Derived, RetTy> {
1908private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001909 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001910 return static_cast<Derived*>(this)->Success(V, E);
1911 }
Rafael Espindolafafe4b72011-12-30 03:11:50 +00001912 RetTy DerivedValueInitialization(const Expr *E) {
1913 return static_cast<Derived*>(this)->ValueInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00001914 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001915
1916protected:
1917 EvalInfo &Info;
1918 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1919 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1920
Richard Smith92b1ce02011-12-12 09:28:41 +00001921 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith187ef012011-12-12 09:41:58 +00001922 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001923 }
1924
1925 /// Report an evaluation error. This should only be called when an error is
1926 /// first discovered. When propagating an error, just return false.
1927 bool Error(const Expr *E, diag::kind D) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001928 Info.Diag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001929 return false;
1930 }
1931 bool Error(const Expr *E) {
1932 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1933 }
1934
Rafael Espindolafafe4b72011-12-30 03:11:50 +00001935 RetTy ValueInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00001936
Peter Collingbournee9200682011-05-13 03:29:01 +00001937public:
1938 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1939
1940 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00001941 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00001942 }
1943 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001944 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001945 }
1946
1947 RetTy VisitParenExpr(const ParenExpr *E)
1948 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1949 RetTy VisitUnaryExtension(const UnaryOperator *E)
1950 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1951 RetTy VisitUnaryPlus(const UnaryOperator *E)
1952 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1953 RetTy VisitChooseExpr(const ChooseExpr *E)
1954 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1955 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1956 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00001957 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1958 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00001959 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1960 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00001961 // We cannot create any objects for which cleanups are required, so there is
1962 // nothing to do here; all cleanups must come from unevaluated subexpressions.
1963 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
1964 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001965
Richard Smith6d6ecc32011-12-12 12:46:16 +00001966 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1967 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1968 return static_cast<Derived*>(this)->VisitCastExpr(E);
1969 }
1970 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1971 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1972 return static_cast<Derived*>(this)->VisitCastExpr(E);
1973 }
1974
Richard Smith027bf112011-11-17 22:56:20 +00001975 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1976 switch (E->getOpcode()) {
1977 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00001978 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00001979
1980 case BO_Comma:
1981 VisitIgnoredValue(E->getLHS());
1982 return StmtVisitorTy::Visit(E->getRHS());
1983
1984 case BO_PtrMemD:
1985 case BO_PtrMemI: {
1986 LValue Obj;
1987 if (!HandleMemberPointerAccess(Info, E, Obj))
1988 return false;
1989 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001990 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00001991 return false;
1992 return DerivedSuccess(Result, E);
1993 }
1994 }
1995 }
1996
Peter Collingbournee9200682011-05-13 03:29:01 +00001997 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1998 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1999 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002000 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002001
2002 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00002003 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002004 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002005
2006 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2007 }
2008
2009 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2010 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002011 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002012 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002013
Richard Smith11562c52011-10-28 17:51:58 +00002014 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00002015 return StmtVisitorTy::Visit(EvalExpr);
2016 }
2017
2018 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002019 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002020 if (!Value) {
2021 const Expr *Source = E->getSourceExpr();
2022 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002023 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002024 if (Source == E) { // sanity checking.
2025 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00002026 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002027 }
2028 return StmtVisitorTy::Visit(Source);
2029 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00002030 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002031 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002032
Richard Smith254a73d2011-10-28 22:34:42 +00002033 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002034 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00002035 QualType CalleeType = Callee->getType();
2036
Richard Smith254a73d2011-10-28 22:34:42 +00002037 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00002038 LValue *This = 0, ThisVal;
2039 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00002040
Richard Smithe97cbd72011-11-11 04:05:33 +00002041 // Extract function decl and 'this' pointer from the callee.
2042 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002043 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00002044 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2045 // Explicit bound member calls, such as x.f() or p->g();
2046 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002047 return false;
2048 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002049 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002050 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2051 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00002052 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2053 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00002054 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002055 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002056 return Error(Callee);
2057
2058 FD = dyn_cast<FunctionDecl>(Member);
2059 if (!FD)
2060 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002061 } else if (CalleeType->isFunctionPointerType()) {
2062 CCValue Call;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002063 if (!Evaluate(Call, Info, Callee))
2064 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00002065
Richard Smithf57d8cb2011-12-09 22:58:01 +00002066 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
2067 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00002068 FD = dyn_cast_or_null<FunctionDecl>(
2069 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00002070 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002071 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002072
2073 // Overloaded operator calls to member functions are represented as normal
2074 // calls with '*this' as the first argument.
2075 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2076 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002077 // FIXME: When selecting an implicit conversion for an overloaded
2078 // operator delete, we sometimes try to evaluate calls to conversion
2079 // operators without a 'this' parameter!
2080 if (Args.empty())
2081 return Error(E);
2082
Richard Smithe97cbd72011-11-11 04:05:33 +00002083 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2084 return false;
2085 This = &ThisVal;
2086 Args = Args.slice(1);
2087 }
2088
2089 // Don't call function pointers which have been cast to some other type.
2090 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002091 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002092 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002093 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002094
Richard Smith357362d2011-12-13 06:39:58 +00002095 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002096 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00002097 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002098
Richard Smith357362d2011-12-13 06:39:58 +00002099 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smithf6f003a2011-12-16 19:06:07 +00002100 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002101 return false;
2102
2103 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00002104 }
2105
Richard Smith11562c52011-10-28 17:51:58 +00002106 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2107 return StmtVisitorTy::Visit(E->getInitializer());
2108 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002109 RetTy VisitInitListExpr(const InitListExpr *E) {
2110 if (Info.getLangOpts().CPlusPlus0x) {
2111 if (E->getNumInits() == 0)
Rafael Espindolafafe4b72011-12-30 03:11:50 +00002112 return DerivedValueInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002113 if (E->getNumInits() == 1)
2114 return StmtVisitorTy::Visit(E->getInit(0));
2115 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00002116 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002117 }
2118 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Rafael Espindolafafe4b72011-12-30 03:11:50 +00002119 return DerivedValueInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002120 }
2121 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Rafael Espindolafafe4b72011-12-30 03:11:50 +00002122 return DerivedValueInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002123 }
Richard Smith027bf112011-11-17 22:56:20 +00002124 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Rafael Espindolafafe4b72011-12-30 03:11:50 +00002125 return DerivedValueInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002126 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002127
Richard Smithd62306a2011-11-10 06:34:14 +00002128 /// A member expression where the object is a prvalue is itself a prvalue.
2129 RetTy VisitMemberExpr(const MemberExpr *E) {
2130 assert(!E->isArrow() && "missing call to bound member function?");
2131
2132 CCValue Val;
2133 if (!Evaluate(Val, Info, E->getBase()))
2134 return false;
2135
2136 QualType BaseTy = E->getBase()->getType();
2137
2138 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002139 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002140 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2141 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2142 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2143
2144 SubobjectDesignator Designator;
2145 Designator.addDecl(FD);
2146
Richard Smithf57d8cb2011-12-09 22:58:01 +00002147 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002148 DerivedSuccess(Val, E);
2149 }
2150
Richard Smith11562c52011-10-28 17:51:58 +00002151 RetTy VisitCastExpr(const CastExpr *E) {
2152 switch (E->getCastKind()) {
2153 default:
2154 break;
2155
2156 case CK_NoOp:
2157 return StmtVisitorTy::Visit(E->getSubExpr());
2158
2159 case CK_LValueToRValue: {
2160 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002161 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2162 return false;
2163 CCValue RVal;
2164 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2165 return false;
2166 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002167 }
2168 }
2169
Richard Smithf57d8cb2011-12-09 22:58:01 +00002170 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002171 }
2172
Richard Smith4a678122011-10-24 18:44:57 +00002173 /// Visit a value which is evaluated, but whose value is ignored.
2174 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002175 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002176 if (!Evaluate(Scratch, Info, E))
2177 Info.EvalStatus.HasSideEffects = true;
2178 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002179};
2180
2181}
2182
2183//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002184// Common base class for lvalue and temporary evaluation.
2185//===----------------------------------------------------------------------===//
2186namespace {
2187template<class Derived>
2188class LValueExprEvaluatorBase
2189 : public ExprEvaluatorBase<Derived, bool> {
2190protected:
2191 LValue &Result;
2192 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2193 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2194
2195 bool Success(APValue::LValueBase B) {
2196 Result.set(B);
2197 return true;
2198 }
2199
2200public:
2201 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2202 ExprEvaluatorBaseTy(Info), Result(Result) {}
2203
2204 bool Success(const CCValue &V, const Expr *E) {
2205 Result.setFrom(V);
2206 return true;
2207 }
Richard Smith027bf112011-11-17 22:56:20 +00002208
2209 bool CheckValidLValue() {
2210 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
2211 // there are no null references, nor once-past-the-end references.
2212 // FIXME: Check for one-past-the-end array indices
2213 return Result.Base && !Result.Designator.Invalid &&
2214 !Result.Designator.OnePastTheEnd;
2215 }
2216
2217 bool VisitMemberExpr(const MemberExpr *E) {
2218 // Handle non-static data members.
2219 QualType BaseTy;
2220 if (E->isArrow()) {
2221 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2222 return false;
2223 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002224 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002225 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002226 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2227 return false;
2228 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002229 } else {
2230 if (!this->Visit(E->getBase()))
2231 return false;
2232 BaseTy = E->getBase()->getType();
2233 }
2234 // FIXME: In C++11, require the result to be a valid lvalue.
2235
2236 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2237 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00002238 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002239 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2240 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2241 (void)BaseTy;
2242
2243 HandleLValueMember(this->Info, Result, FD);
2244
2245 if (FD->getType()->isReferenceType()) {
2246 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002247 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002248 RefValue))
2249 return false;
2250 return Success(RefValue, E);
2251 }
2252 return true;
2253 }
2254
2255 bool VisitBinaryOperator(const BinaryOperator *E) {
2256 switch (E->getOpcode()) {
2257 default:
2258 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2259
2260 case BO_PtrMemD:
2261 case BO_PtrMemI:
2262 return HandleMemberPointerAccess(this->Info, E, Result);
2263 }
2264 }
2265
2266 bool VisitCastExpr(const CastExpr *E) {
2267 switch (E->getCastKind()) {
2268 default:
2269 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2270
2271 case CK_DerivedToBase:
2272 case CK_UncheckedDerivedToBase: {
2273 if (!this->Visit(E->getSubExpr()))
2274 return false;
2275 if (!CheckValidLValue())
2276 return false;
2277
2278 // Now figure out the necessary offset to add to the base LV to get from
2279 // the derived class to the base class.
2280 QualType Type = E->getSubExpr()->getType();
2281
2282 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2283 PathE = E->path_end(); PathI != PathE; ++PathI) {
2284 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2285 *PathI))
2286 return false;
2287 Type = (*PathI)->getType();
2288 }
2289
2290 return true;
2291 }
2292 }
2293 }
2294};
2295}
2296
2297//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002298// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002299//
2300// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2301// function designators (in C), decl references to void objects (in C), and
2302// temporaries (if building with -Wno-address-of-temporary).
2303//
2304// LValue evaluation produces values comprising a base expression of one of the
2305// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002306// - Declarations
2307// * VarDecl
2308// * FunctionDecl
2309// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002310// * CompoundLiteralExpr in C
2311// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00002312// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00002313// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002314// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002315// * ObjCEncodeExpr
2316// * AddrLabelExpr
2317// * BlockExpr
2318// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002319// - Locals and temporaries
2320// * Any Expr, with a Frame indicating the function in which the temporary was
2321// evaluated.
2322// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002323//===----------------------------------------------------------------------===//
2324namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002325class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002326 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002327public:
Richard Smith027bf112011-11-17 22:56:20 +00002328 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2329 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002330
Richard Smith11562c52011-10-28 17:51:58 +00002331 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2332
Peter Collingbournee9200682011-05-13 03:29:01 +00002333 bool VisitDeclRefExpr(const DeclRefExpr *E);
2334 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002335 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002336 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2337 bool VisitMemberExpr(const MemberExpr *E);
2338 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2339 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00002340 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002341 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2342 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002343
Peter Collingbournee9200682011-05-13 03:29:01 +00002344 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002345 switch (E->getCastKind()) {
2346 default:
Richard Smith027bf112011-11-17 22:56:20 +00002347 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002348
Eli Friedmance3e02a2011-10-11 00:13:24 +00002349 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002350 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002351 if (!Visit(E->getSubExpr()))
2352 return false;
2353 Result.Designator.setInvalid();
2354 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002355
Richard Smith027bf112011-11-17 22:56:20 +00002356 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002357 if (!Visit(E->getSubExpr()))
2358 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002359 if (!CheckValidLValue())
2360 return false;
2361 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002362 }
2363 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00002364
Eli Friedman449fe542009-03-23 04:56:01 +00002365 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00002366
Eli Friedman9a156e52008-11-12 09:44:48 +00002367};
2368} // end anonymous namespace
2369
Richard Smith11562c52011-10-28 17:51:58 +00002370/// Evaluate an expression as an lvalue. This can be legitimately called on
2371/// expressions which are not glvalues, in a few cases:
2372/// * function designators in C,
2373/// * "extern void" objects,
2374/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002375static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002376 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2377 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2378 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002379 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002380}
2381
Peter Collingbournee9200682011-05-13 03:29:01 +00002382bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002383 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2384 return Success(FD);
2385 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002386 return VisitVarDecl(E, VD);
2387 return Error(E);
2388}
Richard Smith733237d2011-10-24 23:14:33 +00002389
Richard Smith11562c52011-10-28 17:51:58 +00002390bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002391 if (!VD->getType()->isReferenceType()) {
2392 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002393 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002394 return true;
2395 }
Richard Smithce40ad62011-11-12 22:28:03 +00002396 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002397 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002398
Richard Smith0b0a0b62011-10-29 20:57:55 +00002399 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002400 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2401 return false;
2402 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002403}
2404
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002405bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2406 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002407 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002408 if (E->getType()->isRecordType())
Richard Smith027bf112011-11-17 22:56:20 +00002409 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2410
2411 Result.set(E, Info.CurrentCall);
2412 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2413 Result, E->GetTemporaryExpr());
2414 }
2415
2416 // Materialization of an lvalue temporary occurs when we need to force a copy
2417 // (for instance, if it's a bitfield).
2418 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2419 if (!Visit(E->GetTemporaryExpr()))
2420 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002421 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002422 Info.CurrentCall->Temporaries[E]))
2423 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002424 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002425 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002426}
2427
Peter Collingbournee9200682011-05-13 03:29:01 +00002428bool
2429LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002430 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2431 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2432 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002433 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002434}
2435
Richard Smith6e525142011-12-27 12:18:28 +00002436bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2437 if (E->isTypeOperand())
2438 return Success(E);
2439 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2440 if (RD && RD->isPolymorphic()) {
2441 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2442 << E->getExprOperand()->getType()
2443 << E->getExprOperand()->getSourceRange();
2444 return false;
2445 }
2446 return Success(E);
2447}
2448
Peter Collingbournee9200682011-05-13 03:29:01 +00002449bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002450 // Handle static data members.
2451 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2452 VisitIgnoredValue(E->getBase());
2453 return VisitVarDecl(E, VD);
2454 }
2455
Richard Smith254a73d2011-10-28 22:34:42 +00002456 // Handle static member functions.
2457 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2458 if (MD->isStatic()) {
2459 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002460 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002461 }
2462 }
2463
Richard Smithd62306a2011-11-10 06:34:14 +00002464 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002465 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002466}
2467
Peter Collingbournee9200682011-05-13 03:29:01 +00002468bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002469 // FIXME: Deal with vectors as array subscript bases.
2470 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002471 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002472
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002473 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002474 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002475
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002476 APSInt Index;
2477 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002478 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002479 int64_t IndexValue
2480 = Index.isSigned() ? Index.getSExtValue()
2481 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002482
Richard Smith027bf112011-11-17 22:56:20 +00002483 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002484 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002485}
Eli Friedman9a156e52008-11-12 09:44:48 +00002486
Peter Collingbournee9200682011-05-13 03:29:01 +00002487bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002488 // FIXME: In C++11, require the result to be a valid lvalue.
John McCall45d55e42010-05-07 21:00:08 +00002489 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002490}
2491
Eli Friedman9a156e52008-11-12 09:44:48 +00002492//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002493// Pointer Evaluation
2494//===----------------------------------------------------------------------===//
2495
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002496namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002497class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002498 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002499 LValue &Result;
2500
Peter Collingbournee9200682011-05-13 03:29:01 +00002501 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002502 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002503 return true;
2504 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002505public:
Mike Stump11289f42009-09-09 15:08:12 +00002506
John McCall45d55e42010-05-07 21:00:08 +00002507 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002508 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002509
Richard Smith0b0a0b62011-10-29 20:57:55 +00002510 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002511 Result.setFrom(V);
2512 return true;
2513 }
Rafael Espindolafafe4b72011-12-30 03:11:50 +00002514 bool ValueInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002515 return Success((Expr*)0);
2516 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002517
John McCall45d55e42010-05-07 21:00:08 +00002518 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002519 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002520 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002521 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002522 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002523 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002524 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002525 bool VisitCallExpr(const CallExpr *E);
2526 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002527 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002528 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002529 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002530 }
Richard Smithd62306a2011-11-10 06:34:14 +00002531 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2532 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002533 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002534 Result = *Info.CurrentCall->This;
2535 return true;
2536 }
John McCallc07a0c72011-02-17 10:25:35 +00002537
Eli Friedman449fe542009-03-23 04:56:01 +00002538 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002539};
Chris Lattner05706e882008-07-11 18:11:29 +00002540} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002541
John McCall45d55e42010-05-07 21:00:08 +00002542static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002543 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002544 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002545}
2546
John McCall45d55e42010-05-07 21:00:08 +00002547bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002548 if (E->getOpcode() != BO_Add &&
2549 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002550 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002551
Chris Lattner05706e882008-07-11 18:11:29 +00002552 const Expr *PExp = E->getLHS();
2553 const Expr *IExp = E->getRHS();
2554 if (IExp->getType()->isPointerType())
2555 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002556
John McCall45d55e42010-05-07 21:00:08 +00002557 if (!EvaluatePointer(PExp, Result, Info))
2558 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002559
John McCall45d55e42010-05-07 21:00:08 +00002560 llvm::APSInt Offset;
2561 if (!EvaluateInteger(IExp, Offset, Info))
2562 return false;
2563 int64_t AdditionalOffset
2564 = Offset.isSigned() ? Offset.getSExtValue()
2565 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002566 if (E->getOpcode() == BO_Sub)
2567 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002568
Richard Smithd62306a2011-11-10 06:34:14 +00002569 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith027bf112011-11-17 22:56:20 +00002570 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002571 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002572}
Eli Friedman9a156e52008-11-12 09:44:48 +00002573
John McCall45d55e42010-05-07 21:00:08 +00002574bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2575 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002576}
Mike Stump11289f42009-09-09 15:08:12 +00002577
Peter Collingbournee9200682011-05-13 03:29:01 +00002578bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2579 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002580
Eli Friedman847a2bc2009-12-27 05:43:15 +00002581 switch (E->getCastKind()) {
2582 default:
2583 break;
2584
John McCalle3027922010-08-25 11:45:40 +00002585 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002586 case CK_CPointerToObjCPointerCast:
2587 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002588 case CK_AnyPointerToBlockPointerCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002589 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2590 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2591 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00002592 if (!E->getType()->isVoidPointerType()) {
2593 if (SubExpr->getType()->isVoidPointerType())
2594 CCEDiag(E, diag::note_constexpr_invalid_cast)
2595 << 3 << SubExpr->getType();
2596 else
2597 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2598 }
Richard Smith96e0c102011-11-04 02:25:55 +00002599 if (!Visit(SubExpr))
2600 return false;
2601 Result.Designator.setInvalid();
2602 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002603
Anders Carlsson18275092010-10-31 20:41:46 +00002604 case CK_DerivedToBase:
2605 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002606 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002607 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002608 if (!Result.Base && Result.Offset.isZero())
2609 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002610
Richard Smithd62306a2011-11-10 06:34:14 +00002611 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002612 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002613 QualType Type =
2614 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002615
Richard Smithd62306a2011-11-10 06:34:14 +00002616 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002617 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithd62306a2011-11-10 06:34:14 +00002618 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002619 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002620 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002621 }
2622
Anders Carlsson18275092010-10-31 20:41:46 +00002623 return true;
2624 }
2625
Richard Smith027bf112011-11-17 22:56:20 +00002626 case CK_BaseToDerived:
2627 if (!Visit(E->getSubExpr()))
2628 return false;
2629 if (!Result.Base && Result.Offset.isZero())
2630 return true;
2631 return HandleBaseToDerivedCast(Info, E, Result);
2632
Richard Smith0b0a0b62011-10-29 20:57:55 +00002633 case CK_NullToPointer:
Rafael Espindolafafe4b72011-12-30 03:11:50 +00002634 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002635
John McCalle3027922010-08-25 11:45:40 +00002636 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00002637 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2638
Richard Smith0b0a0b62011-10-29 20:57:55 +00002639 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002640 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002641 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002642
John McCall45d55e42010-05-07 21:00:08 +00002643 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002644 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2645 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002646 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002647 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002648 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002649 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002650 return true;
2651 } else {
2652 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002653 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002654 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002655 }
2656 }
John McCalle3027922010-08-25 11:45:40 +00002657 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002658 if (SubExpr->isGLValue()) {
2659 if (!EvaluateLValue(SubExpr, Result, Info))
2660 return false;
2661 } else {
2662 Result.set(SubExpr, Info.CurrentCall);
2663 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2664 Info, Result, SubExpr))
2665 return false;
2666 }
Richard Smith96e0c102011-11-04 02:25:55 +00002667 // The result is a pointer to the first element of the array.
2668 Result.Designator.addIndex(0);
2669 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002670
John McCalle3027922010-08-25 11:45:40 +00002671 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002672 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002673 }
2674
Richard Smith11562c52011-10-28 17:51:58 +00002675 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002676}
Chris Lattner05706e882008-07-11 18:11:29 +00002677
Peter Collingbournee9200682011-05-13 03:29:01 +00002678bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002679 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002680 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002681
Peter Collingbournee9200682011-05-13 03:29:01 +00002682 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002683}
Chris Lattner05706e882008-07-11 18:11:29 +00002684
2685//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002686// Member Pointer Evaluation
2687//===----------------------------------------------------------------------===//
2688
2689namespace {
2690class MemberPointerExprEvaluator
2691 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2692 MemberPtr &Result;
2693
2694 bool Success(const ValueDecl *D) {
2695 Result = MemberPtr(D);
2696 return true;
2697 }
2698public:
2699
2700 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2701 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2702
2703 bool Success(const CCValue &V, const Expr *E) {
2704 Result.setFrom(V);
2705 return true;
2706 }
Rafael Espindolafafe4b72011-12-30 03:11:50 +00002707 bool ValueInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002708 return Success((const ValueDecl*)0);
2709 }
2710
2711 bool VisitCastExpr(const CastExpr *E);
2712 bool VisitUnaryAddrOf(const UnaryOperator *E);
2713};
2714} // end anonymous namespace
2715
2716static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2717 EvalInfo &Info) {
2718 assert(E->isRValue() && E->getType()->isMemberPointerType());
2719 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2720}
2721
2722bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2723 switch (E->getCastKind()) {
2724 default:
2725 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2726
2727 case CK_NullToMemberPointer:
Rafael Espindolafafe4b72011-12-30 03:11:50 +00002728 return ValueInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002729
2730 case CK_BaseToDerivedMemberPointer: {
2731 if (!Visit(E->getSubExpr()))
2732 return false;
2733 if (E->path_empty())
2734 return true;
2735 // Base-to-derived member pointer casts store the path in derived-to-base
2736 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2737 // the wrong end of the derived->base arc, so stagger the path by one class.
2738 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2739 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2740 PathI != PathE; ++PathI) {
2741 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2742 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2743 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002744 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002745 }
2746 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2747 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002748 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002749 return true;
2750 }
2751
2752 case CK_DerivedToBaseMemberPointer:
2753 if (!Visit(E->getSubExpr()))
2754 return false;
2755 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2756 PathE = E->path_end(); PathI != PathE; ++PathI) {
2757 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2758 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2759 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002760 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002761 }
2762 return true;
2763 }
2764}
2765
2766bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2767 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2768 // member can be formed.
2769 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2770}
2771
2772//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002773// Record Evaluation
2774//===----------------------------------------------------------------------===//
2775
2776namespace {
2777 class RecordExprEvaluator
2778 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2779 const LValue &This;
2780 APValue &Result;
2781 public:
2782
2783 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2784 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2785
2786 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002787 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002788 }
Richard Smithd62306a2011-11-10 06:34:14 +00002789
Richard Smithe97cbd72011-11-11 04:05:33 +00002790 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002791 bool VisitInitListExpr(const InitListExpr *E);
2792 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2793 };
2794}
2795
Richard Smithe97cbd72011-11-11 04:05:33 +00002796bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2797 switch (E->getCastKind()) {
2798 default:
2799 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2800
2801 case CK_ConstructorConversion:
2802 return Visit(E->getSubExpr());
2803
2804 case CK_DerivedToBase:
2805 case CK_UncheckedDerivedToBase: {
2806 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002807 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002808 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002809 if (!DerivedObject.isStruct())
2810 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00002811
2812 // Derived-to-base rvalue conversion: just slice off the derived part.
2813 APValue *Value = &DerivedObject;
2814 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2815 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2816 PathE = E->path_end(); PathI != PathE; ++PathI) {
2817 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2818 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2819 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2820 RD = Base;
2821 }
2822 Result = *Value;
2823 return true;
2824 }
2825 }
2826}
2827
Richard Smithd62306a2011-11-10 06:34:14 +00002828bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2829 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2830 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2831
2832 if (RD->isUnion()) {
2833 Result = APValue(E->getInitializedFieldInUnion());
2834 if (!E->getNumInits())
2835 return true;
2836 LValue Subobject = This;
2837 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2838 &Layout);
2839 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2840 Subobject, E->getInit(0));
2841 }
2842
2843 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2844 "initializer list for class with base classes");
2845 Result = APValue(APValue::UninitStruct(), 0,
2846 std::distance(RD->field_begin(), RD->field_end()));
2847 unsigned ElementNo = 0;
2848 for (RecordDecl::field_iterator Field = RD->field_begin(),
2849 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2850 // Anonymous bit-fields are not considered members of the class for
2851 // purposes of aggregate initialization.
2852 if (Field->isUnnamedBitfield())
2853 continue;
2854
2855 LValue Subobject = This;
2856 HandleLValueMember(Info, Subobject, *Field, &Layout);
2857
2858 if (ElementNo < E->getNumInits()) {
2859 if (!EvaluateConstantExpression(
2860 Result.getStructField((*Field)->getFieldIndex()),
2861 Info, Subobject, E->getInit(ElementNo++)))
2862 return false;
2863 } else {
2864 // Perform an implicit value-initialization for members beyond the end of
2865 // the initializer list.
2866 ImplicitValueInitExpr VIE(Field->getType());
2867 if (!EvaluateConstantExpression(
2868 Result.getStructField((*Field)->getFieldIndex()),
2869 Info, Subobject, &VIE))
2870 return false;
2871 }
2872 }
2873
2874 return true;
2875}
2876
2877bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2878 const CXXConstructorDecl *FD = E->getConstructor();
Rafael Espindolafafe4b72011-12-30 03:11:50 +00002879 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD)) {
Richard Smithcc36f692011-12-22 02:22:31 +00002880 const CXXRecordDecl *RD = FD->getParent();
2881 if (RD->isUnion())
2882 Result = APValue((FieldDecl*)0);
2883 else
2884 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2885 std::distance(RD->field_begin(), RD->field_end()));
2886 return true;
2887 }
2888
Richard Smithd62306a2011-11-10 06:34:14 +00002889 const FunctionDecl *Definition = 0;
2890 FD->getBody(Definition);
2891
Richard Smith357362d2011-12-13 06:39:58 +00002892 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2893 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002894
2895 // FIXME: Elide the copy/move construction wherever we can.
Rafael Espindolafafe4b72011-12-30 03:11:50 +00002896 if (E->isElidable())
Richard Smithd62306a2011-11-10 06:34:14 +00002897 if (const MaterializeTemporaryExpr *ME
2898 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2899 return Visit(ME->GetTemporaryExpr());
2900
2901 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002902 return HandleConstructorCall(E, This, Args,
2903 cast<CXXConstructorDecl>(Definition), Info,
2904 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002905}
2906
2907static bool EvaluateRecord(const Expr *E, const LValue &This,
2908 APValue &Result, EvalInfo &Info) {
2909 assert(E->isRValue() && E->getType()->isRecordType() &&
Rafael Espindolafafe4b72011-12-30 03:11:50 +00002910 E->getType()->isLiteralType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00002911 "can't evaluate expression as a record rvalue");
2912 return RecordExprEvaluator(Info, This, Result).Visit(E);
2913}
2914
2915//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002916// Temporary Evaluation
2917//
2918// Temporaries are represented in the AST as rvalues, but generally behave like
2919// lvalues. The full-object of which the temporary is a subobject is implicitly
2920// materialized so that a reference can bind to it.
2921//===----------------------------------------------------------------------===//
2922namespace {
2923class TemporaryExprEvaluator
2924 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
2925public:
2926 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
2927 LValueExprEvaluatorBaseTy(Info, Result) {}
2928
2929 /// Visit an expression which constructs the value of this temporary.
2930 bool VisitConstructExpr(const Expr *E) {
2931 Result.set(E, Info.CurrentCall);
2932 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2933 Result, E);
2934 }
2935
2936 bool VisitCastExpr(const CastExpr *E) {
2937 switch (E->getCastKind()) {
2938 default:
2939 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2940
2941 case CK_ConstructorConversion:
2942 return VisitConstructExpr(E->getSubExpr());
2943 }
2944 }
2945 bool VisitInitListExpr(const InitListExpr *E) {
2946 return VisitConstructExpr(E);
2947 }
2948 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2949 return VisitConstructExpr(E);
2950 }
2951 bool VisitCallExpr(const CallExpr *E) {
2952 return VisitConstructExpr(E);
2953 }
2954};
2955} // end anonymous namespace
2956
2957/// Evaluate an expression of record type as a temporary.
2958static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002959 assert(E->isRValue() && E->getType()->isRecordType());
Rafael Espindolafafe4b72011-12-30 03:11:50 +00002960 if (!E->getType()->isLiteralType()) {
2961 if (Info.getLangOpts().CPlusPlus0x)
2962 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
2963 << E->getType();
2964 else
2965 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
2966 return false;
2967 }
Richard Smith027bf112011-11-17 22:56:20 +00002968 return TemporaryExprEvaluator(Info, Result).Visit(E);
2969}
2970
2971//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002972// Vector Evaluation
2973//===----------------------------------------------------------------------===//
2974
2975namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002976 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00002977 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
2978 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002979 public:
Mike Stump11289f42009-09-09 15:08:12 +00002980
Richard Smith2d406342011-10-22 21:10:00 +00002981 VectorExprEvaluator(EvalInfo &info, APValue &Result)
2982 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002983
Richard Smith2d406342011-10-22 21:10:00 +00002984 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
2985 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
2986 // FIXME: remove this APValue copy.
2987 Result = APValue(V.data(), V.size());
2988 return true;
2989 }
Richard Smithed5165f2011-11-04 05:33:44 +00002990 bool Success(const CCValue &V, const Expr *E) {
2991 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00002992 Result = V;
2993 return true;
2994 }
Rafael Espindolafafe4b72011-12-30 03:11:50 +00002995 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002996
Richard Smith2d406342011-10-22 21:10:00 +00002997 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00002998 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00002999 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00003000 bool VisitInitListExpr(const InitListExpr *E);
3001 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003002 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00003003 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00003004 // shufflevector, ExtVectorElementExpr
3005 // (Note that these require implementing conversions
3006 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003007 };
3008} // end anonymous namespace
3009
3010static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003011 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00003012 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003013}
3014
Richard Smith2d406342011-10-22 21:10:00 +00003015bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3016 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003017 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003018
Richard Smith161f09a2011-12-06 22:44:34 +00003019 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00003020 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003021
Eli Friedmanc757de22011-03-25 00:43:55 +00003022 switch (E->getCastKind()) {
3023 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00003024 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00003025 if (SETy->isIntegerType()) {
3026 APSInt IntResult;
3027 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003028 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003029 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00003030 } else if (SETy->isRealFloatingType()) {
3031 APFloat F(0.0);
3032 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003033 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003034 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00003035 } else {
Richard Smith2d406342011-10-22 21:10:00 +00003036 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003037 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003038
3039 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00003040 SmallVector<APValue, 4> Elts(NElts, Val);
3041 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00003042 }
Eli Friedman803acb32011-12-22 03:51:45 +00003043 case CK_BitCast: {
3044 // Evaluate the operand into an APInt we can extract from.
3045 llvm::APInt SValInt;
3046 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3047 return false;
3048 // Extract the elements
3049 QualType EltTy = VTy->getElementType();
3050 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3051 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3052 SmallVector<APValue, 4> Elts;
3053 if (EltTy->isRealFloatingType()) {
3054 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3055 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3056 unsigned FloatEltSize = EltSize;
3057 if (&Sem == &APFloat::x87DoubleExtended)
3058 FloatEltSize = 80;
3059 for (unsigned i = 0; i < NElts; i++) {
3060 llvm::APInt Elt;
3061 if (BigEndian)
3062 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3063 else
3064 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3065 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3066 }
3067 } else if (EltTy->isIntegerType()) {
3068 for (unsigned i = 0; i < NElts; i++) {
3069 llvm::APInt Elt;
3070 if (BigEndian)
3071 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3072 else
3073 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3074 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3075 }
3076 } else {
3077 return Error(E);
3078 }
3079 return Success(Elts, E);
3080 }
Eli Friedmanc757de22011-03-25 00:43:55 +00003081 default:
Richard Smith11562c52011-10-28 17:51:58 +00003082 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003083 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003084}
3085
Richard Smith2d406342011-10-22 21:10:00 +00003086bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003087VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003088 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003089 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00003090 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003091
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003092 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003093 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003094
John McCall875679e2010-06-11 17:54:15 +00003095 // If a vector is initialized with a single element, that value
3096 // becomes every element of the vector, not just the first.
3097 // This is the behavior described in the IBM AltiVec documentation.
3098 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00003099
3100 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00003101 // vector (OpenCL 6.1.6).
3102 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00003103 return Visit(E->getInit(0));
3104
John McCall875679e2010-06-11 17:54:15 +00003105 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003106 if (EltTy->isIntegerType()) {
3107 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00003108 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003109 return false;
John McCall875679e2010-06-11 17:54:15 +00003110 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003111 } else {
3112 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00003113 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003114 return false;
John McCall875679e2010-06-11 17:54:15 +00003115 InitValue = APValue(f);
3116 }
3117 for (unsigned i = 0; i < NumElements; i++) {
3118 Elements.push_back(InitValue);
3119 }
3120 } else {
3121 for (unsigned i = 0; i < NumElements; i++) {
3122 if (EltTy->isIntegerType()) {
3123 llvm::APSInt sInt(32);
3124 if (i < NumInits) {
3125 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003126 return false;
John McCall875679e2010-06-11 17:54:15 +00003127 } else {
3128 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3129 }
3130 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00003131 } else {
John McCall875679e2010-06-11 17:54:15 +00003132 llvm::APFloat f(0.0);
3133 if (i < NumInits) {
3134 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003135 return false;
John McCall875679e2010-06-11 17:54:15 +00003136 } else {
3137 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3138 }
3139 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00003140 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003141 }
3142 }
Richard Smith2d406342011-10-22 21:10:00 +00003143 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003144}
3145
Richard Smith2d406342011-10-22 21:10:00 +00003146bool
Rafael Espindolafafe4b72011-12-30 03:11:50 +00003147VectorExprEvaluator::ValueInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003148 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00003149 QualType EltTy = VT->getElementType();
3150 APValue ZeroElement;
3151 if (EltTy->isIntegerType())
3152 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3153 else
3154 ZeroElement =
3155 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3156
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003157 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00003158 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003159}
3160
Richard Smith2d406342011-10-22 21:10:00 +00003161bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00003162 VisitIgnoredValue(E->getSubExpr());
Rafael Espindolafafe4b72011-12-30 03:11:50 +00003163 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003164}
3165
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003166//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00003167// Array Evaluation
3168//===----------------------------------------------------------------------===//
3169
3170namespace {
3171 class ArrayExprEvaluator
3172 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00003173 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00003174 APValue &Result;
3175 public:
3176
Richard Smithd62306a2011-11-10 06:34:14 +00003177 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3178 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00003179
3180 bool Success(const APValue &V, const Expr *E) {
3181 assert(V.isArray() && "Expected array type");
3182 Result = V;
3183 return true;
3184 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003185
Rafael Espindolafafe4b72011-12-30 03:11:50 +00003186 bool ValueInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003187 const ConstantArrayType *CAT =
3188 Info.Ctx.getAsConstantArrayType(E->getType());
3189 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003190 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003191
3192 Result = APValue(APValue::UninitArray(), 0,
3193 CAT->getSize().getZExtValue());
3194 if (!Result.hasArrayFiller()) return true;
3195
Rafael Espindolafafe4b72011-12-30 03:11:50 +00003196 // Value-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00003197 LValue Subobject = This;
3198 Subobject.Designator.addIndex(0);
3199 ImplicitValueInitExpr VIE(CAT->getElementType());
3200 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3201 Subobject, &VIE);
3202 }
3203
Richard Smithf3e9e432011-11-07 09:22:26 +00003204 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00003205 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003206 };
3207} // end anonymous namespace
3208
Richard Smithd62306a2011-11-10 06:34:14 +00003209static bool EvaluateArray(const Expr *E, const LValue &This,
3210 APValue &Result, EvalInfo &Info) {
Rafael Espindolafafe4b72011-12-30 03:11:50 +00003211 assert(E->isRValue() && E->getType()->isArrayType() &&
3212 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00003213 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003214}
3215
3216bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3217 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3218 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003219 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003220
Richard Smithca2cfbf2011-12-22 01:07:19 +00003221 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3222 // an appropriately-typed string literal enclosed in braces.
3223 if (E->getNumInits() == 1 && CAT->getElementType()->isAnyCharacterType() &&
3224 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3225 LValue LV;
3226 if (!EvaluateLValue(E->getInit(0), LV, Info))
3227 return false;
3228 uint64_t NumElements = CAT->getSize().getZExtValue();
3229 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3230
3231 // Copy the string literal into the array. FIXME: Do this better.
3232 LV.Designator.addIndex(0);
3233 for (uint64_t I = 0; I < NumElements; ++I) {
3234 CCValue Char;
3235 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3236 CAT->getElementType(), LV, Char))
3237 return false;
3238 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3239 Result.getArrayInitializedElt(I)))
3240 return false;
3241 if (!HandleLValueArrayAdjustment(Info, LV, CAT->getElementType(), 1))
3242 return false;
3243 }
3244 return true;
3245 }
3246
Richard Smithf3e9e432011-11-07 09:22:26 +00003247 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3248 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00003249 LValue Subobject = This;
3250 Subobject.Designator.addIndex(0);
3251 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00003252 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00003253 I != End; ++I, ++Index) {
3254 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3255 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00003256 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003257 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
3258 return false;
3259 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003260
3261 if (!Result.hasArrayFiller()) return true;
3262 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00003263 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3264 // but sometimes does:
3265 // struct S { constexpr S() : p(&p) {} void *p; };
3266 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00003267 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00003268 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00003269}
3270
Richard Smith027bf112011-11-17 22:56:20 +00003271bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3272 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3273 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003274 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003275
3276 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3277 if (!Result.hasArrayFiller())
3278 return true;
3279
3280 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00003281
Rafael Espindolafafe4b72011-12-30 03:11:50 +00003282 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD)) {
Richard Smithcc36f692011-12-22 02:22:31 +00003283 const CXXRecordDecl *RD = FD->getParent();
3284 if (RD->isUnion())
3285 Result.getArrayFiller() = APValue((FieldDecl*)0);
3286 else
3287 Result.getArrayFiller() =
3288 APValue(APValue::UninitStruct(), RD->getNumBases(),
3289 std::distance(RD->field_begin(), RD->field_end()));
3290 return true;
3291 }
3292
Richard Smith027bf112011-11-17 22:56:20 +00003293 const FunctionDecl *Definition = 0;
3294 FD->getBody(Definition);
3295
Richard Smith357362d2011-12-13 06:39:58 +00003296 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3297 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003298
3299 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3300 // but sometimes does:
3301 // struct S { constexpr S() : p(&p) {} void *p; };
3302 // S s[10];
3303 LValue Subobject = This;
3304 Subobject.Designator.addIndex(0);
3305 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00003306 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003307 cast<CXXConstructorDecl>(Definition),
3308 Info, Result.getArrayFiller());
3309}
3310
Richard Smithf3e9e432011-11-07 09:22:26 +00003311//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003312// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003313//
3314// As a GNU extension, we support casting pointers to sufficiently-wide integer
3315// types and back in constant folding. Integer values are thus represented
3316// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003317//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003318
3319namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003320class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003321 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003322 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003323public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00003324 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003325 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003326
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003327 bool Success(const llvm::APSInt &SI, const Expr *E) {
3328 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003329 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003330 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003331 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003332 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003333 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003334 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003335 return true;
3336 }
3337
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003338 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003339 assert(E->getType()->isIntegralOrEnumerationType() &&
3340 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003341 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003342 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003343 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003344 Result.getInt().setIsUnsigned(
3345 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003346 return true;
3347 }
3348
3349 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003350 assert(E->getType()->isIntegralOrEnumerationType() &&
3351 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00003352 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003353 return true;
3354 }
3355
Ken Dyckdbc01912011-03-11 02:13:43 +00003356 bool Success(CharUnits Size, const Expr *E) {
3357 return Success(Size.getQuantity(), E);
3358 }
3359
Richard Smith0b0a0b62011-10-29 20:57:55 +00003360 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00003361 if (V.isLValue()) {
3362 Result = V;
3363 return true;
3364 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003365 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003366 }
Mike Stump11289f42009-09-09 15:08:12 +00003367
Rafael Espindolafafe4b72011-12-30 03:11:50 +00003368 bool ValueInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00003369
Peter Collingbournee9200682011-05-13 03:29:01 +00003370 //===--------------------------------------------------------------------===//
3371 // Visitor Methods
3372 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003373
Chris Lattner7174bf32008-07-12 00:38:25 +00003374 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003375 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003376 }
3377 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003378 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003379 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003380
3381 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3382 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003383 if (CheckReferencedDecl(E, E->getDecl()))
3384 return true;
3385
3386 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003387 }
3388 bool VisitMemberExpr(const MemberExpr *E) {
3389 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00003390 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003391 return true;
3392 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003393
3394 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003395 }
3396
Peter Collingbournee9200682011-05-13 03:29:01 +00003397 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003398 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00003399 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00003400 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00003401
Peter Collingbournee9200682011-05-13 03:29:01 +00003402 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003403 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00003404
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003405 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003406 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003407 }
Mike Stump11289f42009-09-09 15:08:12 +00003408
Richard Smith4ce706a2011-10-11 21:43:33 +00003409 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00003410 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Rafael Espindolafafe4b72011-12-30 03:11:50 +00003411 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003412 }
3413
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003414 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003415 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003416 }
3417
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003418 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3419 return Success(E->getValue(), E);
3420 }
3421
John Wiegley6242b6a2011-04-28 00:16:57 +00003422 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3423 return Success(E->getValue(), E);
3424 }
3425
John Wiegleyf9f65842011-04-25 06:54:41 +00003426 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3427 return Success(E->getValue(), E);
3428 }
3429
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003430 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003431 bool VisitUnaryImag(const UnaryOperator *E);
3432
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003433 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003434 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00003435
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003436private:
Ken Dyck160146e2010-01-27 17:10:57 +00003437 CharUnits GetAlignOfExpr(const Expr *E);
3438 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00003439 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00003440 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00003441 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00003442};
Chris Lattner05706e882008-07-11 18:11:29 +00003443} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003444
Richard Smith11562c52011-10-28 17:51:58 +00003445/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3446/// produce either the integer value or a pointer.
3447///
3448/// GCC has a heinous extension which folds casts between pointer types and
3449/// pointer-sized integral types. We support this by allowing the evaluation of
3450/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3451/// Some simple arithmetic on such values is supported (they are treated much
3452/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00003453static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00003454 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003455 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003456 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00003457}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003458
Richard Smithf57d8cb2011-12-09 22:58:01 +00003459static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003460 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003461 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00003462 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003463 if (!Val.isInt()) {
3464 // FIXME: It would be better to produce the diagnostic for casting
3465 // a pointer to an integer.
Richard Smith92b1ce02011-12-12 09:28:41 +00003466 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003467 return false;
3468 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003469 Result = Val.getInt();
3470 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003471}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003472
Richard Smithf57d8cb2011-12-09 22:58:01 +00003473/// Check whether the given declaration can be directly converted to an integral
3474/// rvalue. If not, no diagnostic is produced; there are other things we can
3475/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003476bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003477 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003478 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003479 // Check for signedness/width mismatches between E type and ECD value.
3480 bool SameSign = (ECD->getInitVal().isSigned()
3481 == E->getType()->isSignedIntegerOrEnumerationType());
3482 bool SameWidth = (ECD->getInitVal().getBitWidth()
3483 == Info.Ctx.getIntWidth(E->getType()));
3484 if (SameSign && SameWidth)
3485 return Success(ECD->getInitVal(), E);
3486 else {
3487 // Get rid of mismatch (otherwise Success assertions will fail)
3488 // by computing a new value matching the type of E.
3489 llvm::APSInt Val = ECD->getInitVal();
3490 if (!SameSign)
3491 Val.setIsSigned(!ECD->getInitVal().isSigned());
3492 if (!SameWidth)
3493 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3494 return Success(Val, E);
3495 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003496 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003497 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003498}
3499
Chris Lattner86ee2862008-10-06 06:40:35 +00003500/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3501/// as GCC.
3502static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3503 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003504 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003505 enum gcc_type_class {
3506 no_type_class = -1,
3507 void_type_class, integer_type_class, char_type_class,
3508 enumeral_type_class, boolean_type_class,
3509 pointer_type_class, reference_type_class, offset_type_class,
3510 real_type_class, complex_type_class,
3511 function_type_class, method_type_class,
3512 record_type_class, union_type_class,
3513 array_type_class, string_type_class,
3514 lang_type_class
3515 };
Mike Stump11289f42009-09-09 15:08:12 +00003516
3517 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003518 // ideal, however it is what gcc does.
3519 if (E->getNumArgs() == 0)
3520 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003521
Chris Lattner86ee2862008-10-06 06:40:35 +00003522 QualType ArgTy = E->getArg(0)->getType();
3523 if (ArgTy->isVoidType())
3524 return void_type_class;
3525 else if (ArgTy->isEnumeralType())
3526 return enumeral_type_class;
3527 else if (ArgTy->isBooleanType())
3528 return boolean_type_class;
3529 else if (ArgTy->isCharType())
3530 return string_type_class; // gcc doesn't appear to use char_type_class
3531 else if (ArgTy->isIntegerType())
3532 return integer_type_class;
3533 else if (ArgTy->isPointerType())
3534 return pointer_type_class;
3535 else if (ArgTy->isReferenceType())
3536 return reference_type_class;
3537 else if (ArgTy->isRealType())
3538 return real_type_class;
3539 else if (ArgTy->isComplexType())
3540 return complex_type_class;
3541 else if (ArgTy->isFunctionType())
3542 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003543 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003544 return record_type_class;
3545 else if (ArgTy->isUnionType())
3546 return union_type_class;
3547 else if (ArgTy->isArrayType())
3548 return array_type_class;
3549 else if (ArgTy->isUnionType())
3550 return union_type_class;
3551 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003552 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003553 return -1;
3554}
3555
Richard Smith5fab0c92011-12-28 19:48:30 +00003556/// EvaluateBuiltinConstantPForLValue - Determine the result of
3557/// __builtin_constant_p when applied to the given lvalue.
3558///
3559/// An lvalue is only "constant" if it is a pointer or reference to the first
3560/// character of a string literal.
3561template<typename LValue>
3562static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3563 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3564 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3565}
3566
3567/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3568/// GCC as we can manage.
3569static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3570 QualType ArgType = Arg->getType();
3571
3572 // __builtin_constant_p always has one operand. The rules which gcc follows
3573 // are not precisely documented, but are as follows:
3574 //
3575 // - If the operand is of integral, floating, complex or enumeration type,
3576 // and can be folded to a known value of that type, it returns 1.
3577 // - If the operand and can be folded to a pointer to the first character
3578 // of a string literal (or such a pointer cast to an integral type), it
3579 // returns 1.
3580 //
3581 // Otherwise, it returns 0.
3582 //
3583 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3584 // its support for this does not currently work.
3585 if (ArgType->isIntegralOrEnumerationType()) {
3586 Expr::EvalResult Result;
3587 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3588 return false;
3589
3590 APValue &V = Result.Val;
3591 if (V.getKind() == APValue::Int)
3592 return true;
3593
3594 return EvaluateBuiltinConstantPForLValue(V);
3595 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3596 return Arg->isEvaluatable(Ctx);
3597 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3598 LValue LV;
3599 Expr::EvalStatus Status;
3600 EvalInfo Info(Ctx, Status);
3601 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3602 : EvaluatePointer(Arg, LV, Info)) &&
3603 !Status.HasSideEffects)
3604 return EvaluateBuiltinConstantPForLValue(LV);
3605 }
3606
3607 // Anything else isn't considered to be sufficiently constant.
3608 return false;
3609}
3610
John McCall95007602010-05-10 23:27:23 +00003611/// Retrieves the "underlying object type" of the given expression,
3612/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003613QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3614 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3615 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003616 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003617 } else if (const Expr *E = B.get<const Expr*>()) {
3618 if (isa<CompoundLiteralExpr>(E))
3619 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003620 }
3621
3622 return QualType();
3623}
3624
Peter Collingbournee9200682011-05-13 03:29:01 +00003625bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003626 // TODO: Perhaps we should let LLVM lower this?
3627 LValue Base;
3628 if (!EvaluatePointer(E->getArg(0), Base, Info))
3629 return false;
3630
3631 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003632 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003633
Richard Smithce40ad62011-11-12 22:28:03 +00003634 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003635 if (T.isNull() ||
3636 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003637 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003638 T->isVariablyModifiedType() ||
3639 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003640 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003641
3642 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3643 CharUnits Offset = Base.getLValueOffset();
3644
3645 if (!Offset.isNegative() && Offset <= Size)
3646 Size -= Offset;
3647 else
3648 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003649 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003650}
3651
Peter Collingbournee9200682011-05-13 03:29:01 +00003652bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003653 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003654 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003655 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003656
3657 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003658 if (TryEvaluateBuiltinObjectSize(E))
3659 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003660
Eric Christopher99469702010-01-19 22:58:35 +00003661 // If evaluating the argument has side-effects we can't determine
3662 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003663 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003664 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003665 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003666 return Success(0, E);
3667 }
Mike Stump876387b2009-10-27 22:09:17 +00003668
Richard Smithf57d8cb2011-12-09 22:58:01 +00003669 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003670 }
3671
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003672 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003673 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003674
Richard Smith5fab0c92011-12-28 19:48:30 +00003675 case Builtin::BI__builtin_constant_p:
3676 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00003677
Chris Lattnerd545ad12009-09-23 06:06:36 +00003678 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003679 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003680 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003681 return Success(Operand, E);
3682 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003683
3684 case Builtin::BI__builtin_expect:
3685 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003686
3687 case Builtin::BIstrlen:
3688 case Builtin::BI__builtin_strlen:
3689 // As an extension, we support strlen() and __builtin_strlen() as constant
3690 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003691 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003692 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3693 // The string literal may have embedded null characters. Find the first
3694 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003695 StringRef Str = S->getString();
3696 StringRef::size_type Pos = Str.find(0);
3697 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003698 Str = Str.substr(0, Pos);
3699
3700 return Success(Str.size(), E);
3701 }
3702
Richard Smithf57d8cb2011-12-09 22:58:01 +00003703 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003704
3705 case Builtin::BI__atomic_is_lock_free: {
3706 APSInt SizeVal;
3707 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3708 return false;
3709
3710 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3711 // of two less than the maximum inline atomic width, we know it is
3712 // lock-free. If the size isn't a power of two, or greater than the
3713 // maximum alignment where we promote atomics, we know it is not lock-free
3714 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3715 // the answer can only be determined at runtime; for example, 16-byte
3716 // atomics have lock-free implementations on some, but not all,
3717 // x86-64 processors.
3718
3719 // Check power-of-two.
3720 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3721 if (!Size.isPowerOfTwo())
3722#if 0
3723 // FIXME: Suppress this folding until the ABI for the promotion width
3724 // settles.
3725 return Success(0, E);
3726#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003727 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003728#endif
3729
3730#if 0
3731 // Check against promotion width.
3732 // FIXME: Suppress this folding until the ABI for the promotion width
3733 // settles.
3734 unsigned PromoteWidthBits =
3735 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3736 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3737 return Success(0, E);
3738#endif
3739
3740 // Check against inlining width.
3741 unsigned InlineWidthBits =
3742 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3743 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3744 return Success(1, E);
3745
Richard Smithf57d8cb2011-12-09 22:58:01 +00003746 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003747 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003748 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003749}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003750
Richard Smith8b3497e2011-10-31 01:37:14 +00003751static bool HasSameBase(const LValue &A, const LValue &B) {
3752 if (!A.getLValueBase())
3753 return !B.getLValueBase();
3754 if (!B.getLValueBase())
3755 return false;
3756
Richard Smithce40ad62011-11-12 22:28:03 +00003757 if (A.getLValueBase().getOpaqueValue() !=
3758 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003759 const Decl *ADecl = GetLValueBaseDecl(A);
3760 if (!ADecl)
3761 return false;
3762 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003763 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003764 return false;
3765 }
3766
3767 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003768 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003769}
3770
Chris Lattnere13042c2008-07-11 19:10:17 +00003771bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003772 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003773 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003774
John McCalle3027922010-08-25 11:45:40 +00003775 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003776 VisitIgnoredValue(E->getLHS());
3777 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003778 }
3779
3780 if (E->isLogicalOp()) {
3781 // These need to be handled specially because the operands aren't
3782 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003783 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003784
Richard Smith11562c52011-10-28 17:51:58 +00003785 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003786 // We were able to evaluate the LHS, see if we can get away with not
3787 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003788 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003789 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003790
Richard Smith11562c52011-10-28 17:51:58 +00003791 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003792 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003793 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003794 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003795 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003796 }
3797 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003798 // FIXME: If both evaluations fail, we should produce the diagnostic from
3799 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3800 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003801 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003802 // We can't evaluate the LHS; however, sometimes the result
3803 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003804 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003805 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003806 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00003807 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003808
3809 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003810 }
3811 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00003812 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00003813
Eli Friedman5a332ea2008-11-13 06:09:17 +00003814 return false;
3815 }
3816
Anders Carlssonacc79812008-11-16 07:17:21 +00003817 QualType LHSTy = E->getLHS()->getType();
3818 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003819
3820 if (LHSTy->isAnyComplexType()) {
3821 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00003822 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003823
3824 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3825 return false;
3826
3827 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3828 return false;
3829
3830 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00003831 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003832 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00003833 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003834 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3835
John McCalle3027922010-08-25 11:45:40 +00003836 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003837 return Success((CR_r == APFloat::cmpEqual &&
3838 CR_i == APFloat::cmpEqual), E);
3839 else {
John McCalle3027922010-08-25 11:45:40 +00003840 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003841 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00003842 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003843 CR_r == APFloat::cmpLessThan ||
3844 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00003845 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003846 CR_i == APFloat::cmpLessThan ||
3847 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003848 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003849 } else {
John McCalle3027922010-08-25 11:45:40 +00003850 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003851 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3852 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3853 else {
John McCalle3027922010-08-25 11:45:40 +00003854 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003855 "Invalid compex comparison.");
3856 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3857 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3858 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003859 }
3860 }
Mike Stump11289f42009-09-09 15:08:12 +00003861
Anders Carlssonacc79812008-11-16 07:17:21 +00003862 if (LHSTy->isRealFloatingType() &&
3863 RHSTy->isRealFloatingType()) {
3864 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00003865
Anders Carlssonacc79812008-11-16 07:17:21 +00003866 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3867 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003868
Anders Carlssonacc79812008-11-16 07:17:21 +00003869 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3870 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003871
Anders Carlssonacc79812008-11-16 07:17:21 +00003872 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00003873
Anders Carlssonacc79812008-11-16 07:17:21 +00003874 switch (E->getOpcode()) {
3875 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003876 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00003877 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003878 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00003879 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003880 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00003881 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003882 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003883 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00003884 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003885 E);
John McCalle3027922010-08-25 11:45:40 +00003886 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003887 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003888 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00003889 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00003890 || CR == APFloat::cmpLessThan
3891 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00003892 }
Anders Carlssonacc79812008-11-16 07:17:21 +00003893 }
Mike Stump11289f42009-09-09 15:08:12 +00003894
Eli Friedmana38da572009-04-28 19:17:36 +00003895 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003896 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00003897 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003898 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3899 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003900
John McCall45d55e42010-05-07 21:00:08 +00003901 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003902 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3903 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003904
Richard Smith8b3497e2011-10-31 01:37:14 +00003905 // Reject differing bases from the normal codepath; we special-case
3906 // comparisons to null.
3907 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00003908 // Inequalities and subtractions between unrelated pointers have
3909 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00003910 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003911 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003912 // A constant address may compare equal to the address of a symbol.
3913 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00003914 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003915 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3916 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003917 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003918 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00003919 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00003920 // distinct. However, we do know that the address of a literal will be
3921 // non-null.
3922 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
3923 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003924 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003925 // We can't tell whether weak symbols will end up pointing to the same
3926 // object.
3927 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003928 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003929 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00003930 // (Note that clang defaults to -fmerge-all-constants, which can
3931 // lead to inconsistent results for comparisons involving the address
3932 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00003933 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00003934 }
Eli Friedman64004332009-03-23 04:38:34 +00003935
Richard Smithf3e9e432011-11-07 09:22:26 +00003936 // FIXME: Implement the C++11 restrictions:
3937 // - Pointer subtractions must be on elements of the same array.
3938 // - Pointer comparisons must be between members with the same access.
3939
John McCalle3027922010-08-25 11:45:40 +00003940 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00003941 QualType Type = E->getLHS()->getType();
3942 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003943
Richard Smithd62306a2011-11-10 06:34:14 +00003944 CharUnits ElementSize;
3945 if (!HandleSizeof(Info, ElementType, ElementSize))
3946 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003947
Richard Smithd62306a2011-11-10 06:34:14 +00003948 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00003949 RHSValue.getLValueOffset();
3950 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003951 }
Richard Smith8b3497e2011-10-31 01:37:14 +00003952
3953 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
3954 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
3955 switch (E->getOpcode()) {
3956 default: llvm_unreachable("missing comparison operator");
3957 case BO_LT: return Success(LHSOffset < RHSOffset, E);
3958 case BO_GT: return Success(LHSOffset > RHSOffset, E);
3959 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
3960 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
3961 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
3962 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003963 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003964 }
3965 }
Douglas Gregorb90df602010-06-16 00:17:44 +00003966 if (!LHSTy->isIntegralOrEnumerationType() ||
3967 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00003968 // We can't continue from here for non-integral types.
3969 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003970 }
3971
Anders Carlsson9c181652008-07-08 14:35:21 +00003972 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00003973 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00003974 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003975 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00003976
Richard Smith11562c52011-10-28 17:51:58 +00003977 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003978 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003979 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00003980
3981 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00003982 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00003983 CharUnits AdditionalOffset = CharUnits::fromQuantity(
3984 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00003985 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00003986 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00003987 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00003988 LHSVal.getLValueOffset() -= AdditionalOffset;
3989 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00003990 return true;
3991 }
3992
3993 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00003994 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00003995 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003996 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
3997 LHSVal.getInt().getZExtValue());
3998 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00003999 return true;
4000 }
4001
4002 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00004003 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004004 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004005
Richard Smith11562c52011-10-28 17:51:58 +00004006 APSInt &LHS = LHSVal.getInt();
4007 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00004008
Anders Carlsson9c181652008-07-08 14:35:21 +00004009 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00004010 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004011 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004012 case BO_Mul: return Success(LHS * RHS, E);
4013 case BO_Add: return Success(LHS + RHS, E);
4014 case BO_Sub: return Success(LHS - RHS, E);
4015 case BO_And: return Success(LHS & RHS, E);
4016 case BO_Xor: return Success(LHS ^ RHS, E);
4017 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004018 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00004019 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004020 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004021 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004022 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00004023 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004024 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00004025 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00004026 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00004027 // During constant-folding, a negative shift is an opposite shift.
4028 if (RHS.isSigned() && RHS.isNegative()) {
4029 RHS = -RHS;
4030 goto shift_right;
4031 }
4032
4033 shift_left:
4034 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00004035 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4036 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004037 }
John McCalle3027922010-08-25 11:45:40 +00004038 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00004039 // During constant-folding, a negative shift is an opposite shift.
4040 if (RHS.isSigned() && RHS.isNegative()) {
4041 RHS = -RHS;
4042 goto shift_left;
4043 }
4044
4045 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00004046 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00004047 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4048 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004049 }
Mike Stump11289f42009-09-09 15:08:12 +00004050
Richard Smith11562c52011-10-28 17:51:58 +00004051 case BO_LT: return Success(LHS < RHS, E);
4052 case BO_GT: return Success(LHS > RHS, E);
4053 case BO_LE: return Success(LHS <= RHS, E);
4054 case BO_GE: return Success(LHS >= RHS, E);
4055 case BO_EQ: return Success(LHS == RHS, E);
4056 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00004057 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004058}
4059
Ken Dyck160146e2010-01-27 17:10:57 +00004060CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00004061 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4062 // the result is the size of the referenced type."
4063 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4064 // result shall be the alignment of the referenced type."
4065 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4066 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00004067
4068 // __alignof is defined to return the preferred alignment.
4069 return Info.Ctx.toCharUnitsFromBits(
4070 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00004071}
4072
Ken Dyck160146e2010-01-27 17:10:57 +00004073CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00004074 E = E->IgnoreParens();
4075
4076 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00004077 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00004078 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004079 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4080 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00004081
Chris Lattner68061312009-01-24 21:53:27 +00004082 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00004083 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4084 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00004085
Chris Lattner24aeeab2009-01-24 21:09:06 +00004086 return GetAlignOfType(E->getType());
4087}
4088
4089
Peter Collingbournee190dee2011-03-11 19:24:49 +00004090/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4091/// a result as the expression's type.
4092bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4093 const UnaryExprOrTypeTraitExpr *E) {
4094 switch(E->getKind()) {
4095 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00004096 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00004097 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004098 else
Ken Dyckdbc01912011-03-11 02:13:43 +00004099 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00004100 }
Eli Friedman64004332009-03-23 04:38:34 +00004101
Peter Collingbournee190dee2011-03-11 19:24:49 +00004102 case UETT_VecStep: {
4103 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00004104
Peter Collingbournee190dee2011-03-11 19:24:49 +00004105 if (Ty->isVectorType()) {
4106 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00004107
Peter Collingbournee190dee2011-03-11 19:24:49 +00004108 // The vec_step built-in functions that take a 3-component
4109 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4110 if (n == 3)
4111 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00004112
Peter Collingbournee190dee2011-03-11 19:24:49 +00004113 return Success(n, E);
4114 } else
4115 return Success(1, E);
4116 }
4117
4118 case UETT_SizeOf: {
4119 QualType SrcTy = E->getTypeOfArgument();
4120 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4121 // the result is the size of the referenced type."
4122 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4123 // result shall be the alignment of the referenced type."
4124 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4125 SrcTy = Ref->getPointeeType();
4126
Richard Smithd62306a2011-11-10 06:34:14 +00004127 CharUnits Sizeof;
4128 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00004129 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004130 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004131 }
4132 }
4133
4134 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004135 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004136}
4137
Peter Collingbournee9200682011-05-13 03:29:01 +00004138bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00004139 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00004140 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00004141 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004142 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00004143 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00004144 for (unsigned i = 0; i != n; ++i) {
4145 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4146 switch (ON.getKind()) {
4147 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00004148 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00004149 APSInt IdxResult;
4150 if (!EvaluateInteger(Idx, IdxResult, Info))
4151 return false;
4152 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4153 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004154 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004155 CurrentType = AT->getElementType();
4156 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4157 Result += IdxResult.getSExtValue() * ElementSize;
4158 break;
4159 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004160
Douglas Gregor882211c2010-04-28 22:16:22 +00004161 case OffsetOfExpr::OffsetOfNode::Field: {
4162 FieldDecl *MemberDecl = ON.getField();
4163 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004164 if (!RT)
4165 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004166 RecordDecl *RD = RT->getDecl();
4167 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00004168 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00004169 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00004170 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00004171 CurrentType = MemberDecl->getType().getNonReferenceType();
4172 break;
4173 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00004174
Douglas Gregor882211c2010-04-28 22:16:22 +00004175 case OffsetOfExpr::OffsetOfNode::Identifier:
4176 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004177 return Error(OOE);
4178
Douglas Gregord1702062010-04-29 00:18:15 +00004179 case OffsetOfExpr::OffsetOfNode::Base: {
4180 CXXBaseSpecifier *BaseSpec = ON.getBase();
4181 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004182 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004183
4184 // Find the layout of the class whose base we are looking into.
4185 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00004186 if (!RT)
4187 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004188 RecordDecl *RD = RT->getDecl();
4189 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4190
4191 // Find the base class itself.
4192 CurrentType = BaseSpec->getType();
4193 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4194 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004195 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00004196
4197 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00004198 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00004199 break;
4200 }
Douglas Gregor882211c2010-04-28 22:16:22 +00004201 }
4202 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004203 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00004204}
4205
Chris Lattnere13042c2008-07-11 19:10:17 +00004206bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004207 switch (E->getOpcode()) {
4208 default:
4209 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4210 // See C99 6.6p3.
4211 return Error(E);
4212 case UO_Extension:
4213 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4214 // If so, we could clear the diagnostic ID.
4215 return Visit(E->getSubExpr());
4216 case UO_Plus:
4217 // The result is just the value.
4218 return Visit(E->getSubExpr());
4219 case UO_Minus: {
4220 if (!Visit(E->getSubExpr()))
4221 return false;
4222 if (!Result.isInt()) return Error(E);
4223 return Success(-Result.getInt(), E);
4224 }
4225 case UO_Not: {
4226 if (!Visit(E->getSubExpr()))
4227 return false;
4228 if (!Result.isInt()) return Error(E);
4229 return Success(~Result.getInt(), E);
4230 }
4231 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00004232 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00004233 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00004234 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004235 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004236 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004237 }
Anders Carlsson9c181652008-07-08 14:35:21 +00004238}
Mike Stump11289f42009-09-09 15:08:12 +00004239
Chris Lattner477c4be2008-07-12 01:15:53 +00004240/// HandleCast - This is used to evaluate implicit or explicit casts where the
4241/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00004242bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4243 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004244 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00004245 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00004246
Eli Friedmanc757de22011-03-25 00:43:55 +00004247 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00004248 case CK_BaseToDerived:
4249 case CK_DerivedToBase:
4250 case CK_UncheckedDerivedToBase:
4251 case CK_Dynamic:
4252 case CK_ToUnion:
4253 case CK_ArrayToPointerDecay:
4254 case CK_FunctionToPointerDecay:
4255 case CK_NullToPointer:
4256 case CK_NullToMemberPointer:
4257 case CK_BaseToDerivedMemberPointer:
4258 case CK_DerivedToBaseMemberPointer:
4259 case CK_ConstructorConversion:
4260 case CK_IntegralToPointer:
4261 case CK_ToVoid:
4262 case CK_VectorSplat:
4263 case CK_IntegralToFloating:
4264 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004265 case CK_CPointerToObjCPointerCast:
4266 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004267 case CK_AnyPointerToBlockPointerCast:
4268 case CK_ObjCObjectLValueCast:
4269 case CK_FloatingRealToComplex:
4270 case CK_FloatingComplexToReal:
4271 case CK_FloatingComplexCast:
4272 case CK_FloatingComplexToIntegralComplex:
4273 case CK_IntegralRealToComplex:
4274 case CK_IntegralComplexCast:
4275 case CK_IntegralComplexToFloatingComplex:
4276 llvm_unreachable("invalid cast kind for integral value");
4277
Eli Friedman9faf2f92011-03-25 19:07:11 +00004278 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00004279 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004280 case CK_LValueBitCast:
4281 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00004282 case CK_ARCProduceObject:
4283 case CK_ARCConsumeObject:
4284 case CK_ARCReclaimReturnedObject:
4285 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004286 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004287
4288 case CK_LValueToRValue:
4289 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004290 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004291
4292 case CK_MemberPointerToBoolean:
4293 case CK_PointerToBoolean:
4294 case CK_IntegralToBoolean:
4295 case CK_FloatingToBoolean:
4296 case CK_FloatingComplexToBoolean:
4297 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004298 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00004299 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004300 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004301 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004302 }
4303
Eli Friedmanc757de22011-03-25 00:43:55 +00004304 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00004305 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00004306 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004307
Eli Friedman742421e2009-02-20 01:15:07 +00004308 if (!Result.isInt()) {
4309 // Only allow casts of lvalues if they are lossless.
4310 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4311 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004312
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004313 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004314 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00004315 }
Mike Stump11289f42009-09-09 15:08:12 +00004316
Eli Friedmanc757de22011-03-25 00:43:55 +00004317 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004318 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4319
John McCall45d55e42010-05-07 21:00:08 +00004320 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00004321 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00004322 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00004323
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004324 if (LV.getLValueBase()) {
4325 // Only allow based lvalue casts if they are lossless.
4326 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004327 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004328
Richard Smithcf74da72011-11-16 07:18:12 +00004329 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004330 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004331 return true;
4332 }
4333
Ken Dyck02990832010-01-15 12:37:54 +00004334 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4335 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00004336 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004337 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004338
Eli Friedmanc757de22011-03-25 00:43:55 +00004339 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00004340 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004341 if (!EvaluateComplex(SubExpr, C, Info))
4342 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00004343 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00004344 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00004345
Eli Friedmanc757de22011-03-25 00:43:55 +00004346 case CK_FloatingToIntegral: {
4347 APFloat F(0.0);
4348 if (!EvaluateFloat(SubExpr, F, Info))
4349 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00004350
Richard Smith357362d2011-12-13 06:39:58 +00004351 APSInt Value;
4352 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4353 return false;
4354 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00004355 }
4356 }
Mike Stump11289f42009-09-09 15:08:12 +00004357
Eli Friedmanc757de22011-03-25 00:43:55 +00004358 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004359 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00004360}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004361
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004362bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4363 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004364 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004365 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4366 return false;
4367 if (!LV.isComplexInt())
4368 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004369 return Success(LV.getComplexIntReal(), E);
4370 }
4371
4372 return Visit(E->getSubExpr());
4373}
4374
Eli Friedman4e7a2412009-02-27 04:45:43 +00004375bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004376 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00004377 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004378 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4379 return false;
4380 if (!LV.isComplexInt())
4381 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004382 return Success(LV.getComplexIntImag(), E);
4383 }
4384
Richard Smith4a678122011-10-24 18:44:57 +00004385 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00004386 return Success(0, E);
4387}
4388
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004389bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4390 return Success(E->getPackLength(), E);
4391}
4392
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004393bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4394 return Success(E->getValue(), E);
4395}
4396
Chris Lattner05706e882008-07-11 18:11:29 +00004397//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00004398// Float Evaluation
4399//===----------------------------------------------------------------------===//
4400
4401namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004402class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004403 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00004404 APFloat &Result;
4405public:
4406 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004407 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00004408
Richard Smith0b0a0b62011-10-29 20:57:55 +00004409 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004410 Result = V.getFloat();
4411 return true;
4412 }
Eli Friedman24c01542008-08-22 00:06:13 +00004413
Rafael Espindolafafe4b72011-12-30 03:11:50 +00004414 bool ValueInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00004415 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4416 return true;
4417 }
4418
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004419 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004420
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004421 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00004422 bool VisitBinaryOperator(const BinaryOperator *E);
4423 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004424 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00004425
John McCallb1fb0d32010-05-07 22:08:54 +00004426 bool VisitUnaryReal(const UnaryOperator *E);
4427 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00004428
Rafael Espindolafafe4b72011-12-30 03:11:50 +00004429 // FIXME: Missing: array subscript of vector, member of vector,
4430 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00004431};
4432} // end anonymous namespace
4433
4434static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004435 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004436 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00004437}
4438
Jay Foad39c79802011-01-12 09:06:06 +00004439static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00004440 QualType ResultTy,
4441 const Expr *Arg,
4442 bool SNaN,
4443 llvm::APFloat &Result) {
4444 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4445 if (!S) return false;
4446
4447 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4448
4449 llvm::APInt fill;
4450
4451 // Treat empty strings as if they were zero.
4452 if (S->getString().empty())
4453 fill = llvm::APInt(32, 0);
4454 else if (S->getString().getAsInteger(0, fill))
4455 return false;
4456
4457 if (SNaN)
4458 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4459 else
4460 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4461 return true;
4462}
4463
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004464bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004465 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004466 default:
4467 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4468
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004469 case Builtin::BI__builtin_huge_val:
4470 case Builtin::BI__builtin_huge_valf:
4471 case Builtin::BI__builtin_huge_vall:
4472 case Builtin::BI__builtin_inf:
4473 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004474 case Builtin::BI__builtin_infl: {
4475 const llvm::fltSemantics &Sem =
4476 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00004477 Result = llvm::APFloat::getInf(Sem);
4478 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00004479 }
Mike Stump11289f42009-09-09 15:08:12 +00004480
John McCall16291492010-02-28 13:00:19 +00004481 case Builtin::BI__builtin_nans:
4482 case Builtin::BI__builtin_nansf:
4483 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004484 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4485 true, Result))
4486 return Error(E);
4487 return true;
John McCall16291492010-02-28 13:00:19 +00004488
Chris Lattner0b7282e2008-10-06 06:31:58 +00004489 case Builtin::BI__builtin_nan:
4490 case Builtin::BI__builtin_nanf:
4491 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00004492 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00004493 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004494 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4495 false, Result))
4496 return Error(E);
4497 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004498
4499 case Builtin::BI__builtin_fabs:
4500 case Builtin::BI__builtin_fabsf:
4501 case Builtin::BI__builtin_fabsl:
4502 if (!EvaluateFloat(E->getArg(0), Result, Info))
4503 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004504
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004505 if (Result.isNegative())
4506 Result.changeSign();
4507 return true;
4508
Mike Stump11289f42009-09-09 15:08:12 +00004509 case Builtin::BI__builtin_copysign:
4510 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004511 case Builtin::BI__builtin_copysignl: {
4512 APFloat RHS(0.);
4513 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4514 !EvaluateFloat(E->getArg(1), RHS, Info))
4515 return false;
4516 Result.copySign(RHS);
4517 return true;
4518 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004519 }
4520}
4521
John McCallb1fb0d32010-05-07 22:08:54 +00004522bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004523 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4524 ComplexValue CV;
4525 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4526 return false;
4527 Result = CV.FloatReal;
4528 return true;
4529 }
4530
4531 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004532}
4533
4534bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004535 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4536 ComplexValue CV;
4537 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4538 return false;
4539 Result = CV.FloatImag;
4540 return true;
4541 }
4542
Richard Smith4a678122011-10-24 18:44:57 +00004543 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004544 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4545 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004546 return true;
4547}
4548
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004549bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004550 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004551 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004552 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004553 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004554 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004555 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4556 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004557 Result.changeSign();
4558 return true;
4559 }
4560}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004561
Eli Friedman24c01542008-08-22 00:06:13 +00004562bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004563 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4564 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004565
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004566 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004567 if (!EvaluateFloat(E->getLHS(), Result, Info))
4568 return false;
4569 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4570 return false;
4571
4572 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004573 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004574 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004575 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4576 return true;
John McCalle3027922010-08-25 11:45:40 +00004577 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004578 Result.add(RHS, APFloat::rmNearestTiesToEven);
4579 return true;
John McCalle3027922010-08-25 11:45:40 +00004580 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004581 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4582 return true;
John McCalle3027922010-08-25 11:45:40 +00004583 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004584 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4585 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004586 }
4587}
4588
4589bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4590 Result = E->getValue();
4591 return true;
4592}
4593
Peter Collingbournee9200682011-05-13 03:29:01 +00004594bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4595 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004596
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004597 switch (E->getCastKind()) {
4598 default:
Richard Smith11562c52011-10-28 17:51:58 +00004599 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004600
4601 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004602 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00004603 return EvaluateInteger(SubExpr, IntResult, Info) &&
4604 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4605 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004606 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004607
4608 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004609 if (!Visit(SubExpr))
4610 return false;
Richard Smith357362d2011-12-13 06:39:58 +00004611 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4612 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00004613 }
John McCalld7646252010-11-14 08:17:51 +00004614
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004615 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004616 ComplexValue V;
4617 if (!EvaluateComplex(SubExpr, V, Info))
4618 return false;
4619 Result = V.getComplexFloatReal();
4620 return true;
4621 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004622 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004623
Richard Smithf57d8cb2011-12-09 22:58:01 +00004624 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004625}
4626
Eli Friedman24c01542008-08-22 00:06:13 +00004627//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004628// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004629//===----------------------------------------------------------------------===//
4630
4631namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004632class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004633 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004634 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004635
Anders Carlsson537969c2008-11-16 20:27:53 +00004636public:
John McCall93d91dc2010-05-07 17:22:02 +00004637 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004638 : ExprEvaluatorBaseTy(info), Result(Result) {}
4639
Richard Smith0b0a0b62011-10-29 20:57:55 +00004640 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004641 Result.setFrom(V);
4642 return true;
4643 }
Mike Stump11289f42009-09-09 15:08:12 +00004644
Anders Carlsson537969c2008-11-16 20:27:53 +00004645 //===--------------------------------------------------------------------===//
4646 // Visitor Methods
4647 //===--------------------------------------------------------------------===//
4648
Peter Collingbournee9200682011-05-13 03:29:01 +00004649 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00004650
Peter Collingbournee9200682011-05-13 03:29:01 +00004651 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004652
John McCall93d91dc2010-05-07 17:22:02 +00004653 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004654 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004655 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00004656};
4657} // end anonymous namespace
4658
John McCall93d91dc2010-05-07 17:22:02 +00004659static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4660 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004661 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004662 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004663}
4664
Peter Collingbournee9200682011-05-13 03:29:01 +00004665bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4666 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004667
4668 if (SubExpr->getType()->isRealFloatingType()) {
4669 Result.makeComplexFloat();
4670 APFloat &Imag = Result.FloatImag;
4671 if (!EvaluateFloat(SubExpr, Imag, Info))
4672 return false;
4673
4674 Result.FloatReal = APFloat(Imag.getSemantics());
4675 return true;
4676 } else {
4677 assert(SubExpr->getType()->isIntegerType() &&
4678 "Unexpected imaginary literal.");
4679
4680 Result.makeComplexInt();
4681 APSInt &Imag = Result.IntImag;
4682 if (!EvaluateInteger(SubExpr, Imag, Info))
4683 return false;
4684
4685 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4686 return true;
4687 }
4688}
4689
Peter Collingbournee9200682011-05-13 03:29:01 +00004690bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004691
John McCallfcef3cf2010-12-14 17:51:41 +00004692 switch (E->getCastKind()) {
4693 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004694 case CK_BaseToDerived:
4695 case CK_DerivedToBase:
4696 case CK_UncheckedDerivedToBase:
4697 case CK_Dynamic:
4698 case CK_ToUnion:
4699 case CK_ArrayToPointerDecay:
4700 case CK_FunctionToPointerDecay:
4701 case CK_NullToPointer:
4702 case CK_NullToMemberPointer:
4703 case CK_BaseToDerivedMemberPointer:
4704 case CK_DerivedToBaseMemberPointer:
4705 case CK_MemberPointerToBoolean:
4706 case CK_ConstructorConversion:
4707 case CK_IntegralToPointer:
4708 case CK_PointerToIntegral:
4709 case CK_PointerToBoolean:
4710 case CK_ToVoid:
4711 case CK_VectorSplat:
4712 case CK_IntegralCast:
4713 case CK_IntegralToBoolean:
4714 case CK_IntegralToFloating:
4715 case CK_FloatingToIntegral:
4716 case CK_FloatingToBoolean:
4717 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004718 case CK_CPointerToObjCPointerCast:
4719 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004720 case CK_AnyPointerToBlockPointerCast:
4721 case CK_ObjCObjectLValueCast:
4722 case CK_FloatingComplexToReal:
4723 case CK_FloatingComplexToBoolean:
4724 case CK_IntegralComplexToReal:
4725 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004726 case CK_ARCProduceObject:
4727 case CK_ARCConsumeObject:
4728 case CK_ARCReclaimReturnedObject:
4729 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004730 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004731
John McCallfcef3cf2010-12-14 17:51:41 +00004732 case CK_LValueToRValue:
4733 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004734 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004735
4736 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004737 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004738 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004739 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004740
4741 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004742 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004743 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004744 return false;
4745
John McCallfcef3cf2010-12-14 17:51:41 +00004746 Result.makeComplexFloat();
4747 Result.FloatImag = APFloat(Real.getSemantics());
4748 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004749 }
4750
John McCallfcef3cf2010-12-14 17:51:41 +00004751 case CK_FloatingComplexCast: {
4752 if (!Visit(E->getSubExpr()))
4753 return false;
4754
4755 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4756 QualType From
4757 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4758
Richard Smith357362d2011-12-13 06:39:58 +00004759 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4760 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004761 }
4762
4763 case CK_FloatingComplexToIntegralComplex: {
4764 if (!Visit(E->getSubExpr()))
4765 return false;
4766
4767 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4768 QualType From
4769 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4770 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00004771 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4772 To, Result.IntReal) &&
4773 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4774 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004775 }
4776
4777 case CK_IntegralRealToComplex: {
4778 APSInt &Real = Result.IntReal;
4779 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4780 return false;
4781
4782 Result.makeComplexInt();
4783 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4784 return true;
4785 }
4786
4787 case CK_IntegralComplexCast: {
4788 if (!Visit(E->getSubExpr()))
4789 return false;
4790
4791 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4792 QualType From
4793 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4794
4795 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4796 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4797 return true;
4798 }
4799
4800 case CK_IntegralComplexToFloatingComplex: {
4801 if (!Visit(E->getSubExpr()))
4802 return false;
4803
4804 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4805 QualType From
4806 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4807 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00004808 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4809 To, Result.FloatReal) &&
4810 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4811 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00004812 }
4813 }
4814
4815 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004816 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004817}
4818
John McCall93d91dc2010-05-07 17:22:02 +00004819bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004820 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00004821 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4822
John McCall93d91dc2010-05-07 17:22:02 +00004823 if (!Visit(E->getLHS()))
4824 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004825
John McCall93d91dc2010-05-07 17:22:02 +00004826 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004827 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00004828 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004829
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004830 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4831 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004832 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004833 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004834 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004835 if (Result.isComplexFloat()) {
4836 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4837 APFloat::rmNearestTiesToEven);
4838 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4839 APFloat::rmNearestTiesToEven);
4840 } else {
4841 Result.getComplexIntReal() += RHS.getComplexIntReal();
4842 Result.getComplexIntImag() += RHS.getComplexIntImag();
4843 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004844 break;
John McCalle3027922010-08-25 11:45:40 +00004845 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004846 if (Result.isComplexFloat()) {
4847 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4848 APFloat::rmNearestTiesToEven);
4849 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4850 APFloat::rmNearestTiesToEven);
4851 } else {
4852 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4853 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4854 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004855 break;
John McCalle3027922010-08-25 11:45:40 +00004856 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004857 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00004858 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004859 APFloat &LHS_r = LHS.getComplexFloatReal();
4860 APFloat &LHS_i = LHS.getComplexFloatImag();
4861 APFloat &RHS_r = RHS.getComplexFloatReal();
4862 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00004863
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004864 APFloat Tmp = LHS_r;
4865 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4866 Result.getComplexFloatReal() = Tmp;
4867 Tmp = LHS_i;
4868 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4869 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4870
4871 Tmp = LHS_r;
4872 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4873 Result.getComplexFloatImag() = Tmp;
4874 Tmp = LHS_i;
4875 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4876 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4877 } else {
John McCall93d91dc2010-05-07 17:22:02 +00004878 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00004879 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004880 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4881 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00004882 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004883 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4884 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4885 }
4886 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004887 case BO_Div:
4888 if (Result.isComplexFloat()) {
4889 ComplexValue LHS = Result;
4890 APFloat &LHS_r = LHS.getComplexFloatReal();
4891 APFloat &LHS_i = LHS.getComplexFloatImag();
4892 APFloat &RHS_r = RHS.getComplexFloatReal();
4893 APFloat &RHS_i = RHS.getComplexFloatImag();
4894 APFloat &Res_r = Result.getComplexFloatReal();
4895 APFloat &Res_i = Result.getComplexFloatImag();
4896
4897 APFloat Den = RHS_r;
4898 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4899 APFloat Tmp = RHS_i;
4900 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4901 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4902
4903 Res_r = LHS_r;
4904 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4905 Tmp = LHS_i;
4906 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4907 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4908 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4909
4910 Res_i = LHS_i;
4911 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4912 Tmp = LHS_r;
4913 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4914 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4915 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4916 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004917 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
4918 return Error(E, diag::note_expr_divide_by_zero);
4919
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004920 ComplexValue LHS = Result;
4921 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4922 RHS.getComplexIntImag() * RHS.getComplexIntImag();
4923 Result.getComplexIntReal() =
4924 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
4925 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
4926 Result.getComplexIntImag() =
4927 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
4928 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
4929 }
4930 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004931 }
4932
John McCall93d91dc2010-05-07 17:22:02 +00004933 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004934}
4935
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004936bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4937 // Get the operand value into 'Result'.
4938 if (!Visit(E->getSubExpr()))
4939 return false;
4940
4941 switch (E->getOpcode()) {
4942 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004943 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004944 case UO_Extension:
4945 return true;
4946 case UO_Plus:
4947 // The result is always just the subexpr.
4948 return true;
4949 case UO_Minus:
4950 if (Result.isComplexFloat()) {
4951 Result.getComplexFloatReal().changeSign();
4952 Result.getComplexFloatImag().changeSign();
4953 }
4954 else {
4955 Result.getComplexIntReal() = -Result.getComplexIntReal();
4956 Result.getComplexIntImag() = -Result.getComplexIntImag();
4957 }
4958 return true;
4959 case UO_Not:
4960 if (Result.isComplexFloat())
4961 Result.getComplexFloatImag().changeSign();
4962 else
4963 Result.getComplexIntImag() = -Result.getComplexIntImag();
4964 return true;
4965 }
4966}
4967
Anders Carlsson537969c2008-11-16 20:27:53 +00004968//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00004969// Void expression evaluation, primarily for a cast to void on the LHS of a
4970// comma operator
4971//===----------------------------------------------------------------------===//
4972
4973namespace {
4974class VoidExprEvaluator
4975 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
4976public:
4977 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
4978
4979 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00004980
4981 bool VisitCastExpr(const CastExpr *E) {
4982 switch (E->getCastKind()) {
4983 default:
4984 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4985 case CK_ToVoid:
4986 VisitIgnoredValue(E->getSubExpr());
4987 return true;
4988 }
4989 }
4990};
4991} // end anonymous namespace
4992
4993static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
4994 assert(E->isRValue() && E->getType()->isVoidType());
4995 return VoidExprEvaluator(Info).Visit(E);
4996}
4997
4998//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00004999// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00005000//===----------------------------------------------------------------------===//
5001
Richard Smith0b0a0b62011-10-29 20:57:55 +00005002static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005003 // In C, function designators are not lvalues, but we evaluate them as if they
5004 // are.
5005 if (E->isGLValue() || E->getType()->isFunctionType()) {
5006 LValue LV;
5007 if (!EvaluateLValue(E, LV, Info))
5008 return false;
5009 LV.moveInto(Result);
5010 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005011 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005012 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005013 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00005014 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005015 return false;
John McCall45d55e42010-05-07 21:00:08 +00005016 } else if (E->getType()->hasPointerRepresentation()) {
5017 LValue LV;
5018 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005019 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005020 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00005021 } else if (E->getType()->isRealFloatingType()) {
5022 llvm::APFloat F(0.0);
5023 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005024 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005025 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00005026 } else if (E->getType()->isAnyComplexType()) {
5027 ComplexValue C;
5028 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005029 return false;
Richard Smith725810a2011-10-16 21:26:27 +00005030 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00005031 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00005032 MemberPtr P;
5033 if (!EvaluateMemberPointer(E, P, Info))
5034 return false;
5035 P.moveInto(Result);
5036 return true;
Rafael Espindolafafe4b72011-12-30 03:11:50 +00005037 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005038 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005039 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005040 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00005041 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005042 Result = Info.CurrentCall->Temporaries[E];
Rafael Espindolafafe4b72011-12-30 03:11:50 +00005043 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005044 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00005045 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00005046 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5047 return false;
5048 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00005049 } else if (E->getType()->isVoidType()) {
Richard Smith357362d2011-12-13 06:39:58 +00005050 if (Info.getLangOpts().CPlusPlus0x)
5051 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5052 << E->getType();
5053 else
5054 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith42d3af92011-12-07 00:43:50 +00005055 if (!EvaluateVoid(E, Info))
5056 return false;
Richard Smith357362d2011-12-13 06:39:58 +00005057 } else if (Info.getLangOpts().CPlusPlus0x) {
5058 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5059 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005060 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00005061 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00005062 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005063 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00005064
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00005065 return true;
5066}
5067
Richard Smithed5165f2011-11-04 05:33:44 +00005068/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5069/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5070/// since later initializers for an object can indirectly refer to subobjects
5071/// which were initialized earlier.
5072static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith357362d2011-12-13 06:39:58 +00005073 const LValue &This, const Expr *E,
5074 CheckConstantExpressionKind CCEK) {
Rafael Espindolafafe4b72011-12-30 03:11:50 +00005075 if (E->isRValue() && E->getType()->isLiteralType()) {
Richard Smithed5165f2011-11-04 05:33:44 +00005076 // Evaluate arrays and record types in-place, so that later initializers can
5077 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00005078 if (E->getType()->isArrayType())
5079 return EvaluateArray(E, This, Result, Info);
5080 else if (E->getType()->isRecordType())
5081 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00005082 }
5083
5084 // For any other type, in-place evaluation is unimportant.
5085 CCValue CoreConstResult;
5086 return Evaluate(CoreConstResult, Info, E) &&
Richard Smith357362d2011-12-13 06:39:58 +00005087 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smithed5165f2011-11-04 05:33:44 +00005088}
5089
Richard Smithf57d8cb2011-12-09 22:58:01 +00005090/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5091/// lvalue-to-rvalue cast if it is an lvalue.
5092static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
5093 CCValue Value;
5094 if (!::Evaluate(Value, Info, E))
5095 return false;
5096
5097 if (E->isGLValue()) {
5098 LValue LV;
5099 LV.setFrom(Value);
5100 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5101 return false;
5102 }
5103
5104 // Check this core constant expression is a constant expression, and if so,
5105 // convert it to one.
5106 return CheckConstantExpression(Info, E, Value, Result);
5107}
Richard Smith11562c52011-10-28 17:51:58 +00005108
Richard Smith7b553f12011-10-29 00:50:52 +00005109/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00005110/// any crazy technique (that has nothing to do with language standards) that
5111/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00005112/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5113/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00005114bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00005115 // Fast-path evaluations of integer literals, since we sometimes see files
5116 // containing vast quantities of these.
5117 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5118 Result.Val = APValue(APSInt(L->getValue(),
5119 L->getType()->isUnsignedIntegerType()));
5120 return true;
5121 }
5122
Richard Smith5686e752011-11-10 03:30:42 +00005123 // FIXME: Evaluating initializers for large arrays can cause performance
5124 // problems, and we don't use such values yet. Once we have a more efficient
5125 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00005126 // The same problem affects large records.
5127 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5128 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00005129 return false;
5130
Richard Smithd62306a2011-11-10 06:34:14 +00005131 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005132 EvalInfo Info(Ctx, Result);
5133 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00005134}
5135
Jay Foad39c79802011-01-12 09:06:06 +00005136bool Expr::EvaluateAsBooleanCondition(bool &Result,
5137 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00005138 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00005139 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00005140 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00005141 Result);
John McCall1be1c632010-01-05 23:42:56 +00005142}
5143
Richard Smith5fab0c92011-12-28 19:48:30 +00005144bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5145 SideEffectsKind AllowSideEffects) const {
5146 if (!getType()->isIntegralOrEnumerationType())
5147 return false;
5148
Richard Smith11562c52011-10-28 17:51:58 +00005149 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00005150 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5151 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00005152 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005153
Richard Smith11562c52011-10-28 17:51:58 +00005154 Result = ExprResult.Val.getInt();
5155 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00005156}
5157
Jay Foad39c79802011-01-12 09:06:06 +00005158bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00005159 EvalInfo Info(Ctx, Result);
5160
John McCall45d55e42010-05-07 21:00:08 +00005161 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00005162 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smith357362d2011-12-13 06:39:58 +00005163 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5164 CCEK_Constant);
Eli Friedman7d45c482009-09-13 10:17:44 +00005165}
5166
Richard Smithd0b4dd62011-12-19 06:19:21 +00005167bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5168 const VarDecl *VD,
5169 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
5170 Expr::EvalStatus EStatus;
5171 EStatus.Diag = &Notes;
5172
5173 EvalInfo InitInfo(Ctx, EStatus);
5174 InitInfo.setEvaluatingDecl(VD, Value);
5175
5176 LValue LVal;
5177 LVal.set(VD);
5178
5179 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5180 !EStatus.HasSideEffects;
5181}
5182
Richard Smith7b553f12011-10-29 00:50:52 +00005183/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5184/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00005185bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00005186 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00005187 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00005188}
Anders Carlsson59689ed2008-11-22 21:04:56 +00005189
Jay Foad39c79802011-01-12 09:06:06 +00005190bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00005191 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00005192}
5193
Richard Smithcaf33902011-10-10 18:28:20 +00005194APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005195 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005196 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00005197 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00005198 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005199 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00005200
Anders Carlsson6736d1a22008-12-19 20:58:05 +00005201 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00005202}
John McCall864e3962010-05-07 05:32:02 +00005203
Abramo Bagnaraf8199452010-05-14 17:07:14 +00005204 bool Expr::EvalResult::isGlobalLValue() const {
5205 assert(Val.isLValue());
5206 return IsGlobalLValue(Val.getLValueBase());
5207 }
5208
5209
John McCall864e3962010-05-07 05:32:02 +00005210/// isIntegerConstantExpr - this recursive routine will test if an expression is
5211/// an integer constant expression.
5212
5213/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5214/// comma, etc
5215///
5216/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5217/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5218/// cast+dereference.
5219
5220// CheckICE - This function does the fundamental ICE checking: the returned
5221// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5222// Note that to reduce code duplication, this helper does no evaluation
5223// itself; the caller checks whether the expression is evaluatable, and
5224// in the rare cases where CheckICE actually cares about the evaluated
5225// value, it calls into Evalute.
5226//
5227// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00005228// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00005229// 1: This expression is not an ICE, but if it isn't evaluated, it's
5230// a legal subexpression for an ICE. This return value is used to handle
5231// the comma operator in C99 mode.
5232// 2: This expression is not an ICE, and is not a legal subexpression for one.
5233
Dan Gohman28ade552010-07-26 21:25:24 +00005234namespace {
5235
John McCall864e3962010-05-07 05:32:02 +00005236struct ICEDiag {
5237 unsigned Val;
5238 SourceLocation Loc;
5239
5240 public:
5241 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5242 ICEDiag() : Val(0) {}
5243};
5244
Dan Gohman28ade552010-07-26 21:25:24 +00005245}
5246
5247static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00005248
5249static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5250 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005251 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005252 !EVResult.Val.isInt()) {
5253 return ICEDiag(2, E->getLocStart());
5254 }
5255 return NoDiag();
5256}
5257
5258static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5259 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00005260 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00005261 return ICEDiag(2, E->getLocStart());
5262 }
5263
5264 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00005265#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00005266#define STMT(Node, Base) case Expr::Node##Class:
5267#define EXPR(Node, Base)
5268#include "clang/AST/StmtNodes.inc"
5269 case Expr::PredefinedExprClass:
5270 case Expr::FloatingLiteralClass:
5271 case Expr::ImaginaryLiteralClass:
5272 case Expr::StringLiteralClass:
5273 case Expr::ArraySubscriptExprClass:
5274 case Expr::MemberExprClass:
5275 case Expr::CompoundAssignOperatorClass:
5276 case Expr::CompoundLiteralExprClass:
5277 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00005278 case Expr::DesignatedInitExprClass:
5279 case Expr::ImplicitValueInitExprClass:
5280 case Expr::ParenListExprClass:
5281 case Expr::VAArgExprClass:
5282 case Expr::AddrLabelExprClass:
5283 case Expr::StmtExprClass:
5284 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00005285 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00005286 case Expr::CXXDynamicCastExprClass:
5287 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00005288 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00005289 case Expr::CXXNullPtrLiteralExprClass:
5290 case Expr::CXXThisExprClass:
5291 case Expr::CXXThrowExprClass:
5292 case Expr::CXXNewExprClass:
5293 case Expr::CXXDeleteExprClass:
5294 case Expr::CXXPseudoDestructorExprClass:
5295 case Expr::UnresolvedLookupExprClass:
5296 case Expr::DependentScopeDeclRefExprClass:
5297 case Expr::CXXConstructExprClass:
5298 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00005299 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00005300 case Expr::CXXTemporaryObjectExprClass:
5301 case Expr::CXXUnresolvedConstructExprClass:
5302 case Expr::CXXDependentScopeMemberExprClass:
5303 case Expr::UnresolvedMemberExprClass:
5304 case Expr::ObjCStringLiteralClass:
5305 case Expr::ObjCEncodeExprClass:
5306 case Expr::ObjCMessageExprClass:
5307 case Expr::ObjCSelectorExprClass:
5308 case Expr::ObjCProtocolExprClass:
5309 case Expr::ObjCIvarRefExprClass:
5310 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00005311 case Expr::ObjCIsaExprClass:
5312 case Expr::ShuffleVectorExprClass:
5313 case Expr::BlockExprClass:
5314 case Expr::BlockDeclRefExprClass:
5315 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00005316 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005317 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00005318 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00005319 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00005320 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00005321 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00005322 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00005323 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005324 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00005325 return ICEDiag(2, E->getLocStart());
5326
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005327 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00005328 case Expr::GNUNullExprClass:
5329 // GCC considers the GNU __null value to be an integral constant expression.
5330 return NoDiag();
5331
John McCall7c454bb2011-07-15 05:09:51 +00005332 case Expr::SubstNonTypeTemplateParmExprClass:
5333 return
5334 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5335
John McCall864e3962010-05-07 05:32:02 +00005336 case Expr::ParenExprClass:
5337 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00005338 case Expr::GenericSelectionExprClass:
5339 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005340 case Expr::IntegerLiteralClass:
5341 case Expr::CharacterLiteralClass:
5342 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00005343 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00005344 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005345 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00005346 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00005347 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005348 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00005349 return NoDiag();
5350 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00005351 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00005352 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5353 // constant expressions, but they can never be ICEs because an ICE cannot
5354 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00005355 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005356 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00005357 return CheckEvalInICE(E, Ctx);
5358 return ICEDiag(2, E->getLocStart());
5359 }
5360 case Expr::DeclRefExprClass:
5361 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5362 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00005363 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00005364 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5365
5366 // Parameter variables are never constants. Without this check,
5367 // getAnyInitializer() can find a default argument, which leads
5368 // to chaos.
5369 if (isa<ParmVarDecl>(D))
5370 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5371
5372 // C++ 7.1.5.1p2
5373 // A variable of non-volatile const-qualified integral or enumeration
5374 // type initialized by an ICE can be used in ICEs.
5375 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00005376 if (!Dcl->getType()->isIntegralOrEnumerationType())
5377 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5378
Richard Smithd0b4dd62011-12-19 06:19:21 +00005379 const VarDecl *VD;
5380 // Look for a declaration of this variable that has an initializer, and
5381 // check whether it is an ICE.
5382 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5383 return NoDiag();
5384 else
5385 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00005386 }
5387 }
5388 return ICEDiag(2, E->getLocStart());
5389 case Expr::UnaryOperatorClass: {
5390 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5391 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005392 case UO_PostInc:
5393 case UO_PostDec:
5394 case UO_PreInc:
5395 case UO_PreDec:
5396 case UO_AddrOf:
5397 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00005398 // C99 6.6/3 allows increment and decrement within unevaluated
5399 // subexpressions of constant expressions, but they can never be ICEs
5400 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005401 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00005402 case UO_Extension:
5403 case UO_LNot:
5404 case UO_Plus:
5405 case UO_Minus:
5406 case UO_Not:
5407 case UO_Real:
5408 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00005409 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005410 }
5411
5412 // OffsetOf falls through here.
5413 }
5414 case Expr::OffsetOfExprClass: {
5415 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00005416 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00005417 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00005418 // compliance: we should warn earlier for offsetof expressions with
5419 // array subscripts that aren't ICEs, and if the array subscripts
5420 // are ICEs, the value of the offsetof must be an integer constant.
5421 return CheckEvalInICE(E, Ctx);
5422 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00005423 case Expr::UnaryExprOrTypeTraitExprClass: {
5424 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5425 if ((Exp->getKind() == UETT_SizeOf) &&
5426 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00005427 return ICEDiag(2, E->getLocStart());
5428 return NoDiag();
5429 }
5430 case Expr::BinaryOperatorClass: {
5431 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5432 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005433 case BO_PtrMemD:
5434 case BO_PtrMemI:
5435 case BO_Assign:
5436 case BO_MulAssign:
5437 case BO_DivAssign:
5438 case BO_RemAssign:
5439 case BO_AddAssign:
5440 case BO_SubAssign:
5441 case BO_ShlAssign:
5442 case BO_ShrAssign:
5443 case BO_AndAssign:
5444 case BO_XorAssign:
5445 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00005446 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5447 // constant expressions, but they can never be ICEs because an ICE cannot
5448 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00005449 return ICEDiag(2, E->getLocStart());
5450
John McCalle3027922010-08-25 11:45:40 +00005451 case BO_Mul:
5452 case BO_Div:
5453 case BO_Rem:
5454 case BO_Add:
5455 case BO_Sub:
5456 case BO_Shl:
5457 case BO_Shr:
5458 case BO_LT:
5459 case BO_GT:
5460 case BO_LE:
5461 case BO_GE:
5462 case BO_EQ:
5463 case BO_NE:
5464 case BO_And:
5465 case BO_Xor:
5466 case BO_Or:
5467 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00005468 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5469 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00005470 if (Exp->getOpcode() == BO_Div ||
5471 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00005472 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00005473 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00005474 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00005475 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005476 if (REval == 0)
5477 return ICEDiag(1, E->getLocStart());
5478 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00005479 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00005480 if (LEval.isMinSignedValue())
5481 return ICEDiag(1, E->getLocStart());
5482 }
5483 }
5484 }
John McCalle3027922010-08-25 11:45:40 +00005485 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00005486 if (Ctx.getLangOptions().C99) {
5487 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5488 // if it isn't evaluated.
5489 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5490 return ICEDiag(1, E->getLocStart());
5491 } else {
5492 // In both C89 and C++, commas in ICEs are illegal.
5493 return ICEDiag(2, E->getLocStart());
5494 }
5495 }
5496 if (LHSResult.Val >= RHSResult.Val)
5497 return LHSResult;
5498 return RHSResult;
5499 }
John McCalle3027922010-08-25 11:45:40 +00005500 case BO_LAnd:
5501 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00005502 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5503 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5504 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5505 // Rare case where the RHS has a comma "side-effect"; we need
5506 // to actually check the condition to see whether the side
5507 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00005508 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00005509 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00005510 return RHSResult;
5511 return NoDiag();
5512 }
5513
5514 if (LHSResult.Val >= RHSResult.Val)
5515 return LHSResult;
5516 return RHSResult;
5517 }
5518 }
5519 }
5520 case Expr::ImplicitCastExprClass:
5521 case Expr::CStyleCastExprClass:
5522 case Expr::CXXFunctionalCastExprClass:
5523 case Expr::CXXStaticCastExprClass:
5524 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005525 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005526 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005527 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00005528 if (isa<ExplicitCastExpr>(E)) {
5529 if (const FloatingLiteral *FL
5530 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5531 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5532 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5533 APSInt IgnoredVal(DestWidth, !DestSigned);
5534 bool Ignored;
5535 // If the value does not fit in the destination type, the behavior is
5536 // undefined, so we are not required to treat it as a constant
5537 // expression.
5538 if (FL->getValue().convertToInteger(IgnoredVal,
5539 llvm::APFloat::rmTowardZero,
5540 &Ignored) & APFloat::opInvalidOp)
5541 return ICEDiag(2, E->getLocStart());
5542 return NoDiag();
5543 }
5544 }
Eli Friedman76d4e432011-09-29 21:49:34 +00005545 switch (cast<CastExpr>(E)->getCastKind()) {
5546 case CK_LValueToRValue:
5547 case CK_NoOp:
5548 case CK_IntegralToBoolean:
5549 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005550 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005551 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005552 return ICEDiag(2, E->getLocStart());
5553 }
John McCall864e3962010-05-07 05:32:02 +00005554 }
John McCallc07a0c72011-02-17 10:25:35 +00005555 case Expr::BinaryConditionalOperatorClass: {
5556 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5557 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5558 if (CommonResult.Val == 2) return CommonResult;
5559 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5560 if (FalseResult.Val == 2) return FalseResult;
5561 if (CommonResult.Val == 1) return CommonResult;
5562 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005563 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005564 return FalseResult;
5565 }
John McCall864e3962010-05-07 05:32:02 +00005566 case Expr::ConditionalOperatorClass: {
5567 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5568 // If the condition (ignoring parens) is a __builtin_constant_p call,
5569 // then only the true side is actually considered in an integer constant
5570 // expression, and it is fully evaluated. This is an important GNU
5571 // extension. See GCC PR38377 for discussion.
5572 if (const CallExpr *CallCE
5573 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00005574 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
5575 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00005576 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005577 if (CondResult.Val == 2)
5578 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005579
Richard Smithf57d8cb2011-12-09 22:58:01 +00005580 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5581 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005582
John McCall864e3962010-05-07 05:32:02 +00005583 if (TrueResult.Val == 2)
5584 return TrueResult;
5585 if (FalseResult.Val == 2)
5586 return FalseResult;
5587 if (CondResult.Val == 1)
5588 return CondResult;
5589 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5590 return NoDiag();
5591 // Rare case where the diagnostics depend on which side is evaluated
5592 // Note that if we get here, CondResult is 0, and at least one of
5593 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005594 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005595 return FalseResult;
5596 }
5597 return TrueResult;
5598 }
5599 case Expr::CXXDefaultArgExprClass:
5600 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5601 case Expr::ChooseExprClass: {
5602 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5603 }
5604 }
5605
5606 // Silence a GCC warning
5607 return ICEDiag(2, E->getLocStart());
5608}
5609
Richard Smithf57d8cb2011-12-09 22:58:01 +00005610/// Evaluate an expression as a C++11 integral constant expression.
5611static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5612 const Expr *E,
5613 llvm::APSInt *Value,
5614 SourceLocation *Loc) {
5615 if (!E->getType()->isIntegralOrEnumerationType()) {
5616 if (Loc) *Loc = E->getExprLoc();
5617 return false;
5618 }
5619
5620 Expr::EvalResult Result;
Richard Smith92b1ce02011-12-12 09:28:41 +00005621 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5622 Result.Diag = &Diags;
5623 EvalInfo Info(Ctx, Result);
5624
5625 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5626 if (!Diags.empty()) {
5627 IsICE = false;
5628 if (Loc) *Loc = Diags[0].first;
5629 } else if (!IsICE && Loc) {
5630 *Loc = E->getExprLoc();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005631 }
Richard Smith92b1ce02011-12-12 09:28:41 +00005632
5633 if (!IsICE)
5634 return false;
5635
5636 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5637 if (Value) *Value = Result.Val.getInt();
5638 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005639}
5640
Richard Smith92b1ce02011-12-12 09:28:41 +00005641bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005642 if (Ctx.getLangOptions().CPlusPlus0x)
5643 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5644
John McCall864e3962010-05-07 05:32:02 +00005645 ICEDiag d = CheckICE(this, Ctx);
5646 if (d.Val != 0) {
5647 if (Loc) *Loc = d.Loc;
5648 return false;
5649 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005650 return true;
5651}
5652
5653bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5654 SourceLocation *Loc, bool isEvaluated) const {
5655 if (Ctx.getLangOptions().CPlusPlus0x)
5656 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5657
5658 if (!isIntegerConstantExpr(Ctx, Loc))
5659 return false;
5660 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005661 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005662 return true;
5663}