blob: 96a1785e142a9c1244b3566ed4d7f88e799af324 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Richard Smith180f4792011-11-10 06:34:14 +000046 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000049
Richard Smith1bf9a9e2011-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 Smith180f4792011-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 Smith9a17a682011-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 Smith180f4792011-11-10 06:34:14 +000088 else if (const FieldDecl *FD = getAsField(Path[I]))
Richard Smith9a17a682011-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 Smith0a3bdb62011-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 Smith9a17a682011-11-07 05:07:52 +0000110 typedef APValue::LValuePathEntry PathEntry;
111
Richard Smith0a3bdb62011-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 Smith9a17a682011-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 Smith1bf9a9e2011-11-12 22:28:03 +0000125 ArrayElement = SubobjectIsArrayElement(getType(V.getLValueBase()),
Richard Smith9a17a682011-11-07 05:07:52 +0000126 V.getLValuePath());
127 else
128 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
Richard Smithe24f5fc2011-11-17 22:56:20 +0000129 OnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000130 }
131 }
132
Richard Smith0a3bdb62011-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 Smith9a17a682011-11-07 05:07:52 +0000145 Entry.ArrayIndex = N;
Richard Smith0a3bdb62011-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 Smith180f4792011-11-10 06:34:14 +0000151 void addDecl(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000152 if (Invalid) return;
153 if (OnePastTheEnd) {
154 setInvalid();
155 return;
156 }
157 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000158 APValue::BaseOrMemberType Value(D, Virtual);
159 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-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 Smithcc5d4f62011-11-07 09:22:26 +0000167 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith9a17a682011-11-07 05:07:52 +0000168 Entries.back().ArrayIndex += N;
Richard Smith0a3bdb62011-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 Smith47a1eed2011-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 Smithe24f5fc2011-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 Smith47a1eed2011-10-29 20:57:55 +0000186 class CCValue : public APValue {
187 typedef llvm::APSInt APSInt;
188 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-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 Smith0a3bdb62011-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 Smith47a1eed2011-10-29 20:57:55 +0000195 public:
Richard Smith177dce72011-11-01 16:57:24 +0000196 struct GlobalValue {};
197
Richard Smith47a1eed2011-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 Smith177dce72011-11-01 16:57:24 +0000204 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000205 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000206 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000207 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smith177dce72011-11-01 16:57:24 +0000208 CCValue(const APValue &V, GlobalValue) :
Richard Smith9a17a682011-11-07 05:07:52 +0000209 APValue(V), CallFrame(0), Designator(V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000210 CCValue(const ValueDecl *D, bool IsDerivedMember,
211 ArrayRef<const CXXRecordDecl*> Path) :
212 APValue(D, IsDerivedMember, Path) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000213
Richard Smith177dce72011-11-01 16:57:24 +0000214 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000215 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000216 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000217 }
Richard Smith0a3bdb62011-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 Smith47a1eed2011-10-29 20:57:55 +0000225 };
226
Richard Smithd0dccea2011-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 Smithbd552ef2011-10-31 05:52:43 +0000232 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000233
Richard Smith08d6e032011-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 Smith180f4792011-11-10 06:34:14 +0000240 /// This - The binding for the this pointer in this call, if any.
241 const LValue *This;
242
Richard Smithd0dccea2011-10-28 22:34:42 +0000243 /// ParmBindings - Parameter bindings for this function call, indexed by
244 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000245 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000246
Richard Smithbd552ef2011-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 Smith08d6e032011-12-16 19:06:07 +0000252 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
253 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000254 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000255 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000256 };
257
Richard Smithdd1f29b2011-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 Smithbd552ef2011-10-31 05:52:43 +0000274 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000275 ASTContext &Ctx;
Richard Smithbd552ef2011-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 Smithbd552ef2011-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 Smith180f4792011-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 Smithc1c5f272011-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 Smithbd552ef2011-10-31 05:52:43 +0000307
308 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000309 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith08d6e032011-12-16 19:06:07 +0000310 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
311 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000312
Richard Smithbd552ef2011-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 Smith180f4792011-11-10 06:34:14 +0000319 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
320 EvaluatingDecl = VD;
321 EvaluatingDeclValue = &Value;
322 }
323
Richard Smithc18c4232011-11-21 19:36:32 +0000324 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
325
Richard Smithc1c5f272011-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 Smithc18c4232011-11-21 19:36:32 +0000332 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000333
Richard Smithc1c5f272011-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 Smith08d6e032011-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 Smithc1c5f272011-12-13 06:39:58 +0000345 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000346 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000347 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
348 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000349 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-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 Smithdd1f29b2011-12-12 09:28:41 +0000353 if (EvalStatus.Diag) {
Richard Smith08d6e032011-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 Smithc1c5f272011-12-13 06:39:58 +0000359 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000360 EvalStatus.Diag->clear();
Richard Smith08d6e032011-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 Smithdd1f29b2011-12-12 09:28:41 +0000365 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000366 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-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 Smith7098cbd2011-12-21 05:04:46 +0000372 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
373 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000374 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000375 // Don't override a previous diagnostic.
376 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
377 return OptionalDiagnostic();
Richard Smithc1c5f272011-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 Smithf48fdb02011-12-09 22:58:01 +0000386 }
Richard Smith099e7f62011-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 Smithbd552ef2011-10-31 05:52:43 +0000395 };
Richard Smith08d6e032011-12-16 19:06:07 +0000396}
Richard Smithbd552ef2011-10-31 05:52:43 +0000397
Richard Smith08d6e032011-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 Smithbd552ef2011-10-31 05:52:43 +0000441 }
442
Richard Smith08d6e032011-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 Smithbd552ef2011-10-31 05:52:43 +0000453 }
454
Richard Smith08d6e032011-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 McCallf4cf1a12010-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 Smith47a1eed2011-10-29 20:57:55 +0000497 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000498 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000499 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000500 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000501 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000502 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000503 void setFrom(const CCValue &v) {
John McCall56ca35d2011-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 McCallf4cf1a12010-05-07 17:22:02 +0000515 };
John McCallefdb83e2010-05-07 21:00:08 +0000516
517 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000518 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000519 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000520 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000521 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000522
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000523 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000524 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000525 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000526 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000527 SubobjectDesignator &getLValueDesignator() { return Designator; }
528 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000529
Richard Smith47a1eed2011-10-29 20:57:55 +0000530 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000531 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000532 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000533 void setFrom(const CCValue &V) {
534 assert(V.isLValue());
535 Base = V.getLValueBase();
536 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000537 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000538 Designator = V.getLValueDesignator();
539 }
540
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000541 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
542 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000543 Offset = CharUnits::Zero();
544 Frame = F;
545 Designator = SubobjectDesignator();
John McCall56ca35d2011-02-17 10:25:35 +0000546 }
John McCallefdb83e2010-05-07 21:00:08 +0000547 };
Richard Smithe24f5fc2011-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 Smithc1c5f272011-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 McCallf4cf1a12010-05-07 17:22:02 +0000644}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000645
Richard Smith47a1eed2011-10-29 20:57:55 +0000646static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000647static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000648 const LValue &This, const Expr *E,
649 CheckConstantExpressionKind CCEK
650 = CCEK_Constant);
John McCallefdb83e2010-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 Smithe24f5fc2011-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 Lattner87eae5e2008-07-11 22:52:41 +0000656static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000657static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000658 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000659static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000660static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000661
662//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000663// Misc utilities
664//===----------------------------------------------------------------------===//
665
Richard Smith180f4792011-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 Smith1bf9a9e2011-11-12 22:28:03 +0000673static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-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 Smith1bf9a9e2011-11-12 22:28:03 +0000679 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000680
Richard Smith1bf9a9e2011-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 Smith180f4792011-11-10 06:34:14 +0000690 switch (E->getStmtClass()) {
691 default:
692 return false;
Richard Smith180f4792011-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:
700 return true;
701 case Expr::CallExprClass:
702 return IsStringLiteralCall(cast<CallExpr>(E));
703 // For GCC compatibility, &&label has static storage duration.
704 case Expr::AddrLabelExprClass:
705 return true;
706 // A Block literal expression may be used as the initialization value for
707 // Block variables at global or local static scope.
708 case Expr::BlockExprClass:
709 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
710 }
John McCall42c8f872010-05-10 23:27:23 +0000711}
712
Richard Smith9a17a682011-11-07 05:07:52 +0000713/// Check that this reference or pointer core constant expression is a valid
714/// value for a constant expression. Type T should be either LValue or CCValue.
715template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000716static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000717 const T &LVal, APValue &Value,
718 CheckConstantExpressionKind CCEK) {
719 APValue::LValueBase Base = LVal.getLValueBase();
720 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
721
722 if (!IsGlobalLValue(Base)) {
723 if (Info.getLangOpts().CPlusPlus0x) {
724 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
725 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
726 << E->isGLValue() << !Designator.Entries.empty()
727 << !!VD << CCEK << VD;
728 if (VD)
729 Info.Note(VD->getLocation(), diag::note_declared_at);
730 else
731 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
732 diag::note_constexpr_temporary_here);
733 } else {
Richard Smith7098cbd2011-12-21 05:04:46 +0000734 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000735 }
Richard Smith9a17a682011-11-07 05:07:52 +0000736 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000737 }
Richard Smith9a17a682011-11-07 05:07:52 +0000738
Richard Smith9a17a682011-11-07 05:07:52 +0000739 // A constant expression must refer to an object or be a null pointer.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000740 if (Designator.Invalid ||
Richard Smith9a17a682011-11-07 05:07:52 +0000741 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000742 // FIXME: This is not a core constant expression. We should have already
743 // produced a CCE diagnostic.
Richard Smith9a17a682011-11-07 05:07:52 +0000744 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
745 APValue::NoLValuePath());
746 return true;
747 }
748
Richard Smithc1c5f272011-12-13 06:39:58 +0000749 // Does this refer one past the end of some object?
750 // This is technically not an address constant expression nor a reference
751 // constant expression, but we allow it for address constant expressions.
752 if (E->isGLValue() && Base && Designator.OnePastTheEnd) {
753 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
754 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
755 << !Designator.Entries.empty() << !!VD << VD;
756 if (VD)
757 Info.Note(VD->getLocation(), diag::note_declared_at);
758 else
759 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
760 diag::note_constexpr_temporary_here);
761 return false;
762 }
763
Richard Smith9a17a682011-11-07 05:07:52 +0000764 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smithe24f5fc2011-11-17 22:56:20 +0000765 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith9a17a682011-11-07 05:07:52 +0000766 return true;
767}
768
Richard Smith47a1eed2011-10-29 20:57:55 +0000769/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000770/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithf48fdb02011-12-09 22:58:01 +0000771/// If not, report an appropriate diagnostic.
772static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000773 const CCValue &CCValue, APValue &Value,
774 CheckConstantExpressionKind CCEK
775 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +0000776 if (!CCValue.isLValue()) {
777 Value = CCValue;
778 return true;
779 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000780 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +0000781}
782
Richard Smith9e36b532011-10-31 05:11:32 +0000783const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000784 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +0000785}
786
787static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000788 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +0000789}
790
Richard Smith65ac5982011-11-01 21:06:14 +0000791static bool IsWeakLValue(const LValue &Value) {
792 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +0000793 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +0000794}
795
Richard Smithe24f5fc2011-11-17 22:56:20 +0000796static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +0000797 // A null base expression indicates a null pointer. These are always
798 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000799 if (!Value.getLValueBase()) {
800 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +0000801 return true;
802 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000803
John McCall42c8f872010-05-10 23:27:23 +0000804 // Require the base expression to be a global l-value.
Richard Smith47a1eed2011-10-29 20:57:55 +0000805 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000806 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall42c8f872010-05-10 23:27:23 +0000807
Richard Smithe24f5fc2011-11-17 22:56:20 +0000808 // We have a non-null base. These are generally known to be true, but if it's
809 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +0000810 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000811 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +0000812 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +0000813}
814
Richard Smith47a1eed2011-10-29 20:57:55 +0000815static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +0000816 switch (Val.getKind()) {
817 case APValue::Uninitialized:
818 return false;
819 case APValue::Int:
820 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +0000821 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000822 case APValue::Float:
823 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +0000824 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000825 case APValue::ComplexInt:
826 Result = Val.getComplexIntReal().getBoolValue() ||
827 Val.getComplexIntImag().getBoolValue();
828 return true;
829 case APValue::ComplexFloat:
830 Result = !Val.getComplexFloatReal().isZero() ||
831 !Val.getComplexFloatImag().isZero();
832 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000833 case APValue::LValue:
834 return EvalPointerValueAsBool(Val, Result);
835 case APValue::MemberPointer:
836 Result = Val.getMemberPointerDecl();
837 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000838 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +0000839 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +0000840 case APValue::Struct:
841 case APValue::Union:
Richard Smithc49bd112011-10-28 17:51:58 +0000842 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000843 }
844
Richard Smithc49bd112011-10-28 17:51:58 +0000845 llvm_unreachable("unknown APValue kind");
846}
847
848static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
849 EvalInfo &Info) {
850 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +0000851 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +0000852 if (!Evaluate(Val, Info, E))
853 return false;
854 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +0000855}
856
Richard Smithc1c5f272011-12-13 06:39:58 +0000857template<typename T>
858static bool HandleOverflow(EvalInfo &Info, const Expr *E,
859 const T &SrcValue, QualType DestType) {
860 llvm::SmallVector<char, 32> Buffer;
861 SrcValue.toString(Buffer);
862 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
863 << StringRef(Buffer.data(), Buffer.size()) << DestType;
864 return false;
865}
866
867static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
868 QualType SrcType, const APFloat &Value,
869 QualType DestType, APSInt &Result) {
870 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000871 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000872 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Richard Smithc1c5f272011-12-13 06:39:58 +0000874 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000875 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +0000876 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
877 & APFloat::opInvalidOp)
878 return HandleOverflow(Info, E, Value, DestType);
879 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000880}
881
Richard Smithc1c5f272011-12-13 06:39:58 +0000882static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
883 QualType SrcType, QualType DestType,
884 APFloat &Result) {
885 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000886 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +0000887 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
888 APFloat::rmNearestTiesToEven, &ignored)
889 & APFloat::opOverflow)
890 return HandleOverflow(Info, E, Value, DestType);
891 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000892}
893
Mike Stump1eb44332009-09-09 15:08:12 +0000894static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000895 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000896 unsigned DestWidth = Ctx.getIntWidth(DestType);
897 APSInt Result = Value;
898 // Figure out if this is a truncate, extend or noop cast.
899 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000900 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000901 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000902 return Result;
903}
904
Richard Smithc1c5f272011-12-13 06:39:58 +0000905static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
906 QualType SrcType, const APSInt &Value,
907 QualType DestType, APFloat &Result) {
908 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
909 if (Result.convertFromAPInt(Value, Value.isSigned(),
910 APFloat::rmNearestTiesToEven)
911 & APFloat::opOverflow)
912 return HandleOverflow(Info, E, Value, DestType);
913 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000914}
915
Eli Friedmane6a24e82011-12-22 03:51:45 +0000916static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
917 llvm::APInt &Res) {
918 CCValue SVal;
919 if (!Evaluate(SVal, Info, E))
920 return false;
921 if (SVal.isInt()) {
922 Res = SVal.getInt();
923 return true;
924 }
925 if (SVal.isFloat()) {
926 Res = SVal.getFloat().bitcastToAPInt();
927 return true;
928 }
929 if (SVal.isVector()) {
930 QualType VecTy = E->getType();
931 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
932 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
933 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
934 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
935 Res = llvm::APInt::getNullValue(VecSize);
936 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
937 APValue &Elt = SVal.getVectorElt(i);
938 llvm::APInt EltAsInt;
939 if (Elt.isInt()) {
940 EltAsInt = Elt.getInt();
941 } else if (Elt.isFloat()) {
942 EltAsInt = Elt.getFloat().bitcastToAPInt();
943 } else {
944 // Don't try to handle vectors of anything other than int or float
945 // (not sure if it's possible to hit this case).
946 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
947 return false;
948 }
949 unsigned BaseEltSize = EltAsInt.getBitWidth();
950 if (BigEndian)
951 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
952 else
953 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
954 }
955 return true;
956 }
957 // Give up if the input isn't an int, float, or vector. For example, we
958 // reject "(v4i16)(intptr_t)&a".
959 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
960 return false;
961}
962
Richard Smithe24f5fc2011-11-17 22:56:20 +0000963static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
964 const CXXRecordDecl *&MostDerivedType,
965 unsigned &MostDerivedPathLength,
966 bool &MostDerivedIsArrayElement) {
967 const SubobjectDesignator &D = LVal.Designator;
968 if (D.Invalid || !LVal.Base)
Richard Smith180f4792011-11-10 06:34:14 +0000969 return false;
970
Richard Smithe24f5fc2011-11-17 22:56:20 +0000971 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smith180f4792011-11-10 06:34:14 +0000972
973 // Find path prefix which leads to the most-derived subobject.
Richard Smith180f4792011-11-10 06:34:14 +0000974 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +0000975 MostDerivedPathLength = 0;
976 MostDerivedIsArrayElement = false;
Richard Smith180f4792011-11-10 06:34:14 +0000977
978 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
979 bool IsArray = T && T->isArrayType();
980 if (IsArray)
981 T = T->getBaseElementTypeUnsafe();
982 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
983 T = FD->getType().getTypePtr();
984 else
985 T = 0;
986
987 if (T) {
988 MostDerivedType = T->getAsCXXRecordDecl();
989 MostDerivedPathLength = I + 1;
990 MostDerivedIsArrayElement = IsArray;
991 }
992 }
993
Richard Smith180f4792011-11-10 06:34:14 +0000994 // (B*)&d + 1 has no most-derived object.
995 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
996 return false;
997
Richard Smithe24f5fc2011-11-17 22:56:20 +0000998 return MostDerivedType != 0;
999}
1000
1001static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
1002 const RecordDecl *TruncatedType,
1003 unsigned TruncatedElements,
1004 bool IsArrayElement) {
1005 SubobjectDesignator &D = Result.Designator;
1006 const RecordDecl *RD = TruncatedType;
1007 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001008 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1009 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001010 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001011 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001012 else
Richard Smith180f4792011-11-10 06:34:14 +00001013 Result.Offset -= Layout.getBaseClassOffset(Base);
1014 RD = Base;
1015 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001016 D.Entries.resize(TruncatedElements);
1017 D.ArrayElement = IsArrayElement;
1018}
1019
1020/// If the given LValue refers to a base subobject of some object, find the most
1021/// derived object and the corresponding complete record type. This is necessary
1022/// in order to find the offset of a virtual base class.
1023static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
1024 const CXXRecordDecl *&MostDerivedType) {
1025 unsigned MostDerivedPathLength;
1026 bool MostDerivedIsArrayElement;
1027 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1028 MostDerivedPathLength, MostDerivedIsArrayElement))
1029 return false;
1030
1031 // Remove the trailing base class path entries and their offsets.
1032 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
1033 MostDerivedIsArrayElement);
Richard Smith180f4792011-11-10 06:34:14 +00001034 return true;
1035}
1036
1037static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
1038 const CXXRecordDecl *Derived,
1039 const CXXRecordDecl *Base,
1040 const ASTRecordLayout *RL = 0) {
1041 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1042 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1043 Obj.Designator.addDecl(Base, /*Virtual*/ false);
1044}
1045
1046static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
1047 const CXXRecordDecl *DerivedDecl,
1048 const CXXBaseSpecifier *Base) {
1049 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1050
1051 if (!Base->isVirtual()) {
1052 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
1053 return true;
1054 }
1055
1056 // Extract most-derived object and corresponding type.
1057 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
1058 return false;
1059
1060 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1061 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1062 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
1063 return true;
1064}
1065
1066/// Update LVal to refer to the given field, which must be a member of the type
1067/// currently described by LVal.
1068static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
1069 const FieldDecl *FD,
1070 const ASTRecordLayout *RL = 0) {
1071 if (!RL)
1072 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1073
1074 unsigned I = FD->getFieldIndex();
1075 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1076 LVal.Designator.addDecl(FD);
1077}
1078
1079/// Get the size of the given type in char units.
1080static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1081 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1082 // extension.
1083 if (Type->isVoidType() || Type->isFunctionType()) {
1084 Size = CharUnits::One();
1085 return true;
1086 }
1087
1088 if (!Type->isConstantSizeType()) {
1089 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1090 return false;
1091 }
1092
1093 Size = Info.Ctx.getTypeSizeInChars(Type);
1094 return true;
1095}
1096
1097/// Update a pointer value to model pointer arithmetic.
1098/// \param Info - Information about the ongoing evaluation.
1099/// \param LVal - The pointer value to be updated.
1100/// \param EltTy - The pointee type represented by LVal.
1101/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1102static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
1103 QualType EltTy, int64_t Adjustment) {
1104 CharUnits SizeOfPointee;
1105 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1106 return false;
1107
1108 // Compute the new offset in the appropriate width.
1109 LVal.Offset += Adjustment * SizeOfPointee;
1110 LVal.Designator.adjustIndex(Adjustment);
1111 return true;
1112}
1113
Richard Smith03f96112011-10-24 17:54:18 +00001114/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001115static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1116 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001117 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001118 // If this is a parameter to an active constexpr function call, perform
1119 // argument substitution.
1120 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001121 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001122 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001123 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001124 }
Richard Smith177dce72011-11-01 16:57:24 +00001125 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1126 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001127 }
Richard Smith03f96112011-10-24 17:54:18 +00001128
Richard Smith099e7f62011-12-19 06:19:21 +00001129 // Dig out the initializer, and use the declaration which it's attached to.
1130 const Expr *Init = VD->getAnyInitializer(VD);
1131 if (!Init || Init->isValueDependent()) {
1132 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1133 return false;
1134 }
1135
Richard Smith180f4792011-11-10 06:34:14 +00001136 // If we're currently evaluating the initializer of this declaration, use that
1137 // in-flight value.
1138 if (Info.EvaluatingDecl == VD) {
1139 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
1140 return !Result.isUninit();
1141 }
1142
Richard Smith65ac5982011-11-01 21:06:14 +00001143 // Never evaluate the initializer of a weak variable. We can't be sure that
1144 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001145 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001146 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001147 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001148 }
Richard Smith65ac5982011-11-01 21:06:14 +00001149
Richard Smith099e7f62011-12-19 06:19:21 +00001150 // Check that we can fold the initializer. In C++, we will have already done
1151 // this in the cases where it matters for conformance.
1152 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1153 if (!VD->evaluateValue(Notes)) {
1154 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1155 Notes.size() + 1) << VD;
1156 Info.Note(VD->getLocation(), diag::note_declared_at);
1157 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001158 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001159 } else if (!VD->checkInitIsICE()) {
1160 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1161 Notes.size() + 1) << VD;
1162 Info.Note(VD->getLocation(), diag::note_declared_at);
1163 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001164 }
Richard Smith03f96112011-10-24 17:54:18 +00001165
Richard Smith099e7f62011-12-19 06:19:21 +00001166 Result = CCValue(*VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001167 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001168}
1169
Richard Smithc49bd112011-10-28 17:51:58 +00001170static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001171 Qualifiers Quals = T.getQualifiers();
1172 return Quals.hasConst() && !Quals.hasVolatile();
1173}
1174
Richard Smith59efe262011-11-11 04:05:33 +00001175/// Get the base index of the given base class within an APValue representing
1176/// the given derived class.
1177static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1178 const CXXRecordDecl *Base) {
1179 Base = Base->getCanonicalDecl();
1180 unsigned Index = 0;
1181 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1182 E = Derived->bases_end(); I != E; ++I, ++Index) {
1183 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1184 return Index;
1185 }
1186
1187 llvm_unreachable("base class missing from derived class's bases list");
1188}
1189
Richard Smithcc5d4f62011-11-07 09:22:26 +00001190/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001191static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1192 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001193 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001194 if (Sub.Invalid) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001195 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001196 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001197 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001198 if (Sub.OnePastTheEnd) {
1199 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001200 (unsigned)diag::note_constexpr_read_past_end :
1201 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001202 return false;
1203 }
Richard Smithf64699e2011-11-11 08:28:03 +00001204 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001205 return true;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001206
1207 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1208 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001209 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001210 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001211 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001212 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001213 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001214 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001215 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001216 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001217 // Note, it should not be possible to form a pointer with a valid
1218 // designator which points more than one past the end of the array.
1219 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001220 (unsigned)diag::note_constexpr_read_past_end :
1221 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001222 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001223 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001224 if (O->getArrayInitializedElts() > Index)
1225 O = &O->getArrayInitializedElt(Index);
1226 else
1227 O = &O->getArrayFiller();
1228 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001229 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1230 // Next subobject is a class, struct or union field.
1231 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1232 if (RD->isUnion()) {
1233 const FieldDecl *UnionField = O->getUnionField();
1234 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001235 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001236 Info.Diag(E->getExprLoc(),
1237 diag::note_constexpr_read_inactive_union_member)
1238 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001239 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001240 }
Richard Smith180f4792011-11-10 06:34:14 +00001241 O = &O->getUnionValue();
1242 } else
1243 O = &O->getStructField(Field->getFieldIndex());
1244 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001245
1246 if (ObjType.isVolatileQualified()) {
1247 if (Info.getLangOpts().CPlusPlus) {
1248 // FIXME: Include a description of the path to the volatile subobject.
1249 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1250 << 2 << Field;
1251 Info.Note(Field->getLocation(), diag::note_declared_at);
1252 } else {
1253 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1254 }
1255 return false;
1256 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001257 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001258 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001259 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1260 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1261 O = &O->getStructBase(getBaseIndex(Derived, Base));
1262 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001263 }
Richard Smith180f4792011-11-10 06:34:14 +00001264
Richard Smithf48fdb02011-12-09 22:58:01 +00001265 if (O->isUninit()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001266 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001267 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001268 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001269 }
1270
Richard Smithcc5d4f62011-11-07 09:22:26 +00001271 Obj = CCValue(*O, CCValue::GlobalValue());
1272 return true;
1273}
1274
Richard Smith180f4792011-11-10 06:34:14 +00001275/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1276/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1277/// for looking up the glvalue referred to by an entity of reference type.
1278///
1279/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001280/// \param Conv - The expression for which we are performing the conversion.
1281/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001282/// \param Type - The type we expect this conversion to produce.
1283/// \param LVal - The glvalue on which we are attempting to perform this action.
1284/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001285static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1286 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001287 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001288 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1289 if (!Info.getLangOpts().CPlusPlus)
1290 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1291
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001292 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001293 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001294 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001295
Richard Smithf48fdb02011-12-09 22:58:01 +00001296 if (!LVal.Base) {
1297 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001298 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1299 return false;
1300 }
1301
1302 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1303 // is not a constant expression (even if the object is non-volatile). We also
1304 // apply this rule to C++98, in order to conform to the expected 'volatile'
1305 // semantics.
1306 if (Type.isVolatileQualified()) {
1307 if (Info.getLangOpts().CPlusPlus)
1308 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1309 else
1310 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001311 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001312 }
Richard Smithc49bd112011-10-28 17:51:58 +00001313
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001314 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001315 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1316 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001317 // expressions are constant expressions too. Inside constexpr functions,
1318 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001319 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001320 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001321 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001322 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001323 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001324 }
1325
Richard Smith7098cbd2011-12-21 05:04:46 +00001326 // DR1313: If the object is volatile-qualified but the glvalue was not,
1327 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001328 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001329 if (VT.isVolatileQualified()) {
1330 if (Info.getLangOpts().CPlusPlus) {
1331 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1332 Info.Note(VD->getLocation(), diag::note_declared_at);
1333 } else {
1334 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001335 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001336 return false;
1337 }
1338
1339 if (!isa<ParmVarDecl>(VD)) {
1340 if (VD->isConstexpr()) {
1341 // OK, we can read this variable.
1342 } else if (VT->isIntegralOrEnumerationType()) {
1343 if (!VT.isConstQualified()) {
1344 if (Info.getLangOpts().CPlusPlus) {
1345 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1346 Info.Note(VD->getLocation(), diag::note_declared_at);
1347 } else {
1348 Info.Diag(Loc);
1349 }
1350 return false;
1351 }
1352 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1353 // We support folding of const floating-point types, in order to make
1354 // static const data members of such types (supported as an extension)
1355 // more useful.
1356 if (Info.getLangOpts().CPlusPlus0x) {
1357 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1358 Info.Note(VD->getLocation(), diag::note_declared_at);
1359 } else {
1360 Info.CCEDiag(Loc);
1361 }
1362 } else {
1363 // FIXME: Allow folding of values of any literal type in all languages.
1364 if (Info.getLangOpts().CPlusPlus0x) {
1365 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1366 Info.Note(VD->getLocation(), diag::note_declared_at);
1367 } else {
1368 Info.Diag(Loc);
1369 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001370 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001371 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001372 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001373
Richard Smithf48fdb02011-12-09 22:58:01 +00001374 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001375 return false;
1376
Richard Smith47a1eed2011-10-29 20:57:55 +00001377 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001378 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001379
1380 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1381 // conversion. This happens when the declaration and the lvalue should be
1382 // considered synonymous, for instance when initializing an array of char
1383 // from a string literal. Continue as if the initializer lvalue was the
1384 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001385 assert(RVal.getLValueOffset().isZero() &&
1386 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001387 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001388 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001389 }
1390
Richard Smith7098cbd2011-12-21 05:04:46 +00001391 // Volatile temporary objects cannot be read in constant expressions.
1392 if (Base->getType().isVolatileQualified()) {
1393 if (Info.getLangOpts().CPlusPlus) {
1394 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1395 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1396 } else {
1397 Info.Diag(Loc);
1398 }
1399 return false;
1400 }
1401
Richard Smith0a3bdb62011-11-04 02:25:55 +00001402 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1403 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1404 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001405 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001406 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001407 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001408 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001409
1410 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001411 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001412 const ConstantArrayType *CAT =
1413 Info.Ctx.getAsConstantArrayType(S->getType());
1414 if (Index >= CAT->getSize().getZExtValue()) {
1415 // Note, it should not be possible to form a pointer which points more
1416 // than one past the end of the array without producing a prior const expr
1417 // diagnostic.
1418 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001419 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001420 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001421 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1422 Type->isUnsignedIntegerType());
1423 if (Index < S->getLength())
1424 Value = S->getCodeUnit(Index);
1425 RVal = CCValue(Value);
1426 return true;
1427 }
1428
Richard Smithcc5d4f62011-11-07 09:22:26 +00001429 if (Frame) {
1430 // If this is a temporary expression with a nontrivial initializer, grab the
1431 // value from the relevant stack frame.
1432 RVal = Frame->Temporaries[Base];
1433 } else if (const CompoundLiteralExpr *CLE
1434 = dyn_cast<CompoundLiteralExpr>(Base)) {
1435 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1436 // initializer until now for such expressions. Such an expression can't be
1437 // an ICE in C, so this only matters for fold.
1438 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1439 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1440 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001441 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001442 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001443 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001444 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001445
Richard Smithf48fdb02011-12-09 22:58:01 +00001446 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1447 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001448}
1449
Richard Smith59efe262011-11-11 04:05:33 +00001450/// Build an lvalue for the object argument of a member function call.
1451static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1452 LValue &This) {
1453 if (Object->getType()->isPointerType())
1454 return EvaluatePointer(Object, This, Info);
1455
1456 if (Object->isGLValue())
1457 return EvaluateLValue(Object, This, Info);
1458
Richard Smithe24f5fc2011-11-17 22:56:20 +00001459 if (Object->getType()->isLiteralType())
1460 return EvaluateTemporary(Object, This, Info);
1461
1462 return false;
1463}
1464
1465/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1466/// lvalue referring to the result.
1467///
1468/// \param Info - Information about the ongoing evaluation.
1469/// \param BO - The member pointer access operation.
1470/// \param LV - Filled in with a reference to the resulting object.
1471/// \param IncludeMember - Specifies whether the member itself is included in
1472/// the resulting LValue subobject designator. This is not possible when
1473/// creating a bound member function.
1474/// \return The field or method declaration to which the member pointer refers,
1475/// or 0 if evaluation fails.
1476static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1477 const BinaryOperator *BO,
1478 LValue &LV,
1479 bool IncludeMember = true) {
1480 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1481
1482 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1483 return 0;
1484
1485 MemberPtr MemPtr;
1486 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1487 return 0;
1488
1489 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1490 // member value, the behavior is undefined.
1491 if (!MemPtr.getDecl())
1492 return 0;
1493
1494 if (MemPtr.isDerivedMember()) {
1495 // This is a member of some derived class. Truncate LV appropriately.
1496 const CXXRecordDecl *MostDerivedType;
1497 unsigned MostDerivedPathLength;
1498 bool MostDerivedIsArrayElement;
1499 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1500 MostDerivedIsArrayElement))
1501 return 0;
1502
1503 // The end of the derived-to-base path for the base object must match the
1504 // derived-to-base path for the member pointer.
1505 if (MostDerivedPathLength + MemPtr.Path.size() >
1506 LV.Designator.Entries.size())
1507 return 0;
1508 unsigned PathLengthToMember =
1509 LV.Designator.Entries.size() - MemPtr.Path.size();
1510 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1511 const CXXRecordDecl *LVDecl = getAsBaseClass(
1512 LV.Designator.Entries[PathLengthToMember + I]);
1513 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1514 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1515 return 0;
1516 }
1517
1518 // Truncate the lvalue to the appropriate derived class.
1519 bool ResultIsArray = false;
1520 if (PathLengthToMember == MostDerivedPathLength)
1521 ResultIsArray = MostDerivedIsArrayElement;
1522 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1523 PathLengthToMember, ResultIsArray);
1524 } else if (!MemPtr.Path.empty()) {
1525 // Extend the LValue path with the member pointer's path.
1526 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1527 MemPtr.Path.size() + IncludeMember);
1528
1529 // Walk down to the appropriate base class.
1530 QualType LVType = BO->getLHS()->getType();
1531 if (const PointerType *PT = LVType->getAs<PointerType>())
1532 LVType = PT->getPointeeType();
1533 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1534 assert(RD && "member pointer access on non-class-type expression");
1535 // The first class in the path is that of the lvalue.
1536 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1537 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1538 HandleLValueDirectBase(Info, LV, RD, Base);
1539 RD = Base;
1540 }
1541 // Finally cast to the class containing the member.
1542 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1543 }
1544
1545 // Add the member. Note that we cannot build bound member functions here.
1546 if (IncludeMember) {
1547 // FIXME: Deal with IndirectFieldDecls.
1548 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1549 if (!FD) return 0;
1550 HandleLValueMember(Info, LV, FD);
1551 }
1552
1553 return MemPtr.getDecl();
1554}
1555
1556/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1557/// the provided lvalue, which currently refers to the base object.
1558static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1559 LValue &Result) {
1560 const CXXRecordDecl *MostDerivedType;
1561 unsigned MostDerivedPathLength;
1562 bool MostDerivedIsArrayElement;
1563
1564 // Check this cast doesn't take us outside the object.
1565 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1566 MostDerivedPathLength,
1567 MostDerivedIsArrayElement))
1568 return false;
1569 SubobjectDesignator &D = Result.Designator;
1570 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1571 return false;
1572
1573 // Check the type of the final cast. We don't need to check the path,
1574 // since a cast can only be formed if the path is unique.
1575 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1576 bool ResultIsArray = false;
1577 QualType TargetQT = E->getType();
1578 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1579 TargetQT = PT->getPointeeType();
1580 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1581 const CXXRecordDecl *FinalType;
1582 if (NewEntriesSize == MostDerivedPathLength) {
1583 ResultIsArray = MostDerivedIsArrayElement;
1584 FinalType = MostDerivedType;
1585 } else
1586 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1587 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1588 return false;
1589
1590 // Truncate the lvalue to the appropriate derived class.
1591 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1592 ResultIsArray);
1593 return true;
Richard Smith59efe262011-11-11 04:05:33 +00001594}
1595
Mike Stumpc4c90452009-10-27 22:09:17 +00001596namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001597enum EvalStmtResult {
1598 /// Evaluation failed.
1599 ESR_Failed,
1600 /// Hit a 'return' statement.
1601 ESR_Returned,
1602 /// Evaluation succeeded.
1603 ESR_Succeeded
1604};
1605}
1606
1607// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001608static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001609 const Stmt *S) {
1610 switch (S->getStmtClass()) {
1611 default:
1612 return ESR_Failed;
1613
1614 case Stmt::NullStmtClass:
1615 case Stmt::DeclStmtClass:
1616 return ESR_Succeeded;
1617
Richard Smithc1c5f272011-12-13 06:39:58 +00001618 case Stmt::ReturnStmtClass: {
1619 CCValue CCResult;
1620 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1621 if (!Evaluate(CCResult, Info, RetExpr) ||
1622 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1623 CCEK_ReturnValue))
1624 return ESR_Failed;
1625 return ESR_Returned;
1626 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001627
1628 case Stmt::CompoundStmtClass: {
1629 const CompoundStmt *CS = cast<CompoundStmt>(S);
1630 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1631 BE = CS->body_end(); BI != BE; ++BI) {
1632 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1633 if (ESR != ESR_Succeeded)
1634 return ESR;
1635 }
1636 return ESR_Succeeded;
1637 }
1638 }
1639}
1640
Richard Smith61802452011-12-22 02:22:31 +00001641/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1642/// default constructor. If so, we'll fold it whether or not it's marked as
1643/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1644/// so we need special handling.
1645static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
1646 const CXXConstructorDecl *CD) {
1647 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1648 return false;
1649
1650 if (!CD->isConstexpr()) {
1651 if (Info.getLangOpts().CPlusPlus0x) {
1652 // FIXME: If DiagDecl is an implicitly-declared special member function,
1653 // we should be much more explicit about why it's not constexpr.
1654 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1655 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1656 Info.Note(CD->getLocation(), diag::note_declared_at);
1657 } else {
1658 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1659 }
1660 }
1661 return true;
1662}
1663
Richard Smithc1c5f272011-12-13 06:39:58 +00001664/// CheckConstexprFunction - Check that a function can be called in a constant
1665/// expression.
1666static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1667 const FunctionDecl *Declaration,
1668 const FunctionDecl *Definition) {
1669 // Can we evaluate this function call?
1670 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1671 return true;
1672
1673 if (Info.getLangOpts().CPlusPlus0x) {
1674 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001675 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1676 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001677 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1678 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1679 << DiagDecl;
1680 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1681 } else {
1682 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1683 }
1684 return false;
1685}
1686
Richard Smith180f4792011-11-10 06:34:14 +00001687namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001688typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001689}
1690
1691/// EvaluateArgs - Evaluate the arguments to a function call.
1692static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1693 EvalInfo &Info) {
1694 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1695 I != E; ++I)
1696 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1697 return false;
1698 return true;
1699}
1700
Richard Smithd0dccea2011-10-28 22:34:42 +00001701/// Evaluate a function call.
Richard Smith08d6e032011-12-16 19:06:07 +00001702static bool HandleFunctionCall(const Expr *CallExpr, const FunctionDecl *Callee,
1703 const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00001704 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001705 EvalInfo &Info, APValue &Result) {
1706 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd0dccea2011-10-28 22:34:42 +00001707 return false;
1708
Richard Smith180f4792011-11-10 06:34:14 +00001709 ArgVector ArgValues(Args.size());
1710 if (!EvaluateArgs(Args, ArgValues, Info))
1711 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001712
Richard Smith08d6e032011-12-16 19:06:07 +00001713 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Callee, This,
1714 ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001715 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1716}
1717
Richard Smith180f4792011-11-10 06:34:14 +00001718/// Evaluate a constructor call.
Richard Smithf48fdb02011-12-09 22:58:01 +00001719static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001720 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001721 const CXXConstructorDecl *Definition,
Richard Smith59efe262011-11-11 04:05:33 +00001722 EvalInfo &Info,
Richard Smith180f4792011-11-10 06:34:14 +00001723 APValue &Result) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001724 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith180f4792011-11-10 06:34:14 +00001725 return false;
1726
1727 ArgVector ArgValues(Args.size());
1728 if (!EvaluateArgs(Args, ArgValues, Info))
1729 return false;
1730
Richard Smith08d6e032011-12-16 19:06:07 +00001731 CallStackFrame Frame(Info, CallExpr->getExprLoc(), Definition,
1732 &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00001733
1734 // If it's a delegating constructor, just delegate.
1735 if (Definition->isDelegatingConstructor()) {
1736 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1737 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1738 }
1739
1740 // Reserve space for the struct members.
1741 const CXXRecordDecl *RD = Definition->getParent();
1742 if (!RD->isUnion())
1743 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1744 std::distance(RD->field_begin(), RD->field_end()));
1745
1746 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1747
1748 unsigned BasesSeen = 0;
1749#ifndef NDEBUG
1750 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1751#endif
1752 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1753 E = Definition->init_end(); I != E; ++I) {
1754 if ((*I)->isBaseInitializer()) {
1755 QualType BaseType((*I)->getBaseClass(), 0);
1756#ifndef NDEBUG
1757 // Non-virtual base classes are initialized in the order in the class
1758 // definition. We cannot have a virtual base class for a literal type.
1759 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1760 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1761 "base class initializers not in expected order");
1762 ++BaseIt;
1763#endif
1764 LValue Subobject = This;
1765 HandleLValueDirectBase(Info, Subobject, RD,
1766 BaseType->getAsCXXRecordDecl(), &Layout);
1767 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1768 Subobject, (*I)->getInit()))
1769 return false;
1770 } else if (FieldDecl *FD = (*I)->getMember()) {
1771 LValue Subobject = This;
1772 HandleLValueMember(Info, Subobject, FD, &Layout);
1773 if (RD->isUnion()) {
1774 Result = APValue(FD);
Richard Smithc1c5f272011-12-13 06:39:58 +00001775 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1776 (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001777 return false;
1778 } else if (!EvaluateConstantExpression(
1779 Result.getStructField(FD->getFieldIndex()),
Richard Smithc1c5f272011-12-13 06:39:58 +00001780 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001781 return false;
1782 } else {
1783 // FIXME: handle indirect field initializers
Richard Smithdd1f29b2011-12-12 09:28:41 +00001784 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf48fdb02011-12-09 22:58:01 +00001785 diag::note_invalid_subexpr_in_const_expr);
Richard Smith180f4792011-11-10 06:34:14 +00001786 return false;
1787 }
1788 }
1789
1790 return true;
1791}
1792
Richard Smithd0dccea2011-10-28 22:34:42 +00001793namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001794class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001795 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00001796 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00001797public:
1798
Richard Smith1e12c592011-10-16 21:26:27 +00001799 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00001800
1801 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001802 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00001803 return true;
1804 }
1805
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001806 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1807 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001808 return Visit(E->getResultExpr());
1809 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001810 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001811 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001812 return true;
1813 return false;
1814 }
John McCallf85e1932011-06-15 23:02:42 +00001815 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001816 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001817 return true;
1818 return false;
1819 }
1820 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001821 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001822 return true;
1823 return false;
1824 }
1825
Mike Stumpc4c90452009-10-27 22:09:17 +00001826 // We don't want to evaluate BlockExprs multiple times, as they generate
1827 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001828 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1829 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1830 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00001831 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001832 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1833 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1834 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1835 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1836 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1837 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001838 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001839 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00001840 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001841 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00001842 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001843 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1844 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1845 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1846 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00001847 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001848 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1849 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1850 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1851 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1852 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001853 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001854 return true;
Mike Stump980ca222009-10-29 20:48:09 +00001855 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00001856 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001857 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00001858
1859 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001860 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00001861 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1862 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001863 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00001864 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00001865 return false;
1866 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00001867
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001868 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00001869};
1870
John McCall56ca35d2011-02-17 10:25:35 +00001871class OpaqueValueEvaluation {
1872 EvalInfo &info;
1873 OpaqueValueExpr *opaqueValue;
1874
1875public:
1876 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1877 Expr *value)
1878 : info(info), opaqueValue(opaqueValue) {
1879
1880 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00001881 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00001882 this->opaqueValue = 0;
1883 return;
1884 }
John McCall56ca35d2011-02-17 10:25:35 +00001885 }
1886
1887 bool hasError() const { return opaqueValue == 0; }
1888
1889 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00001890 // FIXME: This will not work for recursive constexpr functions using opaque
1891 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00001892 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1893 }
1894};
1895
Mike Stumpc4c90452009-10-27 22:09:17 +00001896} // end anonymous namespace
1897
Eli Friedman4efaa272008-11-12 09:44:48 +00001898//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001899// Generic Evaluation
1900//===----------------------------------------------------------------------===//
1901namespace {
1902
Richard Smithf48fdb02011-12-09 22:58:01 +00001903// FIXME: RetTy is always bool. Remove it.
1904template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001905class ExprEvaluatorBase
1906 : public ConstStmtVisitor<Derived, RetTy> {
1907private:
Richard Smith47a1eed2011-10-29 20:57:55 +00001908 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001909 return static_cast<Derived*>(this)->Success(V, E);
1910 }
Richard Smithf10d9172011-10-11 21:43:33 +00001911 RetTy DerivedValueInitialization(const Expr *E) {
1912 return static_cast<Derived*>(this)->ValueInitialization(E);
1913 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001914
1915protected:
1916 EvalInfo &Info;
1917 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1918 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1919
Richard Smithdd1f29b2011-12-12 09:28:41 +00001920 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00001921 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001922 }
1923
1924 /// Report an evaluation error. This should only be called when an error is
1925 /// first discovered. When propagating an error, just return false.
1926 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001927 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001928 return false;
1929 }
1930 bool Error(const Expr *E) {
1931 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1932 }
1933
1934 RetTy ValueInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00001935
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001936public:
1937 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1938
1939 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001940 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001941 }
1942 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001943 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001944 }
1945
1946 RetTy VisitParenExpr(const ParenExpr *E)
1947 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1948 RetTy VisitUnaryExtension(const UnaryOperator *E)
1949 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1950 RetTy VisitUnaryPlus(const UnaryOperator *E)
1951 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1952 RetTy VisitChooseExpr(const ChooseExpr *E)
1953 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1954 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1955 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00001956 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1957 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00001958 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1959 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00001960 // We cannot create any objects for which cleanups are required, so there is
1961 // nothing to do here; all cleanups must come from unevaluated subexpressions.
1962 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
1963 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001964
Richard Smithc216a012011-12-12 12:46:16 +00001965 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1966 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1967 return static_cast<Derived*>(this)->VisitCastExpr(E);
1968 }
1969 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1970 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1971 return static_cast<Derived*>(this)->VisitCastExpr(E);
1972 }
1973
Richard Smithe24f5fc2011-11-17 22:56:20 +00001974 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1975 switch (E->getOpcode()) {
1976 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00001977 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001978
1979 case BO_Comma:
1980 VisitIgnoredValue(E->getLHS());
1981 return StmtVisitorTy::Visit(E->getRHS());
1982
1983 case BO_PtrMemD:
1984 case BO_PtrMemI: {
1985 LValue Obj;
1986 if (!HandleMemberPointerAccess(Info, E, Obj))
1987 return false;
1988 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00001989 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001990 return false;
1991 return DerivedSuccess(Result, E);
1992 }
1993 }
1994 }
1995
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001996 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1997 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1998 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00001999 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002000
2001 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002002 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002003 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002004
2005 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2006 }
2007
2008 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2009 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002010 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002011 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002012
Richard Smithc49bd112011-10-28 17:51:58 +00002013 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002014 return StmtVisitorTy::Visit(EvalExpr);
2015 }
2016
2017 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002018 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002019 if (!Value) {
2020 const Expr *Source = E->getSourceExpr();
2021 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002022 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002023 if (Source == E) { // sanity checking.
2024 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002025 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002026 }
2027 return StmtVisitorTy::Visit(Source);
2028 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002029 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002030 }
Richard Smithf10d9172011-10-11 21:43:33 +00002031
Richard Smithd0dccea2011-10-28 22:34:42 +00002032 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002033 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002034 QualType CalleeType = Callee->getType();
2035
Richard Smithd0dccea2011-10-28 22:34:42 +00002036 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002037 LValue *This = 0, ThisVal;
2038 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002039
Richard Smith59efe262011-11-11 04:05:33 +00002040 // Extract function decl and 'this' pointer from the callee.
2041 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002042 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002043 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2044 // Explicit bound member calls, such as x.f() or p->g();
2045 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002046 return false;
2047 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002048 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002049 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2050 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002051 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2052 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002053 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002054 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002055 return Error(Callee);
2056
2057 FD = dyn_cast<FunctionDecl>(Member);
2058 if (!FD)
2059 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002060 } else if (CalleeType->isFunctionPointerType()) {
2061 CCValue Call;
Richard Smithf48fdb02011-12-09 22:58:01 +00002062 if (!Evaluate(Call, Info, Callee))
2063 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002064
Richard Smithf48fdb02011-12-09 22:58:01 +00002065 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
2066 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002067 FD = dyn_cast_or_null<FunctionDecl>(
2068 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002069 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002070 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002071
2072 // Overloaded operator calls to member functions are represented as normal
2073 // calls with '*this' as the first argument.
2074 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2075 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002076 // FIXME: When selecting an implicit conversion for an overloaded
2077 // operator delete, we sometimes try to evaluate calls to conversion
2078 // operators without a 'this' parameter!
2079 if (Args.empty())
2080 return Error(E);
2081
Richard Smith59efe262011-11-11 04:05:33 +00002082 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2083 return false;
2084 This = &ThisVal;
2085 Args = Args.slice(1);
2086 }
2087
2088 // Don't call function pointers which have been cast to some other type.
2089 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002090 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002091 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002092 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002093
Richard Smithc1c5f272011-12-13 06:39:58 +00002094 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002095 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002096 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002097
Richard Smithc1c5f272011-12-13 06:39:58 +00002098 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith08d6e032011-12-16 19:06:07 +00002099 !HandleFunctionCall(E, Definition, This, Args, Body, Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002100 return false;
2101
2102 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002103 }
2104
Richard Smithc49bd112011-10-28 17:51:58 +00002105 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2106 return StmtVisitorTy::Visit(E->getInitializer());
2107 }
Richard Smithf10d9172011-10-11 21:43:33 +00002108 RetTy VisitInitListExpr(const InitListExpr *E) {
2109 if (Info.getLangOpts().CPlusPlus0x) {
2110 if (E->getNumInits() == 0)
2111 return DerivedValueInitialization(E);
2112 if (E->getNumInits() == 1)
2113 return StmtVisitorTy::Visit(E->getInit(0));
2114 }
Richard Smithf48fdb02011-12-09 22:58:01 +00002115 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002116 }
2117 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
2118 return DerivedValueInitialization(E);
2119 }
2120 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
2121 return DerivedValueInitialization(E);
2122 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002123 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
2124 return DerivedValueInitialization(E);
2125 }
Richard Smithf10d9172011-10-11 21:43:33 +00002126
Richard Smith180f4792011-11-10 06:34:14 +00002127 /// A member expression where the object is a prvalue is itself a prvalue.
2128 RetTy VisitMemberExpr(const MemberExpr *E) {
2129 assert(!E->isArrow() && "missing call to bound member function?");
2130
2131 CCValue Val;
2132 if (!Evaluate(Val, Info, E->getBase()))
2133 return false;
2134
2135 QualType BaseTy = E->getBase()->getType();
2136
2137 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002138 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002139 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2140 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2141 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2142
2143 SubobjectDesignator Designator;
2144 Designator.addDecl(FD);
2145
Richard Smithf48fdb02011-12-09 22:58:01 +00002146 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002147 DerivedSuccess(Val, E);
2148 }
2149
Richard Smithc49bd112011-10-28 17:51:58 +00002150 RetTy VisitCastExpr(const CastExpr *E) {
2151 switch (E->getCastKind()) {
2152 default:
2153 break;
2154
2155 case CK_NoOp:
2156 return StmtVisitorTy::Visit(E->getSubExpr());
2157
2158 case CK_LValueToRValue: {
2159 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002160 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2161 return false;
2162 CCValue RVal;
2163 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2164 return false;
2165 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002166 }
2167 }
2168
Richard Smithf48fdb02011-12-09 22:58:01 +00002169 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002170 }
2171
Richard Smith8327fad2011-10-24 18:44:57 +00002172 /// Visit a value which is evaluated, but whose value is ignored.
2173 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002174 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002175 if (!Evaluate(Scratch, Info, E))
2176 Info.EvalStatus.HasSideEffects = true;
2177 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002178};
2179
2180}
2181
2182//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002183// Common base class for lvalue and temporary evaluation.
2184//===----------------------------------------------------------------------===//
2185namespace {
2186template<class Derived>
2187class LValueExprEvaluatorBase
2188 : public ExprEvaluatorBase<Derived, bool> {
2189protected:
2190 LValue &Result;
2191 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2192 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2193
2194 bool Success(APValue::LValueBase B) {
2195 Result.set(B);
2196 return true;
2197 }
2198
2199public:
2200 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2201 ExprEvaluatorBaseTy(Info), Result(Result) {}
2202
2203 bool Success(const CCValue &V, const Expr *E) {
2204 Result.setFrom(V);
2205 return true;
2206 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002207
2208 bool CheckValidLValue() {
2209 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
2210 // there are no null references, nor once-past-the-end references.
2211 // FIXME: Check for one-past-the-end array indices
2212 return Result.Base && !Result.Designator.Invalid &&
2213 !Result.Designator.OnePastTheEnd;
2214 }
2215
2216 bool VisitMemberExpr(const MemberExpr *E) {
2217 // Handle non-static data members.
2218 QualType BaseTy;
2219 if (E->isArrow()) {
2220 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2221 return false;
2222 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002223 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002224 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002225 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2226 return false;
2227 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002228 } else {
2229 if (!this->Visit(E->getBase()))
2230 return false;
2231 BaseTy = E->getBase()->getType();
2232 }
2233 // FIXME: In C++11, require the result to be a valid lvalue.
2234
2235 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2236 // FIXME: Handle IndirectFieldDecls
Richard Smithf48fdb02011-12-09 22:58:01 +00002237 if (!FD) return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002238 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2239 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2240 (void)BaseTy;
2241
2242 HandleLValueMember(this->Info, Result, FD);
2243
2244 if (FD->getType()->isReferenceType()) {
2245 CCValue RefValue;
Richard Smithf48fdb02011-12-09 22:58:01 +00002246 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002247 RefValue))
2248 return false;
2249 return Success(RefValue, E);
2250 }
2251 return true;
2252 }
2253
2254 bool VisitBinaryOperator(const BinaryOperator *E) {
2255 switch (E->getOpcode()) {
2256 default:
2257 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2258
2259 case BO_PtrMemD:
2260 case BO_PtrMemI:
2261 return HandleMemberPointerAccess(this->Info, E, Result);
2262 }
2263 }
2264
2265 bool VisitCastExpr(const CastExpr *E) {
2266 switch (E->getCastKind()) {
2267 default:
2268 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2269
2270 case CK_DerivedToBase:
2271 case CK_UncheckedDerivedToBase: {
2272 if (!this->Visit(E->getSubExpr()))
2273 return false;
2274 if (!CheckValidLValue())
2275 return false;
2276
2277 // Now figure out the necessary offset to add to the base LV to get from
2278 // the derived class to the base class.
2279 QualType Type = E->getSubExpr()->getType();
2280
2281 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2282 PathE = E->path_end(); PathI != PathE; ++PathI) {
2283 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2284 *PathI))
2285 return false;
2286 Type = (*PathI)->getType();
2287 }
2288
2289 return true;
2290 }
2291 }
2292 }
2293};
2294}
2295
2296//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002297// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002298//
2299// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2300// function designators (in C), decl references to void objects (in C), and
2301// temporaries (if building with -Wno-address-of-temporary).
2302//
2303// LValue evaluation produces values comprising a base expression of one of the
2304// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002305// - Declarations
2306// * VarDecl
2307// * FunctionDecl
2308// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002309// * CompoundLiteralExpr in C
2310// * StringLiteral
2311// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002312// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002313// * ObjCEncodeExpr
2314// * AddrLabelExpr
2315// * BlockExpr
2316// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002317// - Locals and temporaries
2318// * Any Expr, with a Frame indicating the function in which the temporary was
2319// evaluated.
2320// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002321//===----------------------------------------------------------------------===//
2322namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002323class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002324 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002325public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002326 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2327 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002328
Richard Smithc49bd112011-10-28 17:51:58 +00002329 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2330
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002331 bool VisitDeclRefExpr(const DeclRefExpr *E);
2332 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002333 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002334 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2335 bool VisitMemberExpr(const MemberExpr *E);
2336 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2337 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2338 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2339 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002340
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002341 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002342 switch (E->getCastKind()) {
2343 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002344 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002345
Eli Friedmandb924222011-10-11 00:13:24 +00002346 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002347 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002348 if (!Visit(E->getSubExpr()))
2349 return false;
2350 Result.Designator.setInvalid();
2351 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002352
Richard Smithe24f5fc2011-11-17 22:56:20 +00002353 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002354 if (!Visit(E->getSubExpr()))
2355 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002356 if (!CheckValidLValue())
2357 return false;
2358 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002359 }
2360 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002361
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002362 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002363
Eli Friedman4efaa272008-11-12 09:44:48 +00002364};
2365} // end anonymous namespace
2366
Richard Smithc49bd112011-10-28 17:51:58 +00002367/// Evaluate an expression as an lvalue. This can be legitimately called on
2368/// expressions which are not glvalues, in a few cases:
2369/// * function designators in C,
2370/// * "extern void" objects,
2371/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002372static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002373 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2374 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2375 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002376 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002377}
2378
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002379bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002380 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2381 return Success(FD);
2382 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002383 return VisitVarDecl(E, VD);
2384 return Error(E);
2385}
Richard Smith436c8892011-10-24 23:14:33 +00002386
Richard Smithc49bd112011-10-28 17:51:58 +00002387bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002388 if (!VD->getType()->isReferenceType()) {
2389 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002390 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002391 return true;
2392 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002393 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002394 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002395
Richard Smith47a1eed2011-10-29 20:57:55 +00002396 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002397 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2398 return false;
2399 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002400}
2401
Richard Smithbd552ef2011-10-31 05:52:43 +00002402bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2403 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002404 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002405 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002406 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2407
2408 Result.set(E, Info.CurrentCall);
2409 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2410 Result, E->GetTemporaryExpr());
2411 }
2412
2413 // Materialization of an lvalue temporary occurs when we need to force a copy
2414 // (for instance, if it's a bitfield).
2415 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2416 if (!Visit(E->GetTemporaryExpr()))
2417 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002418 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002419 Info.CurrentCall->Temporaries[E]))
2420 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002421 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002422 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002423}
2424
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002425bool
2426LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002427 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2428 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2429 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002430 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002431}
2432
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002433bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002434 // Handle static data members.
2435 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2436 VisitIgnoredValue(E->getBase());
2437 return VisitVarDecl(E, VD);
2438 }
2439
Richard Smithd0dccea2011-10-28 22:34:42 +00002440 // Handle static member functions.
2441 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2442 if (MD->isStatic()) {
2443 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002444 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002445 }
2446 }
2447
Richard Smith180f4792011-11-10 06:34:14 +00002448 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002449 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002450}
2451
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002452bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002453 // FIXME: Deal with vectors as array subscript bases.
2454 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002455 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002456
Anders Carlsson3068d112008-11-16 19:01:22 +00002457 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002458 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002459
Anders Carlsson3068d112008-11-16 19:01:22 +00002460 APSInt Index;
2461 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002462 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002463 int64_t IndexValue
2464 = Index.isSigned() ? Index.getSExtValue()
2465 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002466
Richard Smithe24f5fc2011-11-17 22:56:20 +00002467 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smith180f4792011-11-10 06:34:14 +00002468 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002469}
Eli Friedman4efaa272008-11-12 09:44:48 +00002470
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002471bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002472 // FIXME: In C++11, require the result to be a valid lvalue.
John McCallefdb83e2010-05-07 21:00:08 +00002473 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002474}
2475
Eli Friedman4efaa272008-11-12 09:44:48 +00002476//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002477// Pointer Evaluation
2478//===----------------------------------------------------------------------===//
2479
Anders Carlssonc754aa62008-07-08 05:13:58 +00002480namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002481class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002482 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002483 LValue &Result;
2484
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002485 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002486 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002487 return true;
2488 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002489public:
Mike Stump1eb44332009-09-09 15:08:12 +00002490
John McCallefdb83e2010-05-07 21:00:08 +00002491 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002492 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002493
Richard Smith47a1eed2011-10-29 20:57:55 +00002494 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002495 Result.setFrom(V);
2496 return true;
2497 }
Richard Smithf10d9172011-10-11 21:43:33 +00002498 bool ValueInitialization(const Expr *E) {
2499 return Success((Expr*)0);
2500 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002501
John McCallefdb83e2010-05-07 21:00:08 +00002502 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002503 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002504 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002505 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002506 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002507 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002508 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002509 bool VisitCallExpr(const CallExpr *E);
2510 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002511 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002512 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002513 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002514 }
Richard Smith180f4792011-11-10 06:34:14 +00002515 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2516 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002517 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002518 Result = *Info.CurrentCall->This;
2519 return true;
2520 }
John McCall56ca35d2011-02-17 10:25:35 +00002521
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002522 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002523};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002524} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002525
John McCallefdb83e2010-05-07 21:00:08 +00002526static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002527 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002528 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002529}
2530
John McCallefdb83e2010-05-07 21:00:08 +00002531bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002532 if (E->getOpcode() != BO_Add &&
2533 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002534 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002535
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002536 const Expr *PExp = E->getLHS();
2537 const Expr *IExp = E->getRHS();
2538 if (IExp->getType()->isPointerType())
2539 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002540
John McCallefdb83e2010-05-07 21:00:08 +00002541 if (!EvaluatePointer(PExp, Result, Info))
2542 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002543
John McCallefdb83e2010-05-07 21:00:08 +00002544 llvm::APSInt Offset;
2545 if (!EvaluateInteger(IExp, Offset, Info))
2546 return false;
2547 int64_t AdditionalOffset
2548 = Offset.isSigned() ? Offset.getSExtValue()
2549 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002550 if (E->getOpcode() == BO_Sub)
2551 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002552
Richard Smith180f4792011-11-10 06:34:14 +00002553 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002554 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smith180f4792011-11-10 06:34:14 +00002555 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002556}
Eli Friedman4efaa272008-11-12 09:44:48 +00002557
John McCallefdb83e2010-05-07 21:00:08 +00002558bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2559 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002560}
Mike Stump1eb44332009-09-09 15:08:12 +00002561
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002562bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2563 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002564
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002565 switch (E->getCastKind()) {
2566 default:
2567 break;
2568
John McCall2de56d12010-08-25 11:45:40 +00002569 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002570 case CK_CPointerToObjCPointerCast:
2571 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002572 case CK_AnyPointerToBlockPointerCast:
Richard Smithc216a012011-12-12 12:46:16 +00002573 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2574 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2575 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002576 if (!E->getType()->isVoidPointerType()) {
2577 if (SubExpr->getType()->isVoidPointerType())
2578 CCEDiag(E, diag::note_constexpr_invalid_cast)
2579 << 3 << SubExpr->getType();
2580 else
2581 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2582 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002583 if (!Visit(SubExpr))
2584 return false;
2585 Result.Designator.setInvalid();
2586 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002587
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002588 case CK_DerivedToBase:
2589 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002590 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002591 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002592 if (!Result.Base && Result.Offset.isZero())
2593 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002594
Richard Smith180f4792011-11-10 06:34:14 +00002595 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002596 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002597 QualType Type =
2598 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002599
Richard Smith180f4792011-11-10 06:34:14 +00002600 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002601 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smith180f4792011-11-10 06:34:14 +00002602 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002603 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002604 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002605 }
2606
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002607 return true;
2608 }
2609
Richard Smithe24f5fc2011-11-17 22:56:20 +00002610 case CK_BaseToDerived:
2611 if (!Visit(E->getSubExpr()))
2612 return false;
2613 if (!Result.Base && Result.Offset.isZero())
2614 return true;
2615 return HandleBaseToDerivedCast(Info, E, Result);
2616
Richard Smith47a1eed2011-10-29 20:57:55 +00002617 case CK_NullToPointer:
2618 return ValueInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002619
John McCall2de56d12010-08-25 11:45:40 +00002620 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002621 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2622
Richard Smith47a1eed2011-10-29 20:57:55 +00002623 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002624 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002625 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002626
John McCallefdb83e2010-05-07 21:00:08 +00002627 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002628 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2629 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002630 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002631 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002632 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002633 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002634 return true;
2635 } else {
2636 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002637 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002638 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002639 }
2640 }
John McCall2de56d12010-08-25 11:45:40 +00002641 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002642 if (SubExpr->isGLValue()) {
2643 if (!EvaluateLValue(SubExpr, Result, Info))
2644 return false;
2645 } else {
2646 Result.set(SubExpr, Info.CurrentCall);
2647 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2648 Info, Result, SubExpr))
2649 return false;
2650 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002651 // The result is a pointer to the first element of the array.
2652 Result.Designator.addIndex(0);
2653 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002654
John McCall2de56d12010-08-25 11:45:40 +00002655 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002656 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002657 }
2658
Richard Smithc49bd112011-10-28 17:51:58 +00002659 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002660}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002661
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002662bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002663 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002664 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002665
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002666 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002667}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002668
2669//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002670// Member Pointer Evaluation
2671//===----------------------------------------------------------------------===//
2672
2673namespace {
2674class MemberPointerExprEvaluator
2675 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2676 MemberPtr &Result;
2677
2678 bool Success(const ValueDecl *D) {
2679 Result = MemberPtr(D);
2680 return true;
2681 }
2682public:
2683
2684 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2685 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2686
2687 bool Success(const CCValue &V, const Expr *E) {
2688 Result.setFrom(V);
2689 return true;
2690 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002691 bool ValueInitialization(const Expr *E) {
2692 return Success((const ValueDecl*)0);
2693 }
2694
2695 bool VisitCastExpr(const CastExpr *E);
2696 bool VisitUnaryAddrOf(const UnaryOperator *E);
2697};
2698} // end anonymous namespace
2699
2700static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2701 EvalInfo &Info) {
2702 assert(E->isRValue() && E->getType()->isMemberPointerType());
2703 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2704}
2705
2706bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2707 switch (E->getCastKind()) {
2708 default:
2709 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2710
2711 case CK_NullToMemberPointer:
2712 return ValueInitialization(E);
2713
2714 case CK_BaseToDerivedMemberPointer: {
2715 if (!Visit(E->getSubExpr()))
2716 return false;
2717 if (E->path_empty())
2718 return true;
2719 // Base-to-derived member pointer casts store the path in derived-to-base
2720 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2721 // the wrong end of the derived->base arc, so stagger the path by one class.
2722 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2723 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2724 PathI != PathE; ++PathI) {
2725 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2726 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2727 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00002728 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002729 }
2730 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2731 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002732 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002733 return true;
2734 }
2735
2736 case CK_DerivedToBaseMemberPointer:
2737 if (!Visit(E->getSubExpr()))
2738 return false;
2739 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2740 PathE = E->path_end(); PathI != PathE; ++PathI) {
2741 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2742 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2743 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00002744 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002745 }
2746 return true;
2747 }
2748}
2749
2750bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2751 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2752 // member can be formed.
2753 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2754}
2755
2756//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00002757// Record Evaluation
2758//===----------------------------------------------------------------------===//
2759
2760namespace {
2761 class RecordExprEvaluator
2762 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2763 const LValue &This;
2764 APValue &Result;
2765 public:
2766
2767 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2768 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2769
2770 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002771 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00002772 }
Richard Smith180f4792011-11-10 06:34:14 +00002773
Richard Smith59efe262011-11-11 04:05:33 +00002774 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00002775 bool VisitInitListExpr(const InitListExpr *E);
2776 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2777 };
2778}
2779
Richard Smith59efe262011-11-11 04:05:33 +00002780bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2781 switch (E->getCastKind()) {
2782 default:
2783 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2784
2785 case CK_ConstructorConversion:
2786 return Visit(E->getSubExpr());
2787
2788 case CK_DerivedToBase:
2789 case CK_UncheckedDerivedToBase: {
2790 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00002791 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00002792 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002793 if (!DerivedObject.isStruct())
2794 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00002795
2796 // Derived-to-base rvalue conversion: just slice off the derived part.
2797 APValue *Value = &DerivedObject;
2798 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2799 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2800 PathE = E->path_end(); PathI != PathE; ++PathI) {
2801 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2802 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2803 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2804 RD = Base;
2805 }
2806 Result = *Value;
2807 return true;
2808 }
2809 }
2810}
2811
Richard Smith180f4792011-11-10 06:34:14 +00002812bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2813 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2814 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2815
2816 if (RD->isUnion()) {
2817 Result = APValue(E->getInitializedFieldInUnion());
2818 if (!E->getNumInits())
2819 return true;
2820 LValue Subobject = This;
2821 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2822 &Layout);
2823 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2824 Subobject, E->getInit(0));
2825 }
2826
2827 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2828 "initializer list for class with base classes");
2829 Result = APValue(APValue::UninitStruct(), 0,
2830 std::distance(RD->field_begin(), RD->field_end()));
2831 unsigned ElementNo = 0;
2832 for (RecordDecl::field_iterator Field = RD->field_begin(),
2833 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2834 // Anonymous bit-fields are not considered members of the class for
2835 // purposes of aggregate initialization.
2836 if (Field->isUnnamedBitfield())
2837 continue;
2838
2839 LValue Subobject = This;
2840 HandleLValueMember(Info, Subobject, *Field, &Layout);
2841
2842 if (ElementNo < E->getNumInits()) {
2843 if (!EvaluateConstantExpression(
2844 Result.getStructField((*Field)->getFieldIndex()),
2845 Info, Subobject, E->getInit(ElementNo++)))
2846 return false;
2847 } else {
2848 // Perform an implicit value-initialization for members beyond the end of
2849 // the initializer list.
2850 ImplicitValueInitExpr VIE(Field->getType());
2851 if (!EvaluateConstantExpression(
2852 Result.getStructField((*Field)->getFieldIndex()),
2853 Info, Subobject, &VIE))
2854 return false;
2855 }
2856 }
2857
2858 return true;
2859}
2860
2861bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2862 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00002863 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD)) {
2864 const CXXRecordDecl *RD = FD->getParent();
2865 if (RD->isUnion())
2866 Result = APValue((FieldDecl*)0);
2867 else
2868 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2869 std::distance(RD->field_begin(), RD->field_end()));
2870 return true;
2871 }
2872
Richard Smith180f4792011-11-10 06:34:14 +00002873 const FunctionDecl *Definition = 0;
2874 FD->getBody(Definition);
2875
Richard Smithc1c5f272011-12-13 06:39:58 +00002876 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2877 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002878
2879 // FIXME: Elide the copy/move construction wherever we can.
2880 if (E->isElidable())
2881 if (const MaterializeTemporaryExpr *ME
2882 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2883 return Visit(ME->GetTemporaryExpr());
2884
2885 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00002886 return HandleConstructorCall(E, This, Args,
2887 cast<CXXConstructorDecl>(Definition), Info,
2888 Result);
Richard Smith180f4792011-11-10 06:34:14 +00002889}
2890
2891static bool EvaluateRecord(const Expr *E, const LValue &This,
2892 APValue &Result, EvalInfo &Info) {
2893 assert(E->isRValue() && E->getType()->isRecordType() &&
2894 E->getType()->isLiteralType() &&
2895 "can't evaluate expression as a record rvalue");
2896 return RecordExprEvaluator(Info, This, Result).Visit(E);
2897}
2898
2899//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002900// Temporary Evaluation
2901//
2902// Temporaries are represented in the AST as rvalues, but generally behave like
2903// lvalues. The full-object of which the temporary is a subobject is implicitly
2904// materialized so that a reference can bind to it.
2905//===----------------------------------------------------------------------===//
2906namespace {
2907class TemporaryExprEvaluator
2908 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
2909public:
2910 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
2911 LValueExprEvaluatorBaseTy(Info, Result) {}
2912
2913 /// Visit an expression which constructs the value of this temporary.
2914 bool VisitConstructExpr(const Expr *E) {
2915 Result.set(E, Info.CurrentCall);
2916 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2917 Result, E);
2918 }
2919
2920 bool VisitCastExpr(const CastExpr *E) {
2921 switch (E->getCastKind()) {
2922 default:
2923 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2924
2925 case CK_ConstructorConversion:
2926 return VisitConstructExpr(E->getSubExpr());
2927 }
2928 }
2929 bool VisitInitListExpr(const InitListExpr *E) {
2930 return VisitConstructExpr(E);
2931 }
2932 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2933 return VisitConstructExpr(E);
2934 }
2935 bool VisitCallExpr(const CallExpr *E) {
2936 return VisitConstructExpr(E);
2937 }
2938};
2939} // end anonymous namespace
2940
2941/// Evaluate an expression of record type as a temporary.
2942static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002943 assert(E->isRValue() && E->getType()->isRecordType());
2944 if (!E->getType()->isLiteralType()) {
2945 if (Info.getLangOpts().CPlusPlus0x)
2946 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
2947 << E->getType();
2948 else
2949 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
2950 return false;
2951 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002952 return TemporaryExprEvaluator(Info, Result).Visit(E);
2953}
2954
2955//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00002956// Vector Evaluation
2957//===----------------------------------------------------------------------===//
2958
2959namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002960 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00002961 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
2962 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00002963 public:
Mike Stump1eb44332009-09-09 15:08:12 +00002964
Richard Smith07fc6572011-10-22 21:10:00 +00002965 VectorExprEvaluator(EvalInfo &info, APValue &Result)
2966 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002967
Richard Smith07fc6572011-10-22 21:10:00 +00002968 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
2969 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
2970 // FIXME: remove this APValue copy.
2971 Result = APValue(V.data(), V.size());
2972 return true;
2973 }
Richard Smith69c2c502011-11-04 05:33:44 +00002974 bool Success(const CCValue &V, const Expr *E) {
2975 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00002976 Result = V;
2977 return true;
2978 }
Richard Smith07fc6572011-10-22 21:10:00 +00002979 bool ValueInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002980
Richard Smith07fc6572011-10-22 21:10:00 +00002981 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00002982 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00002983 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00002984 bool VisitInitListExpr(const InitListExpr *E);
2985 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002986 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00002987 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00002988 // shufflevector, ExtVectorElementExpr
2989 // (Note that these require implementing conversions
2990 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +00002991 };
2992} // end anonymous namespace
2993
2994static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002995 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00002996 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00002997}
2998
Richard Smith07fc6572011-10-22 21:10:00 +00002999bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3000 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003001 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Richard Smithd62ca372011-12-06 22:44:34 +00003003 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003004 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003005
Eli Friedman46a52322011-03-25 00:43:55 +00003006 switch (E->getCastKind()) {
3007 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003008 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003009 if (SETy->isIntegerType()) {
3010 APSInt IntResult;
3011 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003012 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003013 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003014 } else if (SETy->isRealFloatingType()) {
3015 APFloat F(0.0);
3016 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003017 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003018 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003019 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003020 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003021 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003022
3023 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003024 SmallVector<APValue, 4> Elts(NElts, Val);
3025 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003026 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003027 case CK_BitCast: {
3028 // Evaluate the operand into an APInt we can extract from.
3029 llvm::APInt SValInt;
3030 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3031 return false;
3032 // Extract the elements
3033 QualType EltTy = VTy->getElementType();
3034 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3035 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3036 SmallVector<APValue, 4> Elts;
3037 if (EltTy->isRealFloatingType()) {
3038 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3039 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3040 unsigned FloatEltSize = EltSize;
3041 if (&Sem == &APFloat::x87DoubleExtended)
3042 FloatEltSize = 80;
3043 for (unsigned i = 0; i < NElts; i++) {
3044 llvm::APInt Elt;
3045 if (BigEndian)
3046 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3047 else
3048 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3049 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3050 }
3051 } else if (EltTy->isIntegerType()) {
3052 for (unsigned i = 0; i < NElts; i++) {
3053 llvm::APInt Elt;
3054 if (BigEndian)
3055 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3056 else
3057 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3058 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3059 }
3060 } else {
3061 return Error(E);
3062 }
3063 return Success(Elts, E);
3064 }
Eli Friedman46a52322011-03-25 00:43:55 +00003065 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003066 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003067 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003068}
3069
Richard Smith07fc6572011-10-22 21:10:00 +00003070bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003071VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003072 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003073 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003074 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003075
Nate Begeman59b5da62009-01-18 03:20:47 +00003076 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003077 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003078
John McCalla7d6c222010-06-11 17:54:15 +00003079 // If a vector is initialized with a single element, that value
3080 // becomes every element of the vector, not just the first.
3081 // This is the behavior described in the IBM AltiVec documentation.
3082 if (NumInits == 1) {
Richard Smith07fc6572011-10-22 21:10:00 +00003083
3084 // Handle the case where the vector is initialized by another
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +00003085 // vector (OpenCL 6.1.6).
3086 if (E->getInit(0)->getType()->isVectorType())
Richard Smith07fc6572011-10-22 21:10:00 +00003087 return Visit(E->getInit(0));
3088
John McCalla7d6c222010-06-11 17:54:15 +00003089 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +00003090 if (EltTy->isIntegerType()) {
3091 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +00003092 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003093 return false;
John McCalla7d6c222010-06-11 17:54:15 +00003094 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +00003095 } else {
3096 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +00003097 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003098 return false;
John McCalla7d6c222010-06-11 17:54:15 +00003099 InitValue = APValue(f);
3100 }
3101 for (unsigned i = 0; i < NumElements; i++) {
3102 Elements.push_back(InitValue);
3103 }
3104 } else {
3105 for (unsigned i = 0; i < NumElements; i++) {
3106 if (EltTy->isIntegerType()) {
3107 llvm::APSInt sInt(32);
3108 if (i < NumInits) {
3109 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003110 return false;
John McCalla7d6c222010-06-11 17:54:15 +00003111 } else {
3112 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3113 }
3114 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +00003115 } else {
John McCalla7d6c222010-06-11 17:54:15 +00003116 llvm::APFloat f(0.0);
3117 if (i < NumInits) {
3118 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003119 return false;
John McCalla7d6c222010-06-11 17:54:15 +00003120 } else {
3121 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3122 }
3123 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +00003124 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003125 }
3126 }
Richard Smith07fc6572011-10-22 21:10:00 +00003127 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003128}
3129
Richard Smith07fc6572011-10-22 21:10:00 +00003130bool
3131VectorExprEvaluator::ValueInitialization(const Expr *E) {
3132 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003133 QualType EltTy = VT->getElementType();
3134 APValue ZeroElement;
3135 if (EltTy->isIntegerType())
3136 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3137 else
3138 ZeroElement =
3139 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3140
Chris Lattner5f9e2722011-07-23 10:55:15 +00003141 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003142 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003143}
3144
Richard Smith07fc6572011-10-22 21:10:00 +00003145bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003146 VisitIgnoredValue(E->getSubExpr());
Richard Smith07fc6572011-10-22 21:10:00 +00003147 return ValueInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003148}
3149
Nate Begeman59b5da62009-01-18 03:20:47 +00003150//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003151// Array Evaluation
3152//===----------------------------------------------------------------------===//
3153
3154namespace {
3155 class ArrayExprEvaluator
3156 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003157 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003158 APValue &Result;
3159 public:
3160
Richard Smith180f4792011-11-10 06:34:14 +00003161 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3162 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003163
3164 bool Success(const APValue &V, const Expr *E) {
3165 assert(V.isArray() && "Expected array type");
3166 Result = V;
3167 return true;
3168 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003169
Richard Smith180f4792011-11-10 06:34:14 +00003170 bool ValueInitialization(const Expr *E) {
3171 const ConstantArrayType *CAT =
3172 Info.Ctx.getAsConstantArrayType(E->getType());
3173 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003174 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003175
3176 Result = APValue(APValue::UninitArray(), 0,
3177 CAT->getSize().getZExtValue());
3178 if (!Result.hasArrayFiller()) return true;
3179
3180 // Value-initialize all elements.
3181 LValue Subobject = This;
3182 Subobject.Designator.addIndex(0);
3183 ImplicitValueInitExpr VIE(CAT->getElementType());
3184 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3185 Subobject, &VIE);
3186 }
3187
Richard Smithcc5d4f62011-11-07 09:22:26 +00003188 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003189 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003190 };
3191} // end anonymous namespace
3192
Richard Smith180f4792011-11-10 06:34:14 +00003193static bool EvaluateArray(const Expr *E, const LValue &This,
3194 APValue &Result, EvalInfo &Info) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00003195 assert(E->isRValue() && E->getType()->isArrayType() &&
3196 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003197 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003198}
3199
3200bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3201 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3202 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003203 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003204
Richard Smith974c5f92011-12-22 01:07:19 +00003205 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3206 // an appropriately-typed string literal enclosed in braces.
3207 if (E->getNumInits() == 1 && CAT->getElementType()->isAnyCharacterType() &&
3208 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3209 LValue LV;
3210 if (!EvaluateLValue(E->getInit(0), LV, Info))
3211 return false;
3212 uint64_t NumElements = CAT->getSize().getZExtValue();
3213 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3214
3215 // Copy the string literal into the array. FIXME: Do this better.
3216 LV.Designator.addIndex(0);
3217 for (uint64_t I = 0; I < NumElements; ++I) {
3218 CCValue Char;
3219 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3220 CAT->getElementType(), LV, Char))
3221 return false;
3222 if (!CheckConstantExpression(Info, E->getInit(0), Char,
3223 Result.getArrayInitializedElt(I)))
3224 return false;
3225 if (!HandleLValueArrayAdjustment(Info, LV, CAT->getElementType(), 1))
3226 return false;
3227 }
3228 return true;
3229 }
3230
Richard Smithcc5d4f62011-11-07 09:22:26 +00003231 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3232 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003233 LValue Subobject = This;
3234 Subobject.Designator.addIndex(0);
3235 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003236 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003237 I != End; ++I, ++Index) {
3238 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3239 Info, Subobject, cast<Expr>(*I)))
Richard Smithcc5d4f62011-11-07 09:22:26 +00003240 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003241 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
3242 return false;
3243 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003244
3245 if (!Result.hasArrayFiller()) return true;
3246 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003247 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3248 // but sometimes does:
3249 // struct S { constexpr S() : p(&p) {} void *p; };
3250 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003251 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith180f4792011-11-10 06:34:14 +00003252 Subobject, E->getArrayFiller());
Richard Smithcc5d4f62011-11-07 09:22:26 +00003253}
3254
Richard Smithe24f5fc2011-11-17 22:56:20 +00003255bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3256 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3257 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003258 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003259
3260 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3261 if (!Result.hasArrayFiller())
3262 return true;
3263
3264 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003265
3266 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD)) {
3267 const CXXRecordDecl *RD = FD->getParent();
3268 if (RD->isUnion())
3269 Result.getArrayFiller() = APValue((FieldDecl*)0);
3270 else
3271 Result.getArrayFiller() =
3272 APValue(APValue::UninitStruct(), RD->getNumBases(),
3273 std::distance(RD->field_begin(), RD->field_end()));
3274 return true;
3275 }
3276
Richard Smithe24f5fc2011-11-17 22:56:20 +00003277 const FunctionDecl *Definition = 0;
3278 FD->getBody(Definition);
3279
Richard Smithc1c5f272011-12-13 06:39:58 +00003280 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3281 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003282
3283 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3284 // but sometimes does:
3285 // struct S { constexpr S() : p(&p) {} void *p; };
3286 // S s[10];
3287 LValue Subobject = This;
3288 Subobject.Designator.addIndex(0);
3289 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00003290 return HandleConstructorCall(E, Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003291 cast<CXXConstructorDecl>(Definition),
3292 Info, Result.getArrayFiller());
3293}
3294
Richard Smithcc5d4f62011-11-07 09:22:26 +00003295//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003296// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003297//
3298// As a GNU extension, we support casting pointers to sufficiently-wide integer
3299// types and back in constant folding. Integer values are thus represented
3300// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003301//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003302
3303namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003304class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003305 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003306 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003307public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003308 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003309 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003310
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003311 bool Success(const llvm::APSInt &SI, const Expr *E) {
3312 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003313 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003314 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003315 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003316 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003317 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003318 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003319 return true;
3320 }
3321
Daniel Dunbar131eb432009-02-19 09:06:44 +00003322 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003323 assert(E->getType()->isIntegralOrEnumerationType() &&
3324 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003325 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003326 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003327 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003328 Result.getInt().setIsUnsigned(
3329 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003330 return true;
3331 }
3332
3333 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003334 assert(E->getType()->isIntegralOrEnumerationType() &&
3335 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003336 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003337 return true;
3338 }
3339
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003340 bool Success(CharUnits Size, const Expr *E) {
3341 return Success(Size.getQuantity(), E);
3342 }
3343
Richard Smith47a1eed2011-10-29 20:57:55 +00003344 bool Success(const CCValue &V, const Expr *E) {
Richard Smith342f1f82011-10-29 22:55:55 +00003345 if (V.isLValue()) {
3346 Result = V;
3347 return true;
3348 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003349 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003350 }
Mike Stump1eb44332009-09-09 15:08:12 +00003351
Richard Smithf10d9172011-10-11 21:43:33 +00003352 bool ValueInitialization(const Expr *E) { return Success(0, E); }
3353
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003354 //===--------------------------------------------------------------------===//
3355 // Visitor Methods
3356 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003357
Chris Lattner4c4867e2008-07-12 00:38:25 +00003358 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003359 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003360 }
3361 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003362 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003363 }
Eli Friedman04309752009-11-24 05:28:59 +00003364
3365 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3366 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003367 if (CheckReferencedDecl(E, E->getDecl()))
3368 return true;
3369
3370 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003371 }
3372 bool VisitMemberExpr(const MemberExpr *E) {
3373 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003374 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003375 return true;
3376 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003377
3378 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003379 }
3380
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003381 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003382 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003383 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003384 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003385
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003386 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003387 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003388
Anders Carlsson3068d112008-11-16 19:01:22 +00003389 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003390 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003391 }
Mike Stump1eb44332009-09-09 15:08:12 +00003392
Richard Smithf10d9172011-10-11 21:43:33 +00003393 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003394 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003395 return ValueInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003396 }
3397
Sebastian Redl64b45f72009-01-05 20:52:13 +00003398 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003399 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003400 }
3401
Francois Pichet6ad6f282010-12-07 00:08:36 +00003402 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3403 return Success(E->getValue(), E);
3404 }
3405
John Wiegley21ff2e52011-04-28 00:16:57 +00003406 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3407 return Success(E->getValue(), E);
3408 }
3409
John Wiegley55262202011-04-25 06:54:41 +00003410 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3411 return Success(E->getValue(), E);
3412 }
3413
Eli Friedman722c7172009-02-28 03:59:05 +00003414 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003415 bool VisitUnaryImag(const UnaryOperator *E);
3416
Sebastian Redl295995c2010-09-10 20:55:47 +00003417 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003418 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003419
Chris Lattnerfcee0012008-07-11 21:24:13 +00003420private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003421 CharUnits GetAlignOfExpr(const Expr *E);
3422 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003423 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003424 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003425 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003426};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003427} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003428
Richard Smithc49bd112011-10-28 17:51:58 +00003429/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3430/// produce either the integer value or a pointer.
3431///
3432/// GCC has a heinous extension which folds casts between pointer types and
3433/// pointer-sized integral types. We support this by allowing the evaluation of
3434/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3435/// Some simple arithmetic on such values is supported (they are treated much
3436/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003437static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003438 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003439 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003440 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003441}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003442
Richard Smithf48fdb02011-12-09 22:58:01 +00003443static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003444 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003445 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003446 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003447 if (!Val.isInt()) {
3448 // FIXME: It would be better to produce the diagnostic for casting
3449 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003450 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003451 return false;
3452 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003453 Result = Val.getInt();
3454 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003455}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003456
Richard Smithf48fdb02011-12-09 22:58:01 +00003457/// Check whether the given declaration can be directly converted to an integral
3458/// rvalue. If not, no diagnostic is produced; there are other things we can
3459/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003460bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003461 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003462 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003463 // Check for signedness/width mismatches between E type and ECD value.
3464 bool SameSign = (ECD->getInitVal().isSigned()
3465 == E->getType()->isSignedIntegerOrEnumerationType());
3466 bool SameWidth = (ECD->getInitVal().getBitWidth()
3467 == Info.Ctx.getIntWidth(E->getType()));
3468 if (SameSign && SameWidth)
3469 return Success(ECD->getInitVal(), E);
3470 else {
3471 // Get rid of mismatch (otherwise Success assertions will fail)
3472 // by computing a new value matching the type of E.
3473 llvm::APSInt Val = ECD->getInitVal();
3474 if (!SameSign)
3475 Val.setIsSigned(!ECD->getInitVal().isSigned());
3476 if (!SameWidth)
3477 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3478 return Success(Val, E);
3479 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003480 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003481 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003482}
3483
Chris Lattnera4d55d82008-10-06 06:40:35 +00003484/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3485/// as GCC.
3486static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3487 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003488 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003489 enum gcc_type_class {
3490 no_type_class = -1,
3491 void_type_class, integer_type_class, char_type_class,
3492 enumeral_type_class, boolean_type_class,
3493 pointer_type_class, reference_type_class, offset_type_class,
3494 real_type_class, complex_type_class,
3495 function_type_class, method_type_class,
3496 record_type_class, union_type_class,
3497 array_type_class, string_type_class,
3498 lang_type_class
3499 };
Mike Stump1eb44332009-09-09 15:08:12 +00003500
3501 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003502 // ideal, however it is what gcc does.
3503 if (E->getNumArgs() == 0)
3504 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Chris Lattnera4d55d82008-10-06 06:40:35 +00003506 QualType ArgTy = E->getArg(0)->getType();
3507 if (ArgTy->isVoidType())
3508 return void_type_class;
3509 else if (ArgTy->isEnumeralType())
3510 return enumeral_type_class;
3511 else if (ArgTy->isBooleanType())
3512 return boolean_type_class;
3513 else if (ArgTy->isCharType())
3514 return string_type_class; // gcc doesn't appear to use char_type_class
3515 else if (ArgTy->isIntegerType())
3516 return integer_type_class;
3517 else if (ArgTy->isPointerType())
3518 return pointer_type_class;
3519 else if (ArgTy->isReferenceType())
3520 return reference_type_class;
3521 else if (ArgTy->isRealType())
3522 return real_type_class;
3523 else if (ArgTy->isComplexType())
3524 return complex_type_class;
3525 else if (ArgTy->isFunctionType())
3526 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003527 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003528 return record_type_class;
3529 else if (ArgTy->isUnionType())
3530 return union_type_class;
3531 else if (ArgTy->isArrayType())
3532 return array_type_class;
3533 else if (ArgTy->isUnionType())
3534 return union_type_class;
3535 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003536 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003537 return -1;
3538}
3539
John McCall42c8f872010-05-10 23:27:23 +00003540/// Retrieves the "underlying object type" of the given expression,
3541/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003542QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3543 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3544 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003545 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003546 } else if (const Expr *E = B.get<const Expr*>()) {
3547 if (isa<CompoundLiteralExpr>(E))
3548 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003549 }
3550
3551 return QualType();
3552}
3553
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003554bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003555 // TODO: Perhaps we should let LLVM lower this?
3556 LValue Base;
3557 if (!EvaluatePointer(E->getArg(0), Base, Info))
3558 return false;
3559
3560 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003561 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003562
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003563 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003564 if (T.isNull() ||
3565 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00003566 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00003567 T->isVariablyModifiedType() ||
3568 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003569 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00003570
3571 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3572 CharUnits Offset = Base.getLValueOffset();
3573
3574 if (!Offset.isNegative() && Offset <= Size)
3575 Size -= Offset;
3576 else
3577 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003578 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00003579}
3580
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003581bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003582 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00003583 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003584 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003585
3586 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00003587 if (TryEvaluateBuiltinObjectSize(E))
3588 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00003589
Eric Christopherb2aaf512010-01-19 22:58:35 +00003590 // If evaluating the argument has side-effects we can't determine
3591 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00003592 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003593 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00003594 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003595 return Success(0, E);
3596 }
Mike Stumpc4c90452009-10-27 22:09:17 +00003597
Richard Smithf48fdb02011-12-09 22:58:01 +00003598 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003599 }
3600
Chris Lattner019f4e82008-10-06 05:28:25 +00003601 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003602 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00003603
Richard Smithe052d462011-12-09 02:04:48 +00003604 case Builtin::BI__builtin_constant_p: {
3605 const Expr *Arg = E->getArg(0);
3606 QualType ArgType = Arg->getType();
3607 // __builtin_constant_p always has one operand. The rules which gcc follows
3608 // are not precisely documented, but are as follows:
3609 //
3610 // - If the operand is of integral, floating, complex or enumeration type,
3611 // and can be folded to a known value of that type, it returns 1.
3612 // - If the operand and can be folded to a pointer to the first character
3613 // of a string literal (or such a pointer cast to an integral type), it
3614 // returns 1.
3615 //
3616 // Otherwise, it returns 0.
3617 //
3618 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3619 // its support for this does not currently work.
3620 int IsConstant = 0;
3621 if (ArgType->isIntegralOrEnumerationType()) {
3622 // Note, a pointer cast to an integral type is only a constant if it is
3623 // a pointer to the first character of a string literal.
3624 Expr::EvalResult Result;
3625 if (Arg->EvaluateAsRValue(Result, Info.Ctx) && !Result.HasSideEffects) {
3626 APValue &V = Result.Val;
3627 if (V.getKind() == APValue::LValue) {
3628 if (const Expr *E = V.getLValueBase().dyn_cast<const Expr*>())
3629 IsConstant = isa<StringLiteral>(E) && V.getLValueOffset().isZero();
3630 } else {
3631 IsConstant = 1;
3632 }
3633 }
3634 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3635 IsConstant = Arg->isEvaluatable(Info.Ctx);
3636 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3637 LValue LV;
3638 // Use a separate EvalInfo: ignore constexpr parameter and 'this' bindings
3639 // during the check.
3640 Expr::EvalStatus Status;
3641 EvalInfo SubInfo(Info.Ctx, Status);
3642 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, SubInfo)
3643 : EvaluatePointer(Arg, LV, SubInfo)) &&
3644 !Status.HasSideEffects)
3645 if (const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>())
3646 IsConstant = isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3647 }
3648
3649 return Success(IsConstant, E);
3650 }
Chris Lattner21fb98e2009-09-23 06:06:36 +00003651 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003652 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003653 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00003654 return Success(Operand, E);
3655 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00003656
3657 case Builtin::BI__builtin_expect:
3658 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00003659
3660 case Builtin::BIstrlen:
3661 case Builtin::BI__builtin_strlen:
3662 // As an extension, we support strlen() and __builtin_strlen() as constant
3663 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003664 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00003665 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3666 // The string literal may have embedded null characters. Find the first
3667 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003668 StringRef Str = S->getString();
3669 StringRef::size_type Pos = Str.find(0);
3670 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00003671 Str = Str.substr(0, Pos);
3672
3673 return Success(Str.size(), E);
3674 }
3675
Richard Smithf48fdb02011-12-09 22:58:01 +00003676 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003677
3678 case Builtin::BI__atomic_is_lock_free: {
3679 APSInt SizeVal;
3680 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3681 return false;
3682
3683 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3684 // of two less than the maximum inline atomic width, we know it is
3685 // lock-free. If the size isn't a power of two, or greater than the
3686 // maximum alignment where we promote atomics, we know it is not lock-free
3687 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3688 // the answer can only be determined at runtime; for example, 16-byte
3689 // atomics have lock-free implementations on some, but not all,
3690 // x86-64 processors.
3691
3692 // Check power-of-two.
3693 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3694 if (!Size.isPowerOfTwo())
3695#if 0
3696 // FIXME: Suppress this folding until the ABI for the promotion width
3697 // settles.
3698 return Success(0, E);
3699#else
Richard Smithf48fdb02011-12-09 22:58:01 +00003700 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003701#endif
3702
3703#if 0
3704 // Check against promotion width.
3705 // FIXME: Suppress this folding until the ABI for the promotion width
3706 // settles.
3707 unsigned PromoteWidthBits =
3708 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3709 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3710 return Success(0, E);
3711#endif
3712
3713 // Check against inlining width.
3714 unsigned InlineWidthBits =
3715 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3716 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3717 return Success(1, E);
3718
Richard Smithf48fdb02011-12-09 22:58:01 +00003719 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003720 }
Chris Lattner019f4e82008-10-06 05:28:25 +00003721 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00003722}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003723
Richard Smith625b8072011-10-31 01:37:14 +00003724static bool HasSameBase(const LValue &A, const LValue &B) {
3725 if (!A.getLValueBase())
3726 return !B.getLValueBase();
3727 if (!B.getLValueBase())
3728 return false;
3729
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003730 if (A.getLValueBase().getOpaqueValue() !=
3731 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00003732 const Decl *ADecl = GetLValueBaseDecl(A);
3733 if (!ADecl)
3734 return false;
3735 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00003736 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00003737 return false;
3738 }
3739
3740 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00003741 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00003742}
3743
Chris Lattnerb542afe2008-07-11 19:10:17 +00003744bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003745 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00003746 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003747
John McCall2de56d12010-08-25 11:45:40 +00003748 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00003749 VisitIgnoredValue(E->getLHS());
3750 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00003751 }
3752
3753 if (E->isLogicalOp()) {
3754 // These need to be handled specially because the operands aren't
3755 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003756 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00003757
Richard Smithc49bd112011-10-28 17:51:58 +00003758 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00003759 // We were able to evaluate the LHS, see if we can get away with not
3760 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00003761 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003762 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003763
Richard Smithc49bd112011-10-28 17:51:58 +00003764 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00003765 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003766 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003767 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00003768 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003769 }
3770 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00003771 // FIXME: If both evaluations fail, we should produce the diagnostic from
3772 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3773 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00003774 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003775 // We can't evaluate the LHS; however, sometimes the result
3776 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00003777 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003778 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003779 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00003780 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003781
3782 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003783 }
3784 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00003785 }
Eli Friedmana6afa762008-11-13 06:09:17 +00003786
Eli Friedmana6afa762008-11-13 06:09:17 +00003787 return false;
3788 }
3789
Anders Carlsson286f85e2008-11-16 07:17:21 +00003790 QualType LHSTy = E->getLHS()->getType();
3791 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00003792
3793 if (LHSTy->isAnyComplexType()) {
3794 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00003795 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00003796
3797 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3798 return false;
3799
3800 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3801 return false;
3802
3803 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003804 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00003805 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00003806 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00003807 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3808
John McCall2de56d12010-08-25 11:45:40 +00003809 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003810 return Success((CR_r == APFloat::cmpEqual &&
3811 CR_i == APFloat::cmpEqual), E);
3812 else {
John McCall2de56d12010-08-25 11:45:40 +00003813 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00003814 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00003815 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00003816 CR_r == APFloat::cmpLessThan ||
3817 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003818 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00003819 CR_i == APFloat::cmpLessThan ||
3820 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00003821 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00003822 } else {
John McCall2de56d12010-08-25 11:45:40 +00003823 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003824 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3825 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3826 else {
John McCall2de56d12010-08-25 11:45:40 +00003827 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00003828 "Invalid compex comparison.");
3829 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3830 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3831 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00003832 }
3833 }
Mike Stump1eb44332009-09-09 15:08:12 +00003834
Anders Carlsson286f85e2008-11-16 07:17:21 +00003835 if (LHSTy->isRealFloatingType() &&
3836 RHSTy->isRealFloatingType()) {
3837 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00003838
Anders Carlsson286f85e2008-11-16 07:17:21 +00003839 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3840 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003841
Anders Carlsson286f85e2008-11-16 07:17:21 +00003842 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3843 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003844
Anders Carlsson286f85e2008-11-16 07:17:21 +00003845 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00003846
Anders Carlsson286f85e2008-11-16 07:17:21 +00003847 switch (E->getOpcode()) {
3848 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003849 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00003850 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003851 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00003852 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003853 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00003854 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003855 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00003856 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00003857 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00003858 E);
John McCall2de56d12010-08-25 11:45:40 +00003859 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003860 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00003861 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00003862 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00003863 || CR == APFloat::cmpLessThan
3864 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00003865 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00003866 }
Mike Stump1eb44332009-09-09 15:08:12 +00003867
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003868 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00003869 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00003870 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00003871 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3872 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003873
John McCallefdb83e2010-05-07 21:00:08 +00003874 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00003875 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3876 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003877
Richard Smith625b8072011-10-31 01:37:14 +00003878 // Reject differing bases from the normal codepath; we special-case
3879 // comparisons to null.
3880 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith9e36b532011-10-31 05:11:32 +00003881 // Inequalities and subtractions between unrelated pointers have
3882 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00003883 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00003884 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00003885 // A constant address may compare equal to the address of a symbol.
3886 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00003887 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00003888 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3889 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003890 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00003891 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00003892 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00003893 // distinct. However, we do know that the address of a literal will be
3894 // non-null.
3895 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
3896 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00003897 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00003898 // We can't tell whether weak symbols will end up pointing to the same
3899 // object.
3900 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00003901 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00003902 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00003903 // (Note that clang defaults to -fmerge-all-constants, which can
3904 // lead to inconsistent results for comparisons involving the address
3905 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00003906 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00003907 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00003908
Richard Smithcc5d4f62011-11-07 09:22:26 +00003909 // FIXME: Implement the C++11 restrictions:
3910 // - Pointer subtractions must be on elements of the same array.
3911 // - Pointer comparisons must be between members with the same access.
3912
John McCall2de56d12010-08-25 11:45:40 +00003913 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00003914 QualType Type = E->getLHS()->getType();
3915 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00003916
Richard Smith180f4792011-11-10 06:34:14 +00003917 CharUnits ElementSize;
3918 if (!HandleSizeof(Info, ElementType, ElementSize))
3919 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003920
Richard Smith180f4792011-11-10 06:34:14 +00003921 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00003922 RHSValue.getLValueOffset();
3923 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003924 }
Richard Smith625b8072011-10-31 01:37:14 +00003925
3926 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
3927 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
3928 switch (E->getOpcode()) {
3929 default: llvm_unreachable("missing comparison operator");
3930 case BO_LT: return Success(LHSOffset < RHSOffset, E);
3931 case BO_GT: return Success(LHSOffset > RHSOffset, E);
3932 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
3933 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
3934 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
3935 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003936 }
Anders Carlsson3068d112008-11-16 19:01:22 +00003937 }
3938 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003939 if (!LHSTy->isIntegralOrEnumerationType() ||
3940 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003941 // We can't continue from here for non-integral types.
3942 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003943 }
3944
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003945 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00003946 CCValue LHSVal;
Richard Smithc49bd112011-10-28 17:51:58 +00003947 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003948 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00003949
Richard Smithc49bd112011-10-28 17:51:58 +00003950 if (!Visit(E->getRHS()))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003951 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00003952 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003953
3954 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00003955 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00003956 CharUnits AdditionalOffset = CharUnits::fromQuantity(
3957 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00003958 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00003959 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003960 else
Richard Smith47a1eed2011-10-29 20:57:55 +00003961 LHSVal.getLValueOffset() -= AdditionalOffset;
3962 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003963 return true;
3964 }
3965
3966 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00003967 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00003968 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003969 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
3970 LHSVal.getInt().getZExtValue());
3971 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00003972 return true;
3973 }
3974
3975 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00003976 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00003977 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003978
Richard Smithc49bd112011-10-28 17:51:58 +00003979 APSInt &LHS = LHSVal.getInt();
3980 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00003981
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003982 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00003983 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00003984 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003985 case BO_Mul: return Success(LHS * RHS, E);
3986 case BO_Add: return Success(LHS + RHS, E);
3987 case BO_Sub: return Success(LHS - RHS, E);
3988 case BO_And: return Success(LHS & RHS, E);
3989 case BO_Xor: return Success(LHS ^ RHS, E);
3990 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003991 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00003992 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00003993 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00003994 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003995 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00003996 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00003997 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00003998 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003999 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00004000 // During constant-folding, a negative shift is an opposite shift.
4001 if (RHS.isSigned() && RHS.isNegative()) {
4002 RHS = -RHS;
4003 goto shift_right;
4004 }
4005
4006 shift_left:
4007 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00004008 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4009 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004010 }
John McCall2de56d12010-08-25 11:45:40 +00004011 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00004012 // During constant-folding, a negative shift is an opposite shift.
4013 if (RHS.isSigned() && RHS.isNegative()) {
4014 RHS = -RHS;
4015 goto shift_left;
4016 }
4017
4018 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00004019 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00004020 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4021 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004022 }
Mike Stump1eb44332009-09-09 15:08:12 +00004023
Richard Smithc49bd112011-10-28 17:51:58 +00004024 case BO_LT: return Success(LHS < RHS, E);
4025 case BO_GT: return Success(LHS > RHS, E);
4026 case BO_LE: return Success(LHS <= RHS, E);
4027 case BO_GE: return Success(LHS >= RHS, E);
4028 case BO_EQ: return Success(LHS == RHS, E);
4029 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004030 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004031}
4032
Ken Dyck8b752f12010-01-27 17:10:57 +00004033CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004034 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4035 // the result is the size of the referenced type."
4036 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4037 // result shall be the alignment of the referenced type."
4038 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4039 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004040
4041 // __alignof is defined to return the preferred alignment.
4042 return Info.Ctx.toCharUnitsFromBits(
4043 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004044}
4045
Ken Dyck8b752f12010-01-27 17:10:57 +00004046CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004047 E = E->IgnoreParens();
4048
4049 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004050 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004051 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004052 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4053 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004054
Chris Lattneraf707ab2009-01-24 21:53:27 +00004055 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004056 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4057 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004058
Chris Lattnere9feb472009-01-24 21:09:06 +00004059 return GetAlignOfType(E->getType());
4060}
4061
4062
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004063/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4064/// a result as the expression's type.
4065bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4066 const UnaryExprOrTypeTraitExpr *E) {
4067 switch(E->getKind()) {
4068 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004069 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004070 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004071 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004072 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004073 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004074
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004075 case UETT_VecStep: {
4076 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004077
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004078 if (Ty->isVectorType()) {
4079 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004080
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004081 // The vec_step built-in functions that take a 3-component
4082 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4083 if (n == 3)
4084 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004085
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004086 return Success(n, E);
4087 } else
4088 return Success(1, E);
4089 }
4090
4091 case UETT_SizeOf: {
4092 QualType SrcTy = E->getTypeOfArgument();
4093 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4094 // the result is the size of the referenced type."
4095 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4096 // result shall be the alignment of the referenced type."
4097 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4098 SrcTy = Ref->getPointeeType();
4099
Richard Smith180f4792011-11-10 06:34:14 +00004100 CharUnits Sizeof;
4101 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004102 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004103 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004104 }
4105 }
4106
4107 llvm_unreachable("unknown expr/type trait");
Richard Smithf48fdb02011-12-09 22:58:01 +00004108 return Error(E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00004109}
4110
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004111bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004112 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004113 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004114 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004115 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004116 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004117 for (unsigned i = 0; i != n; ++i) {
4118 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4119 switch (ON.getKind()) {
4120 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004121 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004122 APSInt IdxResult;
4123 if (!EvaluateInteger(Idx, IdxResult, Info))
4124 return false;
4125 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4126 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004127 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004128 CurrentType = AT->getElementType();
4129 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4130 Result += IdxResult.getSExtValue() * ElementSize;
4131 break;
4132 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004133
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004134 case OffsetOfExpr::OffsetOfNode::Field: {
4135 FieldDecl *MemberDecl = ON.getField();
4136 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004137 if (!RT)
4138 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004139 RecordDecl *RD = RT->getDecl();
4140 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004141 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004142 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004143 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004144 CurrentType = MemberDecl->getType().getNonReferenceType();
4145 break;
4146 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004147
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004148 case OffsetOfExpr::OffsetOfNode::Identifier:
4149 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004150 return Error(OOE);
4151
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004152 case OffsetOfExpr::OffsetOfNode::Base: {
4153 CXXBaseSpecifier *BaseSpec = ON.getBase();
4154 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004155 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004156
4157 // Find the layout of the class whose base we are looking into.
4158 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004159 if (!RT)
4160 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004161 RecordDecl *RD = RT->getDecl();
4162 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4163
4164 // Find the base class itself.
4165 CurrentType = BaseSpec->getType();
4166 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4167 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004168 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004169
4170 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004171 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004172 break;
4173 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004174 }
4175 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004176 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004177}
4178
Chris Lattnerb542afe2008-07-11 19:10:17 +00004179bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004180 switch (E->getOpcode()) {
4181 default:
4182 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4183 // See C99 6.6p3.
4184 return Error(E);
4185 case UO_Extension:
4186 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4187 // If so, we could clear the diagnostic ID.
4188 return Visit(E->getSubExpr());
4189 case UO_Plus:
4190 // The result is just the value.
4191 return Visit(E->getSubExpr());
4192 case UO_Minus: {
4193 if (!Visit(E->getSubExpr()))
4194 return false;
4195 if (!Result.isInt()) return Error(E);
4196 return Success(-Result.getInt(), E);
4197 }
4198 case UO_Not: {
4199 if (!Visit(E->getSubExpr()))
4200 return false;
4201 if (!Result.isInt()) return Error(E);
4202 return Success(~Result.getInt(), E);
4203 }
4204 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004205 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004206 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004207 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004208 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004209 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004210 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004211}
Mike Stump1eb44332009-09-09 15:08:12 +00004212
Chris Lattner732b2232008-07-12 01:15:53 +00004213/// HandleCast - This is used to evaluate implicit or explicit casts where the
4214/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004215bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4216 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004217 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004218 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004219
Eli Friedman46a52322011-03-25 00:43:55 +00004220 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004221 case CK_BaseToDerived:
4222 case CK_DerivedToBase:
4223 case CK_UncheckedDerivedToBase:
4224 case CK_Dynamic:
4225 case CK_ToUnion:
4226 case CK_ArrayToPointerDecay:
4227 case CK_FunctionToPointerDecay:
4228 case CK_NullToPointer:
4229 case CK_NullToMemberPointer:
4230 case CK_BaseToDerivedMemberPointer:
4231 case CK_DerivedToBaseMemberPointer:
4232 case CK_ConstructorConversion:
4233 case CK_IntegralToPointer:
4234 case CK_ToVoid:
4235 case CK_VectorSplat:
4236 case CK_IntegralToFloating:
4237 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004238 case CK_CPointerToObjCPointerCast:
4239 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004240 case CK_AnyPointerToBlockPointerCast:
4241 case CK_ObjCObjectLValueCast:
4242 case CK_FloatingRealToComplex:
4243 case CK_FloatingComplexToReal:
4244 case CK_FloatingComplexCast:
4245 case CK_FloatingComplexToIntegralComplex:
4246 case CK_IntegralRealToComplex:
4247 case CK_IntegralComplexCast:
4248 case CK_IntegralComplexToFloatingComplex:
4249 llvm_unreachable("invalid cast kind for integral value");
4250
Eli Friedmane50c2972011-03-25 19:07:11 +00004251 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004252 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004253 case CK_LValueBitCast:
4254 case CK_UserDefinedConversion:
John McCall33e56f32011-09-10 06:18:15 +00004255 case CK_ARCProduceObject:
4256 case CK_ARCConsumeObject:
4257 case CK_ARCReclaimReturnedObject:
4258 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004259 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004260
4261 case CK_LValueToRValue:
4262 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004263 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004264
4265 case CK_MemberPointerToBoolean:
4266 case CK_PointerToBoolean:
4267 case CK_IntegralToBoolean:
4268 case CK_FloatingToBoolean:
4269 case CK_FloatingComplexToBoolean:
4270 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004271 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004272 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004273 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004274 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004275 }
4276
Eli Friedman46a52322011-03-25 00:43:55 +00004277 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004278 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004279 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004280
Eli Friedmanbe265702009-02-20 01:15:07 +00004281 if (!Result.isInt()) {
4282 // Only allow casts of lvalues if they are lossless.
4283 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4284 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004285
Daniel Dunbardd211642009-02-19 22:24:01 +00004286 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004287 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00004288 }
Mike Stump1eb44332009-09-09 15:08:12 +00004289
Eli Friedman46a52322011-03-25 00:43:55 +00004290 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00004291 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4292
John McCallefdb83e2010-05-07 21:00:08 +00004293 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00004294 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004295 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00004296
Daniel Dunbardd211642009-02-19 22:24:01 +00004297 if (LV.getLValueBase()) {
4298 // Only allow based lvalue casts if they are lossless.
4299 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00004300 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004301
Richard Smithb755a9d2011-11-16 07:18:12 +00004302 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004303 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00004304 return true;
4305 }
4306
Ken Dycka7305832010-01-15 12:37:54 +00004307 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4308 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00004309 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00004310 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004311
Eli Friedman46a52322011-03-25 00:43:55 +00004312 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00004313 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00004314 if (!EvaluateComplex(SubExpr, C, Info))
4315 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00004316 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00004317 }
Eli Friedman2217c872009-02-22 11:46:18 +00004318
Eli Friedman46a52322011-03-25 00:43:55 +00004319 case CK_FloatingToIntegral: {
4320 APFloat F(0.0);
4321 if (!EvaluateFloat(SubExpr, F, Info))
4322 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00004323
Richard Smithc1c5f272011-12-13 06:39:58 +00004324 APSInt Value;
4325 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4326 return false;
4327 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00004328 }
4329 }
Mike Stump1eb44332009-09-09 15:08:12 +00004330
Eli Friedman46a52322011-03-25 00:43:55 +00004331 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf48fdb02011-12-09 22:58:01 +00004332 return Error(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004333}
Anders Carlsson2bad1682008-07-08 14:30:00 +00004334
Eli Friedman722c7172009-02-28 03:59:05 +00004335bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4336 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004337 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004338 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4339 return false;
4340 if (!LV.isComplexInt())
4341 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004342 return Success(LV.getComplexIntReal(), E);
4343 }
4344
4345 return Visit(E->getSubExpr());
4346}
4347
Eli Friedman664a1042009-02-27 04:45:43 +00004348bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004349 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004350 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004351 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4352 return false;
4353 if (!LV.isComplexInt())
4354 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004355 return Success(LV.getComplexIntImag(), E);
4356 }
4357
Richard Smith8327fad2011-10-24 18:44:57 +00004358 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004359 return Success(0, E);
4360}
4361
Douglas Gregoree8aff02011-01-04 17:33:58 +00004362bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4363 return Success(E->getPackLength(), E);
4364}
4365
Sebastian Redl295995c2010-09-10 20:55:47 +00004366bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4367 return Success(E->getValue(), E);
4368}
4369
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004370//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004371// Float Evaluation
4372//===----------------------------------------------------------------------===//
4373
4374namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004375class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004376 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004377 APFloat &Result;
4378public:
4379 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004380 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004381
Richard Smith47a1eed2011-10-29 20:57:55 +00004382 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004383 Result = V.getFloat();
4384 return true;
4385 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004386
Richard Smithf10d9172011-10-11 21:43:33 +00004387 bool ValueInitialization(const Expr *E) {
4388 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4389 return true;
4390 }
4391
Chris Lattner019f4e82008-10-06 05:28:25 +00004392 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004393
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004394 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004395 bool VisitBinaryOperator(const BinaryOperator *E);
4396 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004397 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004398
John McCallabd3a852010-05-07 22:08:54 +00004399 bool VisitUnaryReal(const UnaryOperator *E);
4400 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004401
John McCallabd3a852010-05-07 22:08:54 +00004402 // FIXME: Missing: array subscript of vector, member of vector,
4403 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004404};
4405} // end anonymous namespace
4406
4407static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004408 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004409 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004410}
4411
Jay Foad4ba2a172011-01-12 09:06:06 +00004412static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004413 QualType ResultTy,
4414 const Expr *Arg,
4415 bool SNaN,
4416 llvm::APFloat &Result) {
4417 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4418 if (!S) return false;
4419
4420 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4421
4422 llvm::APInt fill;
4423
4424 // Treat empty strings as if they were zero.
4425 if (S->getString().empty())
4426 fill = llvm::APInt(32, 0);
4427 else if (S->getString().getAsInteger(0, fill))
4428 return false;
4429
4430 if (SNaN)
4431 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4432 else
4433 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4434 return true;
4435}
4436
Chris Lattner019f4e82008-10-06 05:28:25 +00004437bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004438 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004439 default:
4440 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4441
Chris Lattner019f4e82008-10-06 05:28:25 +00004442 case Builtin::BI__builtin_huge_val:
4443 case Builtin::BI__builtin_huge_valf:
4444 case Builtin::BI__builtin_huge_vall:
4445 case Builtin::BI__builtin_inf:
4446 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004447 case Builtin::BI__builtin_infl: {
4448 const llvm::fltSemantics &Sem =
4449 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00004450 Result = llvm::APFloat::getInf(Sem);
4451 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004452 }
Mike Stump1eb44332009-09-09 15:08:12 +00004453
John McCalldb7b72a2010-02-28 13:00:19 +00004454 case Builtin::BI__builtin_nans:
4455 case Builtin::BI__builtin_nansf:
4456 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00004457 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4458 true, Result))
4459 return Error(E);
4460 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00004461
Chris Lattner9e621712008-10-06 06:31:58 +00004462 case Builtin::BI__builtin_nan:
4463 case Builtin::BI__builtin_nanf:
4464 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00004465 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00004466 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00004467 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4468 false, Result))
4469 return Error(E);
4470 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004471
4472 case Builtin::BI__builtin_fabs:
4473 case Builtin::BI__builtin_fabsf:
4474 case Builtin::BI__builtin_fabsl:
4475 if (!EvaluateFloat(E->getArg(0), Result, Info))
4476 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004477
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004478 if (Result.isNegative())
4479 Result.changeSign();
4480 return true;
4481
Mike Stump1eb44332009-09-09 15:08:12 +00004482 case Builtin::BI__builtin_copysign:
4483 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004484 case Builtin::BI__builtin_copysignl: {
4485 APFloat RHS(0.);
4486 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4487 !EvaluateFloat(E->getArg(1), RHS, Info))
4488 return false;
4489 Result.copySign(RHS);
4490 return true;
4491 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004492 }
4493}
4494
John McCallabd3a852010-05-07 22:08:54 +00004495bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004496 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4497 ComplexValue CV;
4498 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4499 return false;
4500 Result = CV.FloatReal;
4501 return true;
4502 }
4503
4504 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00004505}
4506
4507bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004508 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4509 ComplexValue CV;
4510 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4511 return false;
4512 Result = CV.FloatImag;
4513 return true;
4514 }
4515
Richard Smith8327fad2011-10-24 18:44:57 +00004516 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00004517 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4518 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00004519 return true;
4520}
4521
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004522bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004523 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004524 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004525 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004526 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00004527 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004528 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4529 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004530 Result.changeSign();
4531 return true;
4532 }
4533}
Chris Lattner019f4e82008-10-06 05:28:25 +00004534
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004535bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004536 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4537 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00004538
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004539 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004540 if (!EvaluateFloat(E->getLHS(), Result, Info))
4541 return false;
4542 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4543 return false;
4544
4545 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004546 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004547 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004548 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4549 return true;
John McCall2de56d12010-08-25 11:45:40 +00004550 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004551 Result.add(RHS, APFloat::rmNearestTiesToEven);
4552 return true;
John McCall2de56d12010-08-25 11:45:40 +00004553 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004554 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4555 return true;
John McCall2de56d12010-08-25 11:45:40 +00004556 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004557 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4558 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004559 }
4560}
4561
4562bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4563 Result = E->getValue();
4564 return true;
4565}
4566
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004567bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4568 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00004569
Eli Friedman2a523ee2011-03-25 00:54:52 +00004570 switch (E->getCastKind()) {
4571 default:
Richard Smithc49bd112011-10-28 17:51:58 +00004572 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00004573
4574 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004575 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00004576 return EvaluateInteger(SubExpr, IntResult, Info) &&
4577 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4578 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004579 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004580
4581 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004582 if (!Visit(SubExpr))
4583 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00004584 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4585 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004586 }
John McCallf3ea8cf2010-11-14 08:17:51 +00004587
Eli Friedman2a523ee2011-03-25 00:54:52 +00004588 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00004589 ComplexValue V;
4590 if (!EvaluateComplex(SubExpr, V, Info))
4591 return false;
4592 Result = V.getComplexFloatReal();
4593 return true;
4594 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004595 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004596
Richard Smithf48fdb02011-12-09 22:58:01 +00004597 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004598}
4599
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004600//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004601// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004602//===----------------------------------------------------------------------===//
4603
4604namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004605class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004606 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00004607 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004608
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004609public:
John McCallf4cf1a12010-05-07 17:22:02 +00004610 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004611 : ExprEvaluatorBaseTy(info), Result(Result) {}
4612
Richard Smith47a1eed2011-10-29 20:57:55 +00004613 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004614 Result.setFrom(V);
4615 return true;
4616 }
Mike Stump1eb44332009-09-09 15:08:12 +00004617
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004618 //===--------------------------------------------------------------------===//
4619 // Visitor Methods
4620 //===--------------------------------------------------------------------===//
4621
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004622 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00004623
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004624 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00004625
John McCallf4cf1a12010-05-07 17:22:02 +00004626 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004627 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004628 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004629};
4630} // end anonymous namespace
4631
John McCallf4cf1a12010-05-07 17:22:02 +00004632static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4633 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004634 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004635 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004636}
4637
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004638bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4639 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004640
4641 if (SubExpr->getType()->isRealFloatingType()) {
4642 Result.makeComplexFloat();
4643 APFloat &Imag = Result.FloatImag;
4644 if (!EvaluateFloat(SubExpr, Imag, Info))
4645 return false;
4646
4647 Result.FloatReal = APFloat(Imag.getSemantics());
4648 return true;
4649 } else {
4650 assert(SubExpr->getType()->isIntegerType() &&
4651 "Unexpected imaginary literal.");
4652
4653 Result.makeComplexInt();
4654 APSInt &Imag = Result.IntImag;
4655 if (!EvaluateInteger(SubExpr, Imag, Info))
4656 return false;
4657
4658 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4659 return true;
4660 }
4661}
4662
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004663bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004664
John McCall8786da72010-12-14 17:51:41 +00004665 switch (E->getCastKind()) {
4666 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00004667 case CK_BaseToDerived:
4668 case CK_DerivedToBase:
4669 case CK_UncheckedDerivedToBase:
4670 case CK_Dynamic:
4671 case CK_ToUnion:
4672 case CK_ArrayToPointerDecay:
4673 case CK_FunctionToPointerDecay:
4674 case CK_NullToPointer:
4675 case CK_NullToMemberPointer:
4676 case CK_BaseToDerivedMemberPointer:
4677 case CK_DerivedToBaseMemberPointer:
4678 case CK_MemberPointerToBoolean:
4679 case CK_ConstructorConversion:
4680 case CK_IntegralToPointer:
4681 case CK_PointerToIntegral:
4682 case CK_PointerToBoolean:
4683 case CK_ToVoid:
4684 case CK_VectorSplat:
4685 case CK_IntegralCast:
4686 case CK_IntegralToBoolean:
4687 case CK_IntegralToFloating:
4688 case CK_FloatingToIntegral:
4689 case CK_FloatingToBoolean:
4690 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004691 case CK_CPointerToObjCPointerCast:
4692 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00004693 case CK_AnyPointerToBlockPointerCast:
4694 case CK_ObjCObjectLValueCast:
4695 case CK_FloatingComplexToReal:
4696 case CK_FloatingComplexToBoolean:
4697 case CK_IntegralComplexToReal:
4698 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00004699 case CK_ARCProduceObject:
4700 case CK_ARCConsumeObject:
4701 case CK_ARCReclaimReturnedObject:
4702 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00004703 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00004704
John McCall8786da72010-12-14 17:51:41 +00004705 case CK_LValueToRValue:
4706 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004707 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00004708
4709 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004710 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00004711 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00004712 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00004713
4714 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004715 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00004716 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004717 return false;
4718
John McCall8786da72010-12-14 17:51:41 +00004719 Result.makeComplexFloat();
4720 Result.FloatImag = APFloat(Real.getSemantics());
4721 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004722 }
4723
John McCall8786da72010-12-14 17:51:41 +00004724 case CK_FloatingComplexCast: {
4725 if (!Visit(E->getSubExpr()))
4726 return false;
4727
4728 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4729 QualType From
4730 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4731
Richard Smithc1c5f272011-12-13 06:39:58 +00004732 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4733 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00004734 }
4735
4736 case CK_FloatingComplexToIntegralComplex: {
4737 if (!Visit(E->getSubExpr()))
4738 return false;
4739
4740 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4741 QualType From
4742 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4743 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00004744 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4745 To, Result.IntReal) &&
4746 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4747 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00004748 }
4749
4750 case CK_IntegralRealToComplex: {
4751 APSInt &Real = Result.IntReal;
4752 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4753 return false;
4754
4755 Result.makeComplexInt();
4756 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4757 return true;
4758 }
4759
4760 case CK_IntegralComplexCast: {
4761 if (!Visit(E->getSubExpr()))
4762 return false;
4763
4764 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4765 QualType From
4766 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4767
4768 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4769 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4770 return true;
4771 }
4772
4773 case CK_IntegralComplexToFloatingComplex: {
4774 if (!Visit(E->getSubExpr()))
4775 return false;
4776
4777 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4778 QualType From
4779 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4780 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00004781 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4782 To, Result.FloatReal) &&
4783 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4784 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00004785 }
4786 }
4787
4788 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf48fdb02011-12-09 22:58:01 +00004789 return Error(E);
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004790}
4791
John McCallf4cf1a12010-05-07 17:22:02 +00004792bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004793 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00004794 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4795
John McCallf4cf1a12010-05-07 17:22:02 +00004796 if (!Visit(E->getLHS()))
4797 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004798
John McCallf4cf1a12010-05-07 17:22:02 +00004799 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004800 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00004801 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004802
Daniel Dunbar3f279872009-01-29 01:32:56 +00004803 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4804 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004805 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004806 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004807 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004808 if (Result.isComplexFloat()) {
4809 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4810 APFloat::rmNearestTiesToEven);
4811 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4812 APFloat::rmNearestTiesToEven);
4813 } else {
4814 Result.getComplexIntReal() += RHS.getComplexIntReal();
4815 Result.getComplexIntImag() += RHS.getComplexIntImag();
4816 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00004817 break;
John McCall2de56d12010-08-25 11:45:40 +00004818 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004819 if (Result.isComplexFloat()) {
4820 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4821 APFloat::rmNearestTiesToEven);
4822 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4823 APFloat::rmNearestTiesToEven);
4824 } else {
4825 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4826 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4827 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00004828 break;
John McCall2de56d12010-08-25 11:45:40 +00004829 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00004830 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004831 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00004832 APFloat &LHS_r = LHS.getComplexFloatReal();
4833 APFloat &LHS_i = LHS.getComplexFloatImag();
4834 APFloat &RHS_r = RHS.getComplexFloatReal();
4835 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00004836
Daniel Dunbar3f279872009-01-29 01:32:56 +00004837 APFloat Tmp = LHS_r;
4838 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4839 Result.getComplexFloatReal() = Tmp;
4840 Tmp = LHS_i;
4841 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4842 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4843
4844 Tmp = LHS_r;
4845 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4846 Result.getComplexFloatImag() = Tmp;
4847 Tmp = LHS_i;
4848 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4849 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4850 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00004851 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004852 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00004853 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4854 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00004855 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00004856 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4857 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4858 }
4859 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004860 case BO_Div:
4861 if (Result.isComplexFloat()) {
4862 ComplexValue LHS = Result;
4863 APFloat &LHS_r = LHS.getComplexFloatReal();
4864 APFloat &LHS_i = LHS.getComplexFloatImag();
4865 APFloat &RHS_r = RHS.getComplexFloatReal();
4866 APFloat &RHS_i = RHS.getComplexFloatImag();
4867 APFloat &Res_r = Result.getComplexFloatReal();
4868 APFloat &Res_i = Result.getComplexFloatImag();
4869
4870 APFloat Den = RHS_r;
4871 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4872 APFloat Tmp = RHS_i;
4873 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4874 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4875
4876 Res_r = LHS_r;
4877 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4878 Tmp = LHS_i;
4879 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4880 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4881 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4882
4883 Res_i = LHS_i;
4884 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4885 Tmp = LHS_r;
4886 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4887 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4888 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4889 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004890 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
4891 return Error(E, diag::note_expr_divide_by_zero);
4892
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004893 ComplexValue LHS = Result;
4894 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4895 RHS.getComplexIntImag() * RHS.getComplexIntImag();
4896 Result.getComplexIntReal() =
4897 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
4898 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
4899 Result.getComplexIntImag() =
4900 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
4901 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
4902 }
4903 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004904 }
4905
John McCallf4cf1a12010-05-07 17:22:02 +00004906 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004907}
4908
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004909bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4910 // Get the operand value into 'Result'.
4911 if (!Visit(E->getSubExpr()))
4912 return false;
4913
4914 switch (E->getOpcode()) {
4915 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004916 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004917 case UO_Extension:
4918 return true;
4919 case UO_Plus:
4920 // The result is always just the subexpr.
4921 return true;
4922 case UO_Minus:
4923 if (Result.isComplexFloat()) {
4924 Result.getComplexFloatReal().changeSign();
4925 Result.getComplexFloatImag().changeSign();
4926 }
4927 else {
4928 Result.getComplexIntReal() = -Result.getComplexIntReal();
4929 Result.getComplexIntImag() = -Result.getComplexIntImag();
4930 }
4931 return true;
4932 case UO_Not:
4933 if (Result.isComplexFloat())
4934 Result.getComplexFloatImag().changeSign();
4935 else
4936 Result.getComplexIntImag() = -Result.getComplexIntImag();
4937 return true;
4938 }
4939}
4940
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004941//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00004942// Void expression evaluation, primarily for a cast to void on the LHS of a
4943// comma operator
4944//===----------------------------------------------------------------------===//
4945
4946namespace {
4947class VoidExprEvaluator
4948 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
4949public:
4950 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
4951
4952 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00004953
4954 bool VisitCastExpr(const CastExpr *E) {
4955 switch (E->getCastKind()) {
4956 default:
4957 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4958 case CK_ToVoid:
4959 VisitIgnoredValue(E->getSubExpr());
4960 return true;
4961 }
4962 }
4963};
4964} // end anonymous namespace
4965
4966static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
4967 assert(E->isRValue() && E->getType()->isVoidType());
4968 return VoidExprEvaluator(Info).Visit(E);
4969}
4970
4971//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00004972// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004973//===----------------------------------------------------------------------===//
4974
Richard Smith47a1eed2011-10-29 20:57:55 +00004975static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004976 // In C, function designators are not lvalues, but we evaluate them as if they
4977 // are.
4978 if (E->isGLValue() || E->getType()->isFunctionType()) {
4979 LValue LV;
4980 if (!EvaluateLValue(E, LV, Info))
4981 return false;
4982 LV.moveInto(Result);
4983 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00004984 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00004985 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00004986 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00004987 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004988 return false;
John McCallefdb83e2010-05-07 21:00:08 +00004989 } else if (E->getType()->hasPointerRepresentation()) {
4990 LValue LV;
4991 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004992 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00004993 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00004994 } else if (E->getType()->isRealFloatingType()) {
4995 llvm::APFloat F(0.0);
4996 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004997 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00004998 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00004999 } else if (E->getType()->isAnyComplexType()) {
5000 ComplexValue C;
5001 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005002 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005003 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005004 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005005 MemberPtr P;
5006 if (!EvaluateMemberPointer(E, P, Info))
5007 return false;
5008 P.moveInto(Result);
5009 return true;
Richard Smith69c2c502011-11-04 05:33:44 +00005010 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005011 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005012 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005013 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005014 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005015 Result = Info.CurrentCall->Temporaries[E];
Richard Smith69c2c502011-11-04 05:33:44 +00005016 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005017 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005018 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005019 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5020 return false;
5021 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005022 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005023 if (Info.getLangOpts().CPlusPlus0x)
5024 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5025 << E->getType();
5026 else
5027 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005028 if (!EvaluateVoid(E, Info))
5029 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005030 } else if (Info.getLangOpts().CPlusPlus0x) {
5031 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5032 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005033 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005034 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005035 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005036 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005037
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005038 return true;
5039}
5040
Richard Smith69c2c502011-11-04 05:33:44 +00005041/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5042/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5043/// since later initializers for an object can indirectly refer to subobjects
5044/// which were initialized earlier.
5045static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005046 const LValue &This, const Expr *E,
5047 CheckConstantExpressionKind CCEK) {
Richard Smith69c2c502011-11-04 05:33:44 +00005048 if (E->isRValue() && E->getType()->isLiteralType()) {
5049 // Evaluate arrays and record types in-place, so that later initializers can
5050 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005051 if (E->getType()->isArrayType())
5052 return EvaluateArray(E, This, Result, Info);
5053 else if (E->getType()->isRecordType())
5054 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005055 }
5056
5057 // For any other type, in-place evaluation is unimportant.
5058 CCValue CoreConstResult;
5059 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005060 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005061}
5062
Richard Smithf48fdb02011-12-09 22:58:01 +00005063/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5064/// lvalue-to-rvalue cast if it is an lvalue.
5065static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
5066 CCValue Value;
5067 if (!::Evaluate(Value, Info, E))
5068 return false;
5069
5070 if (E->isGLValue()) {
5071 LValue LV;
5072 LV.setFrom(Value);
5073 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5074 return false;
5075 }
5076
5077 // Check this core constant expression is a constant expression, and if so,
5078 // convert it to one.
5079 return CheckConstantExpression(Info, E, Value, Result);
5080}
Richard Smithc49bd112011-10-28 17:51:58 +00005081
Richard Smith51f47082011-10-29 00:50:52 +00005082/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005083/// any crazy technique (that has nothing to do with language standards) that
5084/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005085/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5086/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005087bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005088 // Fast-path evaluations of integer literals, since we sometimes see files
5089 // containing vast quantities of these.
5090 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5091 Result.Val = APValue(APSInt(L->getValue(),
5092 L->getType()->isUnsignedIntegerType()));
5093 return true;
5094 }
5095
Richard Smith1445bba2011-11-10 03:30:42 +00005096 // FIXME: Evaluating initializers for large arrays can cause performance
5097 // problems, and we don't use such values yet. Once we have a more efficient
5098 // array representation, this should be reinstated, and used by CodeGen.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005099 // The same problem affects large records.
5100 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5101 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005102 return false;
5103
Richard Smith180f4792011-11-10 06:34:14 +00005104 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf48fdb02011-12-09 22:58:01 +00005105 EvalInfo Info(Ctx, Result);
5106 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005107}
5108
Jay Foad4ba2a172011-01-12 09:06:06 +00005109bool Expr::EvaluateAsBooleanCondition(bool &Result,
5110 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005111 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005112 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith177dce72011-11-01 16:57:24 +00005113 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005114 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005115}
5116
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005117bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005118 EvalResult ExprResult;
Richard Smith51f47082011-10-29 00:50:52 +00005119 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithf48fdb02011-12-09 22:58:01 +00005120 !ExprResult.Val.isInt())
Richard Smithc49bd112011-10-28 17:51:58 +00005121 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005122
Richard Smithc49bd112011-10-28 17:51:58 +00005123 Result = ExprResult.Val.getInt();
5124 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005125}
5126
Jay Foad4ba2a172011-01-12 09:06:06 +00005127bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005128 EvalInfo Info(Ctx, Result);
5129
John McCallefdb83e2010-05-07 21:00:08 +00005130 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005131 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005132 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5133 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005134}
5135
Richard Smith099e7f62011-12-19 06:19:21 +00005136bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5137 const VarDecl *VD,
5138 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
5139 Expr::EvalStatus EStatus;
5140 EStatus.Diag = &Notes;
5141
5142 EvalInfo InitInfo(Ctx, EStatus);
5143 InitInfo.setEvaluatingDecl(VD, Value);
5144
5145 LValue LVal;
5146 LVal.set(VD);
5147
5148 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5149 !EStatus.HasSideEffects;
5150}
5151
Richard Smith51f47082011-10-29 00:50:52 +00005152/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5153/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005154bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005155 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005156 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005157}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005158
Jay Foad4ba2a172011-01-12 09:06:06 +00005159bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005160 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005161}
5162
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005163APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005164 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005165 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005166 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005167 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005168 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005169
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005170 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005171}
John McCalld905f5a2010-05-07 05:32:02 +00005172
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005173 bool Expr::EvalResult::isGlobalLValue() const {
5174 assert(Val.isLValue());
5175 return IsGlobalLValue(Val.getLValueBase());
5176 }
5177
5178
John McCalld905f5a2010-05-07 05:32:02 +00005179/// isIntegerConstantExpr - this recursive routine will test if an expression is
5180/// an integer constant expression.
5181
5182/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5183/// comma, etc
5184///
5185/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5186/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5187/// cast+dereference.
5188
5189// CheckICE - This function does the fundamental ICE checking: the returned
5190// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5191// Note that to reduce code duplication, this helper does no evaluation
5192// itself; the caller checks whether the expression is evaluatable, and
5193// in the rare cases where CheckICE actually cares about the evaluated
5194// value, it calls into Evalute.
5195//
5196// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005197// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005198// 1: This expression is not an ICE, but if it isn't evaluated, it's
5199// a legal subexpression for an ICE. This return value is used to handle
5200// the comma operator in C99 mode.
5201// 2: This expression is not an ICE, and is not a legal subexpression for one.
5202
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005203namespace {
5204
John McCalld905f5a2010-05-07 05:32:02 +00005205struct ICEDiag {
5206 unsigned Val;
5207 SourceLocation Loc;
5208
5209 public:
5210 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5211 ICEDiag() : Val(0) {}
5212};
5213
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005214}
5215
5216static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00005217
5218static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5219 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005220 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005221 !EVResult.Val.isInt()) {
5222 return ICEDiag(2, E->getLocStart());
5223 }
5224 return NoDiag();
5225}
5226
5227static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5228 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005229 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00005230 return ICEDiag(2, E->getLocStart());
5231 }
5232
5233 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00005234#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00005235#define STMT(Node, Base) case Expr::Node##Class:
5236#define EXPR(Node, Base)
5237#include "clang/AST/StmtNodes.inc"
5238 case Expr::PredefinedExprClass:
5239 case Expr::FloatingLiteralClass:
5240 case Expr::ImaginaryLiteralClass:
5241 case Expr::StringLiteralClass:
5242 case Expr::ArraySubscriptExprClass:
5243 case Expr::MemberExprClass:
5244 case Expr::CompoundAssignOperatorClass:
5245 case Expr::CompoundLiteralExprClass:
5246 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005247 case Expr::DesignatedInitExprClass:
5248 case Expr::ImplicitValueInitExprClass:
5249 case Expr::ParenListExprClass:
5250 case Expr::VAArgExprClass:
5251 case Expr::AddrLabelExprClass:
5252 case Expr::StmtExprClass:
5253 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00005254 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005255 case Expr::CXXDynamicCastExprClass:
5256 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00005257 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005258 case Expr::CXXNullPtrLiteralExprClass:
5259 case Expr::CXXThisExprClass:
5260 case Expr::CXXThrowExprClass:
5261 case Expr::CXXNewExprClass:
5262 case Expr::CXXDeleteExprClass:
5263 case Expr::CXXPseudoDestructorExprClass:
5264 case Expr::UnresolvedLookupExprClass:
5265 case Expr::DependentScopeDeclRefExprClass:
5266 case Expr::CXXConstructExprClass:
5267 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00005268 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00005269 case Expr::CXXTemporaryObjectExprClass:
5270 case Expr::CXXUnresolvedConstructExprClass:
5271 case Expr::CXXDependentScopeMemberExprClass:
5272 case Expr::UnresolvedMemberExprClass:
5273 case Expr::ObjCStringLiteralClass:
5274 case Expr::ObjCEncodeExprClass:
5275 case Expr::ObjCMessageExprClass:
5276 case Expr::ObjCSelectorExprClass:
5277 case Expr::ObjCProtocolExprClass:
5278 case Expr::ObjCIvarRefExprClass:
5279 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005280 case Expr::ObjCIsaExprClass:
5281 case Expr::ShuffleVectorExprClass:
5282 case Expr::BlockExprClass:
5283 case Expr::BlockDeclRefExprClass:
5284 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00005285 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00005286 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00005287 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005288 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005289 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00005290 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00005291 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00005292 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005293 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005294 return ICEDiag(2, E->getLocStart());
5295
Douglas Gregoree8aff02011-01-04 17:33:58 +00005296 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005297 case Expr::GNUNullExprClass:
5298 // GCC considers the GNU __null value to be an integral constant expression.
5299 return NoDiag();
5300
John McCall91a57552011-07-15 05:09:51 +00005301 case Expr::SubstNonTypeTemplateParmExprClass:
5302 return
5303 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5304
John McCalld905f5a2010-05-07 05:32:02 +00005305 case Expr::ParenExprClass:
5306 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00005307 case Expr::GenericSelectionExprClass:
5308 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005309 case Expr::IntegerLiteralClass:
5310 case Expr::CharacterLiteralClass:
5311 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00005312 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005313 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00005314 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00005315 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00005316 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00005317 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005318 return NoDiag();
5319 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00005320 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00005321 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5322 // constant expressions, but they can never be ICEs because an ICE cannot
5323 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00005324 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00005325 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00005326 return CheckEvalInICE(E, Ctx);
5327 return ICEDiag(2, E->getLocStart());
5328 }
5329 case Expr::DeclRefExprClass:
5330 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5331 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00005332 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00005333 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5334
5335 // Parameter variables are never constants. Without this check,
5336 // getAnyInitializer() can find a default argument, which leads
5337 // to chaos.
5338 if (isa<ParmVarDecl>(D))
5339 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5340
5341 // C++ 7.1.5.1p2
5342 // A variable of non-volatile const-qualified integral or enumeration
5343 // type initialized by an ICE can be used in ICEs.
5344 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00005345 if (!Dcl->getType()->isIntegralOrEnumerationType())
5346 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5347
Richard Smith099e7f62011-12-19 06:19:21 +00005348 const VarDecl *VD;
5349 // Look for a declaration of this variable that has an initializer, and
5350 // check whether it is an ICE.
5351 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5352 return NoDiag();
5353 else
5354 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00005355 }
5356 }
5357 return ICEDiag(2, E->getLocStart());
5358 case Expr::UnaryOperatorClass: {
5359 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5360 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005361 case UO_PostInc:
5362 case UO_PostDec:
5363 case UO_PreInc:
5364 case UO_PreDec:
5365 case UO_AddrOf:
5366 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00005367 // C99 6.6/3 allows increment and decrement within unevaluated
5368 // subexpressions of constant expressions, but they can never be ICEs
5369 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005370 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00005371 case UO_Extension:
5372 case UO_LNot:
5373 case UO_Plus:
5374 case UO_Minus:
5375 case UO_Not:
5376 case UO_Real:
5377 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00005378 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005379 }
5380
5381 // OffsetOf falls through here.
5382 }
5383 case Expr::OffsetOfExprClass: {
5384 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00005385 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00005386 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00005387 // compliance: we should warn earlier for offsetof expressions with
5388 // array subscripts that aren't ICEs, and if the array subscripts
5389 // are ICEs, the value of the offsetof must be an integer constant.
5390 return CheckEvalInICE(E, Ctx);
5391 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005392 case Expr::UnaryExprOrTypeTraitExprClass: {
5393 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5394 if ((Exp->getKind() == UETT_SizeOf) &&
5395 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00005396 return ICEDiag(2, E->getLocStart());
5397 return NoDiag();
5398 }
5399 case Expr::BinaryOperatorClass: {
5400 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5401 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005402 case BO_PtrMemD:
5403 case BO_PtrMemI:
5404 case BO_Assign:
5405 case BO_MulAssign:
5406 case BO_DivAssign:
5407 case BO_RemAssign:
5408 case BO_AddAssign:
5409 case BO_SubAssign:
5410 case BO_ShlAssign:
5411 case BO_ShrAssign:
5412 case BO_AndAssign:
5413 case BO_XorAssign:
5414 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00005415 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5416 // constant expressions, but they can never be ICEs because an ICE cannot
5417 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005418 return ICEDiag(2, E->getLocStart());
5419
John McCall2de56d12010-08-25 11:45:40 +00005420 case BO_Mul:
5421 case BO_Div:
5422 case BO_Rem:
5423 case BO_Add:
5424 case BO_Sub:
5425 case BO_Shl:
5426 case BO_Shr:
5427 case BO_LT:
5428 case BO_GT:
5429 case BO_LE:
5430 case BO_GE:
5431 case BO_EQ:
5432 case BO_NE:
5433 case BO_And:
5434 case BO_Xor:
5435 case BO_Or:
5436 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00005437 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5438 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00005439 if (Exp->getOpcode() == BO_Div ||
5440 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00005441 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00005442 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00005443 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005444 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005445 if (REval == 0)
5446 return ICEDiag(1, E->getLocStart());
5447 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005448 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005449 if (LEval.isMinSignedValue())
5450 return ICEDiag(1, E->getLocStart());
5451 }
5452 }
5453 }
John McCall2de56d12010-08-25 11:45:40 +00005454 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00005455 if (Ctx.getLangOptions().C99) {
5456 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5457 // if it isn't evaluated.
5458 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5459 return ICEDiag(1, E->getLocStart());
5460 } else {
5461 // In both C89 and C++, commas in ICEs are illegal.
5462 return ICEDiag(2, E->getLocStart());
5463 }
5464 }
5465 if (LHSResult.Val >= RHSResult.Val)
5466 return LHSResult;
5467 return RHSResult;
5468 }
John McCall2de56d12010-08-25 11:45:40 +00005469 case BO_LAnd:
5470 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00005471 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5472 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5473 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5474 // Rare case where the RHS has a comma "side-effect"; we need
5475 // to actually check the condition to see whether the side
5476 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00005477 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005478 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00005479 return RHSResult;
5480 return NoDiag();
5481 }
5482
5483 if (LHSResult.Val >= RHSResult.Val)
5484 return LHSResult;
5485 return RHSResult;
5486 }
5487 }
5488 }
5489 case Expr::ImplicitCastExprClass:
5490 case Expr::CStyleCastExprClass:
5491 case Expr::CXXFunctionalCastExprClass:
5492 case Expr::CXXStaticCastExprClass:
5493 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00005494 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005495 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00005496 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00005497 if (isa<ExplicitCastExpr>(E)) {
5498 if (const FloatingLiteral *FL
5499 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5500 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5501 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5502 APSInt IgnoredVal(DestWidth, !DestSigned);
5503 bool Ignored;
5504 // If the value does not fit in the destination type, the behavior is
5505 // undefined, so we are not required to treat it as a constant
5506 // expression.
5507 if (FL->getValue().convertToInteger(IgnoredVal,
5508 llvm::APFloat::rmTowardZero,
5509 &Ignored) & APFloat::opInvalidOp)
5510 return ICEDiag(2, E->getLocStart());
5511 return NoDiag();
5512 }
5513 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00005514 switch (cast<CastExpr>(E)->getCastKind()) {
5515 case CK_LValueToRValue:
5516 case CK_NoOp:
5517 case CK_IntegralToBoolean:
5518 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00005519 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00005520 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00005521 return ICEDiag(2, E->getLocStart());
5522 }
John McCalld905f5a2010-05-07 05:32:02 +00005523 }
John McCall56ca35d2011-02-17 10:25:35 +00005524 case Expr::BinaryConditionalOperatorClass: {
5525 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5526 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5527 if (CommonResult.Val == 2) return CommonResult;
5528 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5529 if (FalseResult.Val == 2) return FalseResult;
5530 if (CommonResult.Val == 1) return CommonResult;
5531 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005532 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00005533 return FalseResult;
5534 }
John McCalld905f5a2010-05-07 05:32:02 +00005535 case Expr::ConditionalOperatorClass: {
5536 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5537 // If the condition (ignoring parens) is a __builtin_constant_p call,
5538 // then only the true side is actually considered in an integer constant
5539 // expression, and it is fully evaluated. This is an important GNU
5540 // extension. See GCC PR38377 for discussion.
5541 if (const CallExpr *CallCE
5542 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith180f4792011-11-10 06:34:14 +00005543 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCalld905f5a2010-05-07 05:32:02 +00005544 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005545 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005546 !EVResult.Val.isInt()) {
5547 return ICEDiag(2, E->getLocStart());
5548 }
5549 return NoDiag();
5550 }
5551 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005552 if (CondResult.Val == 2)
5553 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00005554
Richard Smithf48fdb02011-12-09 22:58:01 +00005555 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5556 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00005557
John McCalld905f5a2010-05-07 05:32:02 +00005558 if (TrueResult.Val == 2)
5559 return TrueResult;
5560 if (FalseResult.Val == 2)
5561 return FalseResult;
5562 if (CondResult.Val == 1)
5563 return CondResult;
5564 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5565 return NoDiag();
5566 // Rare case where the diagnostics depend on which side is evaluated
5567 // Note that if we get here, CondResult is 0, and at least one of
5568 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005569 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00005570 return FalseResult;
5571 }
5572 return TrueResult;
5573 }
5574 case Expr::CXXDefaultArgExprClass:
5575 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5576 case Expr::ChooseExprClass: {
5577 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5578 }
5579 }
5580
5581 // Silence a GCC warning
5582 return ICEDiag(2, E->getLocStart());
5583}
5584
Richard Smithf48fdb02011-12-09 22:58:01 +00005585/// Evaluate an expression as a C++11 integral constant expression.
5586static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5587 const Expr *E,
5588 llvm::APSInt *Value,
5589 SourceLocation *Loc) {
5590 if (!E->getType()->isIntegralOrEnumerationType()) {
5591 if (Loc) *Loc = E->getExprLoc();
5592 return false;
5593 }
5594
5595 Expr::EvalResult Result;
Richard Smithdd1f29b2011-12-12 09:28:41 +00005596 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5597 Result.Diag = &Diags;
5598 EvalInfo Info(Ctx, Result);
5599
5600 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5601 if (!Diags.empty()) {
5602 IsICE = false;
5603 if (Loc) *Loc = Diags[0].first;
5604 } else if (!IsICE && Loc) {
5605 *Loc = E->getExprLoc();
Richard Smithf48fdb02011-12-09 22:58:01 +00005606 }
Richard Smithdd1f29b2011-12-12 09:28:41 +00005607
5608 if (!IsICE)
5609 return false;
5610
5611 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5612 if (Value) *Value = Result.Val.getInt();
5613 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00005614}
5615
Richard Smithdd1f29b2011-12-12 09:28:41 +00005616bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00005617 if (Ctx.getLangOptions().CPlusPlus0x)
5618 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5619
John McCalld905f5a2010-05-07 05:32:02 +00005620 ICEDiag d = CheckICE(this, Ctx);
5621 if (d.Val != 0) {
5622 if (Loc) *Loc = d.Loc;
5623 return false;
5624 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005625 return true;
5626}
5627
5628bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5629 SourceLocation *Loc, bool isEvaluated) const {
5630 if (Ctx.getLangOptions().CPlusPlus0x)
5631 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5632
5633 if (!isIntegerConstantExpr(Ctx, Loc))
5634 return false;
5635 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00005636 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00005637 return true;
5638}