blob: d507ed34193ed2ec1d0cd97da7f7c5ca1d697f61 [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//
Richard Smith745f5142012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlssonc44eec62008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000038#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000039#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000040#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000041#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000042#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Argyrios Kyrtzidisb2c60b02012-03-01 19:45:56 +000047#include "llvm/Support/SaveAndRestore.h"
Mike Stump4572bab2009-05-30 03:56:50 +000048#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000049#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000050
Anders Carlssonc44eec62008-07-03 04:20:39 +000051using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000054
Richard Smith83587db2012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCallf4cf1a12010-05-07 17:22:02 +000057namespace {
Richard Smith180f4792011-11-10 06:34:14 +000058 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000061
Richard Smith83587db2012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
66 return B.get<const Expr*>()->getType();
67 }
68
Richard Smith180f4792011-11-10 06:34:14 +000069 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000070 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000071 static
Richard Smithf15fda02012-02-02 01:16:57 +000072 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000073 APValue::BaseOrMemberType Value;
74 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000075 return Value;
76 }
77
78 /// Get an LValue path entry, which is known to not be an array index, as a
79 /// field declaration.
Richard Smith83587db2012-02-15 02:18:13 +000080 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000081 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000082 }
83 /// Get an LValue path entry, which is known to not be an array index, as a
84 /// base class declaration.
Richard Smith83587db2012-02-15 02:18:13 +000085 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000086 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000087 }
88 /// Determine whether this LValue path entry for a base class names a virtual
89 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +000090 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000091 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +000092 }
93
Richard Smithb4e85ed2012-01-06 16:39:00 +000094 /// Find the path length and type of the most-derived subobject in the given
95 /// path, and find the size of the containing array, if any.
96 static
97 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
98 ArrayRef<APValue::LValuePathEntry> Path,
99 uint64_t &ArraySize, QualType &Type) {
100 unsigned MostDerivedLength = 0;
101 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000102 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000103 if (Type->isArrayType()) {
104 const ConstantArrayType *CAT =
105 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
106 Type = CAT->getElementType();
107 ArraySize = CAT->getSize().getZExtValue();
108 MostDerivedLength = I + 1;
Richard Smith86024012012-02-18 22:04:06 +0000109 } else if (Type->isAnyComplexType()) {
110 const ComplexType *CT = Type->castAs<ComplexType>();
111 Type = CT->getElementType();
112 ArraySize = 2;
113 MostDerivedLength = I + 1;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000114 } else if (const FieldDecl *FD = getAsField(Path[I])) {
115 Type = FD->getType();
116 ArraySize = 0;
117 MostDerivedLength = I + 1;
118 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000119 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000120 ArraySize = 0;
121 }
Richard Smith9a17a682011-11-07 05:07:52 +0000122 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000123 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000124 }
125
Richard Smithb4e85ed2012-01-06 16:39:00 +0000126 // The order of this enum is important for diagnostics.
127 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000128 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith86024012012-02-18 22:04:06 +0000129 CSK_This, CSK_Real, CSK_Imag
Richard Smithb4e85ed2012-01-06 16:39:00 +0000130 };
131
Richard Smith0a3bdb62011-11-04 02:25:55 +0000132 /// A path from a glvalue to a subobject of that glvalue.
133 struct SubobjectDesignator {
134 /// True if the subobject was named in a manner not supported by C++11. Such
135 /// lvalues can still be folded, but they are not core constant expressions
136 /// and we cannot perform lvalue-to-rvalue conversions on them.
137 bool Invalid : 1;
138
Richard Smithb4e85ed2012-01-06 16:39:00 +0000139 /// Is this a pointer one past the end of an object?
140 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000141
Richard Smithb4e85ed2012-01-06 16:39:00 +0000142 /// The length of the path to the most-derived object of which this is a
143 /// subobject.
144 unsigned MostDerivedPathLength : 30;
145
146 /// The size of the array of which the most-derived object is an element, or
147 /// 0 if the most-derived object is not an array element.
148 uint64_t MostDerivedArraySize;
149
150 /// The type of the most derived object referred to by this address.
151 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000152
Richard Smith9a17a682011-11-07 05:07:52 +0000153 typedef APValue::LValuePathEntry PathEntry;
154
Richard Smith0a3bdb62011-11-04 02:25:55 +0000155 /// The entries on the path from the glvalue to the designated subobject.
156 SmallVector<PathEntry, 8> Entries;
157
Richard Smithb4e85ed2012-01-06 16:39:00 +0000158 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000159
Richard Smithb4e85ed2012-01-06 16:39:00 +0000160 explicit SubobjectDesignator(QualType T)
161 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
162 MostDerivedArraySize(0), MostDerivedType(T) {}
163
164 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
165 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
166 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000167 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000168 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000169 ArrayRef<PathEntry> VEntries = V.getLValuePath();
170 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
171 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000172 MostDerivedPathLength =
173 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
174 V.getLValuePath(), MostDerivedArraySize,
175 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000176 }
177 }
178
Richard Smith0a3bdb62011-11-04 02:25:55 +0000179 void setInvalid() {
180 Invalid = true;
181 Entries.clear();
182 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000183
184 /// Determine whether this is a one-past-the-end pointer.
185 bool isOnePastTheEnd() const {
186 if (IsOnePastTheEnd)
187 return true;
188 if (MostDerivedArraySize &&
189 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
190 return true;
191 return false;
192 }
193
194 /// Check that this refers to a valid subobject.
195 bool isValidSubobject() const {
196 if (Invalid)
197 return false;
198 return !isOnePastTheEnd();
199 }
200 /// Check that this refers to a valid subobject, and if not, produce a
201 /// relevant diagnostic and set the designator as invalid.
202 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
203
204 /// Update this designator to refer to the first element within this array.
205 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000206 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000207 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000208 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000209
210 // This is a most-derived object.
211 MostDerivedType = CAT->getElementType();
212 MostDerivedArraySize = CAT->getSize().getZExtValue();
213 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000214 }
215 /// Update this designator to refer to the given base or member of this
216 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000217 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000218 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000219 APValue::BaseOrMemberType Value(D, Virtual);
220 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000221 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000222
223 // If this isn't a base class, it's a new most-derived object.
224 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
225 MostDerivedType = FD->getType();
226 MostDerivedArraySize = 0;
227 MostDerivedPathLength = Entries.size();
228 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000229 }
Richard Smith86024012012-02-18 22:04:06 +0000230 /// Update this designator to refer to the given complex component.
231 void addComplexUnchecked(QualType EltTy, bool Imag) {
232 PathEntry Entry;
233 Entry.ArrayIndex = Imag;
234 Entries.push_back(Entry);
235
236 // This is technically a most-derived object, though in practice this
237 // is unlikely to matter.
238 MostDerivedType = EltTy;
239 MostDerivedArraySize = 2;
240 MostDerivedPathLength = Entries.size();
241 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000242 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000243 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000244 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000245 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000246 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000247 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000248 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
249 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
250 setInvalid();
251 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000252 return;
253 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000254 // [expr.add]p4: For the purposes of these operators, a pointer to a
255 // nonarray object behaves the same as a pointer to the first element of
256 // an array of length one with the type of the object as its element type.
257 if (IsOnePastTheEnd && N == (uint64_t)-1)
258 IsOnePastTheEnd = false;
259 else if (!IsOnePastTheEnd && N == 1)
260 IsOnePastTheEnd = true;
261 else if (N != 0) {
262 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000263 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000264 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000265 }
266 };
267
Richard Smithd0dccea2011-10-28 22:34:42 +0000268 /// A stack frame in the constexpr call stack.
269 struct CallStackFrame {
270 EvalInfo &Info;
271
272 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000273 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000274
Richard Smith08d6e032011-12-16 19:06:07 +0000275 /// CallLoc - The location of the call expression for this call.
276 SourceLocation CallLoc;
277
278 /// Callee - The function which was called.
279 const FunctionDecl *Callee;
280
Richard Smith83587db2012-02-15 02:18:13 +0000281 /// Index - The call index of this call.
282 unsigned Index;
283
Richard Smith180f4792011-11-10 06:34:14 +0000284 /// This - The binding for the this pointer in this call, if any.
285 const LValue *This;
286
Richard Smithd0dccea2011-10-28 22:34:42 +0000287 /// ParmBindings - Parameter bindings for this function call, indexed by
288 /// parameters' function scope indices.
Richard Smith1aa0be82012-03-03 22:46:17 +0000289 const APValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000290
Richard Smith1aa0be82012-03-03 22:46:17 +0000291 typedef llvm::DenseMap<const Expr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000292 typedef MapTy::const_iterator temp_iterator;
293 /// Temporaries - Temporary lvalues materialized within this stack frame.
294 MapTy Temporaries;
295
Richard Smith08d6e032011-12-16 19:06:07 +0000296 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
297 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000298 const APValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000299 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000300 };
301
Richard Smithdd1f29b2011-12-12 09:28:41 +0000302 /// A partial diagnostic which we might know in advance that we are not going
303 /// to emit.
304 class OptionalDiagnostic {
305 PartialDiagnostic *Diag;
306
307 public:
308 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
309
310 template<typename T>
311 OptionalDiagnostic &operator<<(const T &v) {
312 if (Diag)
313 *Diag << v;
314 return *this;
315 }
Richard Smith789f9b62012-01-31 04:08:20 +0000316
317 OptionalDiagnostic &operator<<(const APSInt &I) {
318 if (Diag) {
319 llvm::SmallVector<char, 32> Buffer;
320 I.toString(Buffer);
321 *Diag << StringRef(Buffer.data(), Buffer.size());
322 }
323 return *this;
324 }
325
326 OptionalDiagnostic &operator<<(const APFloat &F) {
327 if (Diag) {
328 llvm::SmallVector<char, 32> Buffer;
329 F.toString(Buffer);
330 *Diag << StringRef(Buffer.data(), Buffer.size());
331 }
332 return *this;
333 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000334 };
335
Richard Smith83587db2012-02-15 02:18:13 +0000336 /// EvalInfo - This is a private struct used by the evaluator to capture
337 /// information about a subexpression as it is folded. It retains information
338 /// about the AST context, but also maintains information about the folded
339 /// expression.
340 ///
341 /// If an expression could be evaluated, it is still possible it is not a C
342 /// "integer constant expression" or constant expression. If not, this struct
343 /// captures information about how and why not.
344 ///
345 /// One bit of information passed *into* the request for constant folding
346 /// indicates whether the subexpression is "evaluated" or not according to C
347 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
348 /// evaluate the expression regardless of what the RHS is, but C only allows
349 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000350 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000351 ASTContext &Ctx;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000352
Richard Smithbd552ef2011-10-31 05:52:43 +0000353 /// EvalStatus - Contains information about the evaluation.
354 Expr::EvalStatus &EvalStatus;
355
356 /// CurrentCall - The top of the constexpr call stack.
357 CallStackFrame *CurrentCall;
358
Richard Smithbd552ef2011-10-31 05:52:43 +0000359 /// CallStackDepth - The number of calls in the call stack right now.
360 unsigned CallStackDepth;
361
Richard Smith83587db2012-02-15 02:18:13 +0000362 /// NextCallIndex - The next call index to assign.
363 unsigned NextCallIndex;
364
Richard Smith1aa0be82012-03-03 22:46:17 +0000365 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000366 /// OpaqueValues - Values used as the common expression in a
367 /// BinaryConditionalOperator.
368 MapTy OpaqueValues;
369
370 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000371 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000372 CallStackFrame BottomFrame;
373
Richard Smith180f4792011-11-10 06:34:14 +0000374 /// EvaluatingDecl - This is the declaration whose initializer is being
375 /// evaluated, if any.
376 const VarDecl *EvaluatingDecl;
377
378 /// EvaluatingDeclValue - This is the value being constructed for the
379 /// declaration whose initializer is being evaluated, if any.
380 APValue *EvaluatingDeclValue;
381
Richard Smithc1c5f272011-12-13 06:39:58 +0000382 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
383 /// notes attached to it will also be stored, otherwise they will not be.
384 bool HasActiveDiagnostic;
385
Richard Smith745f5142012-01-27 01:14:48 +0000386 /// CheckingPotentialConstantExpression - Are we checking whether the
387 /// expression is a potential constant expression? If so, some diagnostics
388 /// are suppressed.
389 bool CheckingPotentialConstantExpression;
390
Argyrios Kyrtzidisc1b66e62012-02-27 23:18:37 +0000391 /// \brief Stack depth of IntExprEvaluator.
392 /// We check this against a maximum value to avoid stack overflow, see
393 /// test case in test/Sema/many-logical-ops.c.
394 // FIXME: This is a hack; handle properly unlimited logical ops.
395 unsigned IntExprEvaluatorDepth;
Richard Smithbd552ef2011-10-31 05:52:43 +0000396
397 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000398 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000399 CallStackDepth(0), NextCallIndex(1),
400 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000401 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Argyrios Kyrtzidisc1b66e62012-02-27 23:18:37 +0000402 CheckingPotentialConstantExpression(false), IntExprEvaluatorDepth(0) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000403
Richard Smith1aa0be82012-03-03 22:46:17 +0000404 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
Richard Smithbd552ef2011-10-31 05:52:43 +0000405 MapTy::const_iterator i = OpaqueValues.find(e);
406 if (i == OpaqueValues.end()) return 0;
407 return &i->second;
408 }
409
Richard Smith180f4792011-11-10 06:34:14 +0000410 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
411 EvaluatingDecl = VD;
412 EvaluatingDeclValue = &Value;
413 }
414
David Blaikie4e4d0842012-03-11 07:00:24 +0000415 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000416
Richard Smithc1c5f272011-12-13 06:39:58 +0000417 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000418 // Don't perform any constexpr calls (other than the call we're checking)
419 // when checking a potential constant expression.
420 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
421 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000422 if (NextCallIndex == 0) {
423 // NextCallIndex has wrapped around.
424 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
425 return false;
426 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000427 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
428 return true;
429 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
430 << getLangOpts().ConstexprCallDepth;
431 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000432 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000433
Richard Smith83587db2012-02-15 02:18:13 +0000434 CallStackFrame *getCallFrame(unsigned CallIndex) {
435 assert(CallIndex && "no call index in getCallFrame");
436 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
437 // be null in this loop.
438 CallStackFrame *Frame = CurrentCall;
439 while (Frame->Index > CallIndex)
440 Frame = Frame->Caller;
441 return (Frame->Index == CallIndex) ? Frame : 0;
442 }
443
Richard Smithc1c5f272011-12-13 06:39:58 +0000444 private:
445 /// Add a diagnostic to the diagnostics list.
446 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
447 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
448 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
449 return EvalStatus.Diag->back().second;
450 }
451
Richard Smith08d6e032011-12-16 19:06:07 +0000452 /// Add notes containing a call stack to the current point of evaluation.
453 void addCallStack(unsigned Limit);
454
Richard Smithc1c5f272011-12-13 06:39:58 +0000455 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000456 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000457 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
458 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000459 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000460 // If we have a prior diagnostic, it will be noting that the expression
461 // isn't a constant expression. This diagnostic is more important.
462 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000463 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000464 unsigned CallStackNotes = CallStackDepth - 1;
465 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
466 if (Limit)
467 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000468 if (CheckingPotentialConstantExpression)
469 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000470
Richard Smithc1c5f272011-12-13 06:39:58 +0000471 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000472 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000473 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
474 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000475 if (!CheckingPotentialConstantExpression)
476 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000477 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000478 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000479 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000480 return OptionalDiagnostic();
481 }
482
Richard Smithd75fb492012-03-15 00:41:48 +0000483 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
484 = diag::note_invalid_subexpr_in_const_expr,
485 unsigned ExtraNotes = 0) {
486 if (EvalStatus.Diag)
487 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
488 return OptionalDiagnostic();
489 }
490
Richard Smithdd1f29b2011-12-12 09:28:41 +0000491 /// Diagnose that the evaluation does not produce a C++11 core constant
492 /// expression.
Richard Smithd75fb492012-03-15 00:41:48 +0000493 template<typename LocArg>
494 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000495 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000496 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000497 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000498 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
499 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000500 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000501 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000502 return Diag(Loc, DiagId, ExtraNotes);
503 }
504
505 /// Add a note to a prior diagnostic.
506 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
507 if (!HasActiveDiagnostic)
508 return OptionalDiagnostic();
509 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000510 }
Richard Smith099e7f62011-12-19 06:19:21 +0000511
512 /// Add a stack of notes to a prior diagnostic.
513 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
514 if (HasActiveDiagnostic) {
515 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
516 Diags.begin(), Diags.end());
517 }
518 }
Richard Smith745f5142012-01-27 01:14:48 +0000519
520 /// Should we continue evaluation as much as possible after encountering a
521 /// construct which can't be folded?
522 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000523 return CheckingPotentialConstantExpression &&
524 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000525 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000526 };
Richard Smithf15fda02012-02-02 01:16:57 +0000527
528 /// Object used to treat all foldable expressions as constant expressions.
529 struct FoldConstant {
530 bool Enabled;
531
532 explicit FoldConstant(EvalInfo &Info)
533 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
534 !Info.EvalStatus.HasSideEffects) {
535 }
536 // Treat the value we've computed since this object was created as constant.
537 void Fold(EvalInfo &Info) {
538 if (Enabled && !Info.EvalStatus.Diag->empty() &&
539 !Info.EvalStatus.HasSideEffects)
540 Info.EvalStatus.Diag->clear();
541 }
542 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000543
544 /// RAII object used to suppress diagnostics and side-effects from a
545 /// speculative evaluation.
546 class SpeculativeEvaluationRAII {
547 EvalInfo &Info;
548 Expr::EvalStatus Old;
549
550 public:
551 SpeculativeEvaluationRAII(EvalInfo &Info,
552 llvm::SmallVectorImpl<PartialDiagnosticAt>
553 *NewDiag = 0)
554 : Info(Info), Old(Info.EvalStatus) {
555 Info.EvalStatus.Diag = NewDiag;
556 }
557 ~SpeculativeEvaluationRAII() {
558 Info.EvalStatus = Old;
559 }
560 };
Richard Smith08d6e032011-12-16 19:06:07 +0000561}
Richard Smithbd552ef2011-10-31 05:52:43 +0000562
Richard Smithb4e85ed2012-01-06 16:39:00 +0000563bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
564 CheckSubobjectKind CSK) {
565 if (Invalid)
566 return false;
567 if (isOnePastTheEnd()) {
Richard Smithd75fb492012-03-15 00:41:48 +0000568 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000569 << CSK;
570 setInvalid();
571 return false;
572 }
573 return true;
574}
575
576void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
577 const Expr *E, uint64_t N) {
578 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithd75fb492012-03-15 00:41:48 +0000579 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000580 << static_cast<int>(N) << /*array*/ 0
581 << static_cast<unsigned>(MostDerivedArraySize);
582 else
Richard Smithd75fb492012-03-15 00:41:48 +0000583 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000584 << static_cast<int>(N) << /*non-array*/ 1;
585 setInvalid();
586}
587
Richard Smith08d6e032011-12-16 19:06:07 +0000588CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
589 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000590 const APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000591 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000592 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000593 Info.CurrentCall = this;
594 ++Info.CallStackDepth;
595}
596
597CallStackFrame::~CallStackFrame() {
598 assert(Info.CurrentCall == this && "calls retired out of order");
599 --Info.CallStackDepth;
600 Info.CurrentCall = Caller;
601}
602
603/// Produce a string describing the given constexpr call.
604static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
605 unsigned ArgIndex = 0;
606 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000607 !isa<CXXConstructorDecl>(Frame->Callee) &&
608 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000609
610 if (!IsMemberCall)
611 Out << *Frame->Callee << '(';
612
613 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
614 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000615 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000616 Out << ", ";
617
618 const ParmVarDecl *Param = *I;
Richard Smith1aa0be82012-03-03 22:46:17 +0000619 const APValue &Arg = Frame->Arguments[ArgIndex];
620 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smith08d6e032011-12-16 19:06:07 +0000621
622 if (ArgIndex == 0 && IsMemberCall)
623 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000624 }
625
Richard Smith08d6e032011-12-16 19:06:07 +0000626 Out << ')';
627}
628
629void EvalInfo::addCallStack(unsigned Limit) {
630 // Determine which calls to skip, if any.
631 unsigned ActiveCalls = CallStackDepth - 1;
632 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
633 if (Limit && Limit < ActiveCalls) {
634 SkipStart = Limit / 2 + Limit % 2;
635 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000636 }
637
Richard Smith08d6e032011-12-16 19:06:07 +0000638 // Walk the call stack and add the diagnostics.
639 unsigned CallIdx = 0;
640 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
641 Frame = Frame->Caller, ++CallIdx) {
642 // Skip this call?
643 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
644 if (CallIdx == SkipStart) {
645 // Note that we're skipping calls.
646 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
647 << unsigned(ActiveCalls - Limit);
648 }
649 continue;
650 }
651
652 llvm::SmallVector<char, 128> Buffer;
653 llvm::raw_svector_ostream Out(Buffer);
654 describeCall(Frame, Out);
655 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
656 }
657}
658
659namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000660 struct ComplexValue {
661 private:
662 bool IsInt;
663
664 public:
665 APSInt IntReal, IntImag;
666 APFloat FloatReal, FloatImag;
667
668 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
669
670 void makeComplexFloat() { IsInt = false; }
671 bool isComplexFloat() const { return !IsInt; }
672 APFloat &getComplexFloatReal() { return FloatReal; }
673 APFloat &getComplexFloatImag() { return FloatImag; }
674
675 void makeComplexInt() { IsInt = true; }
676 bool isComplexInt() const { return IsInt; }
677 APSInt &getComplexIntReal() { return IntReal; }
678 APSInt &getComplexIntImag() { return IntImag; }
679
Richard Smith1aa0be82012-03-03 22:46:17 +0000680 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000681 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000682 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000683 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000684 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000685 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000686 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000687 assert(v.isComplexFloat() || v.isComplexInt());
688 if (v.isComplexFloat()) {
689 makeComplexFloat();
690 FloatReal = v.getComplexFloatReal();
691 FloatImag = v.getComplexFloatImag();
692 } else {
693 makeComplexInt();
694 IntReal = v.getComplexIntReal();
695 IntImag = v.getComplexIntImag();
696 }
697 }
John McCallf4cf1a12010-05-07 17:22:02 +0000698 };
John McCallefdb83e2010-05-07 21:00:08 +0000699
700 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000701 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000702 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000703 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000704 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000705
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000706 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000707 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000708 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000709 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000710 SubobjectDesignator &getLValueDesignator() { return Designator; }
711 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000712
Richard Smith1aa0be82012-03-03 22:46:17 +0000713 void moveInto(APValue &V) const {
714 if (Designator.Invalid)
715 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
716 else
717 V = APValue(Base, Offset, Designator.Entries,
718 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000719 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000720 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000721 assert(V.isLValue());
722 Base = V.getLValueBase();
723 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000724 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000725 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000726 }
727
Richard Smith83587db2012-02-15 02:18:13 +0000728 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000729 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000730 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000731 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000732 Designator = SubobjectDesignator(getType(B));
733 }
734
735 // Check that this LValue is not based on a null pointer. If it is, produce
736 // a diagnostic and mark the designator as invalid.
737 bool checkNullPointer(EvalInfo &Info, const Expr *E,
738 CheckSubobjectKind CSK) {
739 if (Designator.Invalid)
740 return false;
741 if (!Base) {
Richard Smithd75fb492012-03-15 00:41:48 +0000742 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000743 << CSK;
744 Designator.setInvalid();
745 return false;
746 }
747 return true;
748 }
749
750 // Check this LValue refers to an object. If not, set the designator to be
751 // invalid and emit a diagnostic.
752 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithd75fb492012-03-15 00:41:48 +0000753 // Outside C++11, do not build a designator referring to a subobject of
754 // any object: we won't use such a designator for anything.
755 if (!Info.getLangOpts().CPlusPlus0x)
756 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000757 return checkNullPointer(Info, E, CSK) &&
758 Designator.checkSubobject(Info, E, CSK);
759 }
760
761 void addDecl(EvalInfo &Info, const Expr *E,
762 const Decl *D, bool Virtual = false) {
Richard Smithd75fb492012-03-15 00:41:48 +0000763 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
764 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000765 }
766 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithd75fb492012-03-15 00:41:48 +0000767 if (checkSubobject(Info, E, CSK_ArrayToPointer))
768 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000769 }
Richard Smith86024012012-02-18 22:04:06 +0000770 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithd75fb492012-03-15 00:41:48 +0000771 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
772 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000773 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000774 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithd75fb492012-03-15 00:41:48 +0000775 if (checkNullPointer(Info, E, CSK_ArrayIndex))
776 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000777 }
John McCallefdb83e2010-05-07 21:00:08 +0000778 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000779
780 struct MemberPtr {
781 MemberPtr() {}
782 explicit MemberPtr(const ValueDecl *Decl) :
783 DeclAndIsDerivedMember(Decl, false), Path() {}
784
785 /// The member or (direct or indirect) field referred to by this member
786 /// pointer, or 0 if this is a null member pointer.
787 const ValueDecl *getDecl() const {
788 return DeclAndIsDerivedMember.getPointer();
789 }
790 /// Is this actually a member of some type derived from the relevant class?
791 bool isDerivedMember() const {
792 return DeclAndIsDerivedMember.getInt();
793 }
794 /// Get the class which the declaration actually lives in.
795 const CXXRecordDecl *getContainingRecord() const {
796 return cast<CXXRecordDecl>(
797 DeclAndIsDerivedMember.getPointer()->getDeclContext());
798 }
799
Richard Smith1aa0be82012-03-03 22:46:17 +0000800 void moveInto(APValue &V) const {
801 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000802 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000803 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000804 assert(V.isMemberPointer());
805 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
806 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
807 Path.clear();
808 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
809 Path.insert(Path.end(), P.begin(), P.end());
810 }
811
812 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
813 /// whether the member is a member of some class derived from the class type
814 /// of the member pointer.
815 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
816 /// Path - The path of base/derived classes from the member declaration's
817 /// class (exclusive) to the class type of the member pointer (inclusive).
818 SmallVector<const CXXRecordDecl*, 4> Path;
819
820 /// Perform a cast towards the class of the Decl (either up or down the
821 /// hierarchy).
822 bool castBack(const CXXRecordDecl *Class) {
823 assert(!Path.empty());
824 const CXXRecordDecl *Expected;
825 if (Path.size() >= 2)
826 Expected = Path[Path.size() - 2];
827 else
828 Expected = getContainingRecord();
829 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
830 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
831 // if B does not contain the original member and is not a base or
832 // derived class of the class containing the original member, the result
833 // of the cast is undefined.
834 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
835 // (D::*). We consider that to be a language defect.
836 return false;
837 }
838 Path.pop_back();
839 return true;
840 }
841 /// Perform a base-to-derived member pointer cast.
842 bool castToDerived(const CXXRecordDecl *Derived) {
843 if (!getDecl())
844 return true;
845 if (!isDerivedMember()) {
846 Path.push_back(Derived);
847 return true;
848 }
849 if (!castBack(Derived))
850 return false;
851 if (Path.empty())
852 DeclAndIsDerivedMember.setInt(false);
853 return true;
854 }
855 /// Perform a derived-to-base member pointer cast.
856 bool castToBase(const CXXRecordDecl *Base) {
857 if (!getDecl())
858 return true;
859 if (Path.empty())
860 DeclAndIsDerivedMember.setInt(true);
861 if (isDerivedMember()) {
862 Path.push_back(Base);
863 return true;
864 }
865 return castBack(Base);
866 }
867 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000868
Richard Smithb02e4622012-02-01 01:42:44 +0000869 /// Compare two member pointers, which are assumed to be of the same type.
870 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
871 if (!LHS.getDecl() || !RHS.getDecl())
872 return !LHS.getDecl() && !RHS.getDecl();
873 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
874 return false;
875 return LHS.Path == RHS.Path;
876 }
877
Richard Smithc1c5f272011-12-13 06:39:58 +0000878 /// Kinds of constant expression checking, for diagnostics.
879 enum CheckConstantExpressionKind {
880 CCEK_Constant, ///< A normal constant.
881 CCEK_ReturnValue, ///< A constexpr function return value.
882 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
883 };
John McCallf4cf1a12010-05-07 17:22:02 +0000884}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000885
Richard Smith1aa0be82012-03-03 22:46:17 +0000886static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000887static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
888 const LValue &This, const Expr *E,
889 CheckConstantExpressionKind CCEK = CCEK_Constant,
890 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000891static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
892static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000893static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
894 EvalInfo &Info);
895static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000896static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000897static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000898 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000899static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000900static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000901
902//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000903// Misc utilities
904//===----------------------------------------------------------------------===//
905
Richard Smith180f4792011-11-10 06:34:14 +0000906/// Should this call expression be treated as a string literal?
907static bool IsStringLiteralCall(const CallExpr *E) {
908 unsigned Builtin = E->isBuiltinCall();
909 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
910 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
911}
912
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000913static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000914 // C++11 [expr.const]p3 An address constant expression is a prvalue core
915 // constant expression of pointer type that evaluates to...
916
917 // ... a null pointer value, or a prvalue core constant expression of type
918 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000919 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000920
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000921 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
922 // ... the address of an object with static storage duration,
923 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
924 return VD->hasGlobalStorage();
925 // ... the address of a function,
926 return isa<FunctionDecl>(D);
927 }
928
929 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000930 switch (E->getStmtClass()) {
931 default:
932 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000933 case Expr::CompoundLiteralExprClass: {
934 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
935 return CLE->isFileScope() && CLE->isLValue();
936 }
Richard Smith180f4792011-11-10 06:34:14 +0000937 // A string literal has static storage duration.
938 case Expr::StringLiteralClass:
939 case Expr::PredefinedExprClass:
940 case Expr::ObjCStringLiteralClass:
941 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000942 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000943 return true;
944 case Expr::CallExprClass:
945 return IsStringLiteralCall(cast<CallExpr>(E));
946 // For GCC compatibility, &&label has static storage duration.
947 case Expr::AddrLabelExprClass:
948 return true;
949 // A Block literal expression may be used as the initialization value for
950 // Block variables at global or local static scope.
951 case Expr::BlockExprClass:
952 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000953 case Expr::ImplicitValueInitExprClass:
954 // FIXME:
955 // We can never form an lvalue with an implicit value initialization as its
956 // base through expression evaluation, so these only appear in one case: the
957 // implicit variable declaration we invent when checking whether a constexpr
958 // constructor can produce a constant expression. We must assume that such
959 // an expression might be a global lvalue.
960 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000961 }
John McCall42c8f872010-05-10 23:27:23 +0000962}
963
Richard Smith83587db2012-02-15 02:18:13 +0000964static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
965 assert(Base && "no location for a null lvalue");
966 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
967 if (VD)
968 Info.Note(VD->getLocation(), diag::note_declared_at);
969 else
970 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
971 diag::note_constexpr_temporary_here);
972}
973
Richard Smith9a17a682011-11-07 05:07:52 +0000974/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000975/// value for an address or reference constant expression. Return true if we
976/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000977static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
978 QualType Type, const LValue &LVal) {
979 bool IsReferenceType = Type->isReferenceType();
980
Richard Smithc1c5f272011-12-13 06:39:58 +0000981 APValue::LValueBase Base = LVal.getLValueBase();
982 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
983
Richard Smithb78ae972012-02-18 04:58:18 +0000984 // Check that the object is a global. Note that the fake 'this' object we
985 // manufacture when checking potential constant expressions is conservatively
986 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000987 if (!IsGlobalLValue(Base)) {
988 if (Info.getLangOpts().CPlusPlus0x) {
989 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000990 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
991 << IsReferenceType << !Designator.Entries.empty()
992 << !!VD << VD;
993 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000994 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000995 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000996 }
Richard Smith61e61622012-01-12 06:08:57 +0000997 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000998 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000999 }
Richard Smith83587db2012-02-15 02:18:13 +00001000 assert((Info.CheckingPotentialConstantExpression ||
1001 LVal.getLValueCallIndex() == 0) &&
1002 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +00001003
1004 // Allow address constant expressions to be past-the-end pointers. This is
1005 // an extension: the standard requires them to point to an object.
1006 if (!IsReferenceType)
1007 return true;
1008
1009 // A reference constant expression must refer to an object.
1010 if (!Base) {
1011 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001012 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001013 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001014 }
1015
Richard Smithc1c5f272011-12-13 06:39:58 +00001016 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001017 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001018 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001019 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001020 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001021 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001022 }
1023
Richard Smith9a17a682011-11-07 05:07:52 +00001024 return true;
1025}
1026
Richard Smith51201882011-12-30 21:15:51 +00001027/// Check that this core constant expression is of literal type, and if not,
1028/// produce an appropriate diagnostic.
1029static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1030 if (!E->isRValue() || E->getType()->isLiteralType())
1031 return true;
1032
1033 // Prvalue constant expressions must be of literal types.
1034 if (Info.getLangOpts().CPlusPlus0x)
Richard Smithd75fb492012-03-15 00:41:48 +00001035 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001036 << E->getType();
1037 else
Richard Smithd75fb492012-03-15 00:41:48 +00001038 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001039 return false;
1040}
1041
Richard Smith47a1eed2011-10-29 20:57:55 +00001042/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001043/// constant expression. If not, report an appropriate diagnostic. Does not
1044/// check that the expression is of literal type.
1045static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1046 QualType Type, const APValue &Value) {
1047 // Core issue 1454: For a literal constant expression of array or class type,
1048 // each subobject of its value shall have been initialized by a constant
1049 // expression.
1050 if (Value.isArray()) {
1051 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1052 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1053 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1054 Value.getArrayInitializedElt(I)))
1055 return false;
1056 }
1057 if (!Value.hasArrayFiller())
1058 return true;
1059 return CheckConstantExpression(Info, DiagLoc, EltTy,
1060 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001061 }
Richard Smith83587db2012-02-15 02:18:13 +00001062 if (Value.isUnion() && Value.getUnionField()) {
1063 return CheckConstantExpression(Info, DiagLoc,
1064 Value.getUnionField()->getType(),
1065 Value.getUnionValue());
1066 }
1067 if (Value.isStruct()) {
1068 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1069 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1070 unsigned BaseIndex = 0;
1071 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1072 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1073 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1074 Value.getStructBase(BaseIndex)))
1075 return false;
1076 }
1077 }
1078 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1079 I != E; ++I) {
1080 if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
1081 Value.getStructField((*I)->getFieldIndex())))
1082 return false;
1083 }
1084 }
1085
1086 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001087 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001088 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001089 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1090 }
1091
1092 // Everything else is fine.
1093 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001094}
1095
Richard Smith9e36b532011-10-31 05:11:32 +00001096const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001097 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001098}
1099
1100static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001101 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001102}
1103
Richard Smith65ac5982011-11-01 21:06:14 +00001104static bool IsWeakLValue(const LValue &Value) {
1105 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001106 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001107}
1108
Richard Smith1aa0be82012-03-03 22:46:17 +00001109static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001110 // A null base expression indicates a null pointer. These are always
1111 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001112 if (!Value.getLValueBase()) {
1113 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001114 return true;
1115 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001116
Richard Smithe24f5fc2011-11-17 22:56:20 +00001117 // We have a non-null base. These are generally known to be true, but if it's
1118 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001119 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001120 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001121 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001122}
1123
Richard Smith1aa0be82012-03-03 22:46:17 +00001124static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001125 switch (Val.getKind()) {
1126 case APValue::Uninitialized:
1127 return false;
1128 case APValue::Int:
1129 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001130 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001131 case APValue::Float:
1132 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001133 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001134 case APValue::ComplexInt:
1135 Result = Val.getComplexIntReal().getBoolValue() ||
1136 Val.getComplexIntImag().getBoolValue();
1137 return true;
1138 case APValue::ComplexFloat:
1139 Result = !Val.getComplexFloatReal().isZero() ||
1140 !Val.getComplexFloatImag().isZero();
1141 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001142 case APValue::LValue:
1143 return EvalPointerValueAsBool(Val, Result);
1144 case APValue::MemberPointer:
1145 Result = Val.getMemberPointerDecl();
1146 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001147 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001148 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001149 case APValue::Struct:
1150 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001151 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001152 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001153 }
1154
Richard Smithc49bd112011-10-28 17:51:58 +00001155 llvm_unreachable("unknown APValue kind");
1156}
1157
1158static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1159 EvalInfo &Info) {
1160 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001161 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001162 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001163 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001164 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001165}
1166
Richard Smithc1c5f272011-12-13 06:39:58 +00001167template<typename T>
1168static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1169 const T &SrcValue, QualType DestType) {
Richard Smithd75fb492012-03-15 00:41:48 +00001170 Info.Diag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001171 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001172 return false;
1173}
1174
1175static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1176 QualType SrcType, const APFloat &Value,
1177 QualType DestType, APSInt &Result) {
1178 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001179 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001180 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Richard Smithc1c5f272011-12-13 06:39:58 +00001182 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001183 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001184 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1185 & APFloat::opInvalidOp)
1186 return HandleOverflow(Info, E, Value, DestType);
1187 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001188}
1189
Richard Smithc1c5f272011-12-13 06:39:58 +00001190static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1191 QualType SrcType, QualType DestType,
1192 APFloat &Result) {
1193 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001194 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001195 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1196 APFloat::rmNearestTiesToEven, &ignored)
1197 & APFloat::opOverflow)
1198 return HandleOverflow(Info, E, Value, DestType);
1199 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001200}
1201
Richard Smithf72fccf2012-01-30 22:27:01 +00001202static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1203 QualType DestType, QualType SrcType,
1204 APSInt &Value) {
1205 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001206 APSInt Result = Value;
1207 // Figure out if this is a truncate, extend or noop cast.
1208 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001209 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001210 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001211 return Result;
1212}
1213
Richard Smithc1c5f272011-12-13 06:39:58 +00001214static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1215 QualType SrcType, const APSInt &Value,
1216 QualType DestType, APFloat &Result) {
1217 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1218 if (Result.convertFromAPInt(Value, Value.isSigned(),
1219 APFloat::rmNearestTiesToEven)
1220 & APFloat::opOverflow)
1221 return HandleOverflow(Info, E, Value, DestType);
1222 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001223}
1224
Eli Friedmane6a24e82011-12-22 03:51:45 +00001225static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1226 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001227 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001228 if (!Evaluate(SVal, Info, E))
1229 return false;
1230 if (SVal.isInt()) {
1231 Res = SVal.getInt();
1232 return true;
1233 }
1234 if (SVal.isFloat()) {
1235 Res = SVal.getFloat().bitcastToAPInt();
1236 return true;
1237 }
1238 if (SVal.isVector()) {
1239 QualType VecTy = E->getType();
1240 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1241 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1242 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1243 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1244 Res = llvm::APInt::getNullValue(VecSize);
1245 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1246 APValue &Elt = SVal.getVectorElt(i);
1247 llvm::APInt EltAsInt;
1248 if (Elt.isInt()) {
1249 EltAsInt = Elt.getInt();
1250 } else if (Elt.isFloat()) {
1251 EltAsInt = Elt.getFloat().bitcastToAPInt();
1252 } else {
1253 // Don't try to handle vectors of anything other than int or float
1254 // (not sure if it's possible to hit this case).
Richard Smithd75fb492012-03-15 00:41:48 +00001255 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001256 return false;
1257 }
1258 unsigned BaseEltSize = EltAsInt.getBitWidth();
1259 if (BigEndian)
1260 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1261 else
1262 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1263 }
1264 return true;
1265 }
1266 // Give up if the input isn't an int, float, or vector. For example, we
1267 // reject "(v4i16)(intptr_t)&a".
Richard Smithd75fb492012-03-15 00:41:48 +00001268 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001269 return false;
1270}
1271
Richard Smithb4e85ed2012-01-06 16:39:00 +00001272/// Cast an lvalue referring to a base subobject to a derived class, by
1273/// truncating the lvalue's path to the given length.
1274static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1275 const RecordDecl *TruncatedType,
1276 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001277 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001278
1279 // Check we actually point to a derived class object.
1280 if (TruncatedElements == D.Entries.size())
1281 return true;
1282 assert(TruncatedElements >= D.MostDerivedPathLength &&
1283 "not casting to a derived class");
1284 if (!Result.checkSubobject(Info, E, CSK_Derived))
1285 return false;
1286
1287 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001288 const RecordDecl *RD = TruncatedType;
1289 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001290 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1291 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001292 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001293 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001294 else
Richard Smith180f4792011-11-10 06:34:14 +00001295 Result.Offset -= Layout.getBaseClassOffset(Base);
1296 RD = Base;
1297 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001298 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001299 return true;
1300}
1301
Richard Smithb4e85ed2012-01-06 16:39:00 +00001302static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001303 const CXXRecordDecl *Derived,
1304 const CXXRecordDecl *Base,
1305 const ASTRecordLayout *RL = 0) {
1306 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1307 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001308 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001309}
1310
Richard Smithb4e85ed2012-01-06 16:39:00 +00001311static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001312 const CXXRecordDecl *DerivedDecl,
1313 const CXXBaseSpecifier *Base) {
1314 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1315
1316 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001317 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001318 return true;
1319 }
1320
Richard Smithb4e85ed2012-01-06 16:39:00 +00001321 SubobjectDesignator &D = Obj.Designator;
1322 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001323 return false;
1324
Richard Smithb4e85ed2012-01-06 16:39:00 +00001325 // Extract most-derived object and corresponding type.
1326 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1327 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1328 return false;
1329
1330 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001331 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1332 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001333 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001334 return true;
1335}
1336
1337/// Update LVal to refer to the given field, which must be a member of the type
1338/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001339static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001340 const FieldDecl *FD,
1341 const ASTRecordLayout *RL = 0) {
1342 if (!RL)
1343 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1344
1345 unsigned I = FD->getFieldIndex();
1346 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001347 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001348}
1349
Richard Smithd9b02e72012-01-25 22:15:11 +00001350/// Update LVal to refer to the given indirect field.
1351static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1352 LValue &LVal,
1353 const IndirectFieldDecl *IFD) {
1354 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1355 CE = IFD->chain_end(); C != CE; ++C)
1356 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1357}
1358
Richard Smith180f4792011-11-10 06:34:14 +00001359/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001360static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1361 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001362 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1363 // extension.
1364 if (Type->isVoidType() || Type->isFunctionType()) {
1365 Size = CharUnits::One();
1366 return true;
1367 }
1368
1369 if (!Type->isConstantSizeType()) {
1370 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001371 // FIXME: Better diagnostic.
1372 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001373 return false;
1374 }
1375
1376 Size = Info.Ctx.getTypeSizeInChars(Type);
1377 return true;
1378}
1379
1380/// Update a pointer value to model pointer arithmetic.
1381/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001382/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001383/// \param LVal - The pointer value to be updated.
1384/// \param EltTy - The pointee type represented by LVal.
1385/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001386static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1387 LValue &LVal, QualType EltTy,
1388 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001389 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001390 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001391 return false;
1392
1393 // Compute the new offset in the appropriate width.
1394 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001395 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001396 return true;
1397}
1398
Richard Smith86024012012-02-18 22:04:06 +00001399/// Update an lvalue to refer to a component of a complex number.
1400/// \param Info - Information about the ongoing evaluation.
1401/// \param LVal - The lvalue to be updated.
1402/// \param EltTy - The complex number's component type.
1403/// \param Imag - False for the real component, true for the imaginary.
1404static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1405 LValue &LVal, QualType EltTy,
1406 bool Imag) {
1407 if (Imag) {
1408 CharUnits SizeOfComponent;
1409 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1410 return false;
1411 LVal.Offset += SizeOfComponent;
1412 }
1413 LVal.addComplex(Info, E, EltTy, Imag);
1414 return true;
1415}
1416
Richard Smith03f96112011-10-24 17:54:18 +00001417/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001418static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1419 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001420 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001421 // If this is a parameter to an active constexpr function call, perform
1422 // argument substitution.
1423 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001424 // Assume arguments of a potential constant expression are unknown
1425 // constant expressions.
1426 if (Info.CheckingPotentialConstantExpression)
1427 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001428 if (!Frame || !Frame->Arguments) {
Richard Smithd75fb492012-03-15 00:41:48 +00001429 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001430 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001431 }
Richard Smith177dce72011-11-01 16:57:24 +00001432 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1433 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001434 }
Richard Smith03f96112011-10-24 17:54:18 +00001435
Richard Smith099e7f62011-12-19 06:19:21 +00001436 // Dig out the initializer, and use the declaration which it's attached to.
1437 const Expr *Init = VD->getAnyInitializer(VD);
1438 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001439 // If we're checking a potential constant expression, the variable could be
1440 // initialized later.
1441 if (!Info.CheckingPotentialConstantExpression)
Richard Smithd75fb492012-03-15 00:41:48 +00001442 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001443 return false;
1444 }
1445
Richard Smith180f4792011-11-10 06:34:14 +00001446 // If we're currently evaluating the initializer of this declaration, use that
1447 // in-flight value.
1448 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001449 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001450 return !Result.isUninit();
1451 }
1452
Richard Smith65ac5982011-11-01 21:06:14 +00001453 // Never evaluate the initializer of a weak variable. We can't be sure that
1454 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001455 if (VD->isWeak()) {
Richard Smithd75fb492012-03-15 00:41:48 +00001456 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001457 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001458 }
Richard Smith65ac5982011-11-01 21:06:14 +00001459
Richard Smith099e7f62011-12-19 06:19:21 +00001460 // Check that we can fold the initializer. In C++, we will have already done
1461 // this in the cases where it matters for conformance.
1462 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1463 if (!VD->evaluateValue(Notes)) {
Richard Smithd75fb492012-03-15 00:41:48 +00001464 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001465 Notes.size() + 1) << VD;
1466 Info.Note(VD->getLocation(), diag::note_declared_at);
1467 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001468 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001469 } else if (!VD->checkInitIsICE()) {
Richard Smithd75fb492012-03-15 00:41:48 +00001470 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001471 Notes.size() + 1) << VD;
1472 Info.Note(VD->getLocation(), diag::note_declared_at);
1473 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001474 }
Richard Smith03f96112011-10-24 17:54:18 +00001475
Richard Smith1aa0be82012-03-03 22:46:17 +00001476 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001477 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001478}
1479
Richard Smithc49bd112011-10-28 17:51:58 +00001480static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001481 Qualifiers Quals = T.getQualifiers();
1482 return Quals.hasConst() && !Quals.hasVolatile();
1483}
1484
Richard Smith59efe262011-11-11 04:05:33 +00001485/// Get the base index of the given base class within an APValue representing
1486/// the given derived class.
1487static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1488 const CXXRecordDecl *Base) {
1489 Base = Base->getCanonicalDecl();
1490 unsigned Index = 0;
1491 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1492 E = Derived->bases_end(); I != E; ++I, ++Index) {
1493 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1494 return Index;
1495 }
1496
1497 llvm_unreachable("base class missing from derived class's bases list");
1498}
1499
Richard Smithf3908f22012-02-17 03:35:37 +00001500/// Extract the value of a character from a string literal.
1501static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1502 uint64_t Index) {
1503 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1504 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1505 assert(S && "unexpected string literal expression kind");
1506
1507 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1508 Lit->getType()->getArrayElementTypeNoTypeQual()->isUnsignedIntegerType());
1509 if (Index < S->getLength())
1510 Value = S->getCodeUnit(Index);
1511 return Value;
1512}
1513
Richard Smithcc5d4f62011-11-07 09:22:26 +00001514/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001515static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001516 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001517 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001518 if (Sub.Invalid)
1519 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001520 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001521 if (Sub.isOnePastTheEnd()) {
Richard Smithd75fb492012-03-15 00:41:48 +00001522 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001523 (unsigned)diag::note_constexpr_read_past_end :
1524 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001525 return false;
1526 }
Richard Smithf64699e2011-11-11 08:28:03 +00001527 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001528 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001529 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1530 // This object might be initialized later.
1531 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001532
Richard Smith0069b842012-03-10 00:28:11 +00001533 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001534 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001535 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001536 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001537 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001538 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001539 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001540 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001541 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001542 // Note, it should not be possible to form a pointer with a valid
1543 // designator which points more than one past the end of the array.
Richard Smithd75fb492012-03-15 00:41:48 +00001544 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001545 (unsigned)diag::note_constexpr_read_past_end :
1546 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001547 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001548 }
Richard Smithf3908f22012-02-17 03:35:37 +00001549 // An array object is represented as either an Array APValue or as an
1550 // LValue which refers to a string literal.
1551 if (O->isLValue()) {
1552 assert(I == N - 1 && "extracting subobject of character?");
1553 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001554 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithf3908f22012-02-17 03:35:37 +00001555 Info, O->getLValueBase().get<const Expr*>(), Index));
1556 return true;
1557 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001558 O = &O->getArrayInitializedElt(Index);
1559 else
1560 O = &O->getArrayFiller();
1561 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001562 } else if (ObjType->isAnyComplexType()) {
1563 // Next subobject is a complex number.
1564 uint64_t Index = Sub.Entries[I].ArrayIndex;
1565 if (Index > 1) {
Richard Smithd75fb492012-03-15 00:41:48 +00001566 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Richard Smith86024012012-02-18 22:04:06 +00001567 (unsigned)diag::note_constexpr_read_past_end :
1568 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1569 return false;
1570 }
1571 assert(I == N - 1 && "extracting subobject of scalar?");
1572 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001573 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001574 : O->getComplexIntReal());
1575 } else {
1576 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001577 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001578 : O->getComplexFloatReal());
1579 }
1580 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001581 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001582 if (Field->isMutable()) {
Richard Smithd75fb492012-03-15 00:41:48 +00001583 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001584 << Field;
1585 Info.Note(Field->getLocation(), diag::note_declared_at);
1586 return false;
1587 }
1588
Richard Smith180f4792011-11-10 06:34:14 +00001589 // Next subobject is a class, struct or union field.
1590 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1591 if (RD->isUnion()) {
1592 const FieldDecl *UnionField = O->getUnionField();
1593 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001594 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithd75fb492012-03-15 00:41:48 +00001595 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001596 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001597 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001598 }
Richard Smith180f4792011-11-10 06:34:14 +00001599 O = &O->getUnionValue();
1600 } else
1601 O = &O->getStructField(Field->getFieldIndex());
1602 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001603
1604 if (ObjType.isVolatileQualified()) {
1605 if (Info.getLangOpts().CPlusPlus) {
1606 // FIXME: Include a description of the path to the volatile subobject.
Richard Smithd75fb492012-03-15 00:41:48 +00001607 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001608 << 2 << Field;
1609 Info.Note(Field->getLocation(), diag::note_declared_at);
1610 } else {
Richard Smithd75fb492012-03-15 00:41:48 +00001611 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001612 }
1613 return false;
1614 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001615 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001616 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001617 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1618 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1619 O = &O->getStructBase(getBaseIndex(Derived, Base));
1620 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001621 }
Richard Smith180f4792011-11-10 06:34:14 +00001622
Richard Smithf48fdb02011-12-09 22:58:01 +00001623 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001624 if (!Info.CheckingPotentialConstantExpression)
Richard Smithd75fb492012-03-15 00:41:48 +00001625 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001626 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001627 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001628 }
1629
Richard Smith0069b842012-03-10 00:28:11 +00001630 // This may look super-stupid, but it serves an important purpose: if we just
1631 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1632 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1633 // object, which is destroyed by Tmp's destructor.
1634 APValue Tmp;
1635 O->swap(Tmp);
1636 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001637 return true;
1638}
1639
Richard Smithf15fda02012-02-02 01:16:57 +00001640/// Find the position where two subobject designators diverge, or equivalently
1641/// the length of the common initial subsequence.
1642static unsigned FindDesignatorMismatch(QualType ObjType,
1643 const SubobjectDesignator &A,
1644 const SubobjectDesignator &B,
1645 bool &WasArrayIndex) {
1646 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1647 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001648 if (!ObjType.isNull() &&
1649 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001650 // Next subobject is an array element.
1651 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1652 WasArrayIndex = true;
1653 return I;
1654 }
Richard Smith86024012012-02-18 22:04:06 +00001655 if (ObjType->isAnyComplexType())
1656 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1657 else
1658 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001659 } else {
1660 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1661 WasArrayIndex = false;
1662 return I;
1663 }
1664 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1665 // Next subobject is a field.
1666 ObjType = FD->getType();
1667 else
1668 // Next subobject is a base class.
1669 ObjType = QualType();
1670 }
1671 }
1672 WasArrayIndex = false;
1673 return I;
1674}
1675
1676/// Determine whether the given subobject designators refer to elements of the
1677/// same array object.
1678static bool AreElementsOfSameArray(QualType ObjType,
1679 const SubobjectDesignator &A,
1680 const SubobjectDesignator &B) {
1681 if (A.Entries.size() != B.Entries.size())
1682 return false;
1683
1684 bool IsArray = A.MostDerivedArraySize != 0;
1685 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1686 // A is a subobject of the array element.
1687 return false;
1688
1689 // If A (and B) designates an array element, the last entry will be the array
1690 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1691 // of length 1' case, and the entire path must match.
1692 bool WasArrayIndex;
1693 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1694 return CommonLength >= A.Entries.size() - IsArray;
1695}
1696
Richard Smith180f4792011-11-10 06:34:14 +00001697/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1698/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1699/// for looking up the glvalue referred to by an entity of reference type.
1700///
1701/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001702/// \param Conv - The expression for which we are performing the conversion.
1703/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001704/// \param Type - The type we expect this conversion to produce, before
1705/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001706/// \param LVal - The glvalue on which we are attempting to perform this action.
1707/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001708static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1709 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001710 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001711 if (LVal.Designator.Invalid)
1712 // A diagnostic will have already been produced.
1713 return false;
1714
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001715 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001716
Richard Smithf48fdb02011-12-09 22:58:01 +00001717 if (!LVal.Base) {
1718 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithd75fb492012-03-15 00:41:48 +00001719 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001720 return false;
1721 }
1722
Richard Smith83587db2012-02-15 02:18:13 +00001723 CallStackFrame *Frame = 0;
1724 if (LVal.CallIndex) {
1725 Frame = Info.getCallFrame(LVal.CallIndex);
1726 if (!Frame) {
Richard Smithd75fb492012-03-15 00:41:48 +00001727 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001728 NoteLValueLocation(Info, LVal.Base);
1729 return false;
1730 }
1731 }
1732
Richard Smith7098cbd2011-12-21 05:04:46 +00001733 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1734 // is not a constant expression (even if the object is non-volatile). We also
1735 // apply this rule to C++98, in order to conform to the expected 'volatile'
1736 // semantics.
1737 if (Type.isVolatileQualified()) {
1738 if (Info.getLangOpts().CPlusPlus)
Richard Smithd75fb492012-03-15 00:41:48 +00001739 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001740 else
Richard Smithd75fb492012-03-15 00:41:48 +00001741 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001742 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001743 }
Richard Smithc49bd112011-10-28 17:51:58 +00001744
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001745 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001746 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1747 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001748 // expressions are constant expressions too. Inside constexpr functions,
1749 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001750 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001751 const VarDecl *VD = dyn_cast<VarDecl>(D);
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001752 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
Richard Smithf15fda02012-02-02 01:16:57 +00001753 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001754 if (!VD || VD->isInvalidDecl()) {
Richard Smithd75fb492012-03-15 00:41:48 +00001755 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001756 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001757 }
1758
Richard Smith7098cbd2011-12-21 05:04:46 +00001759 // DR1313: If the object is volatile-qualified but the glvalue was not,
1760 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001761 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001762 if (VT.isVolatileQualified()) {
1763 if (Info.getLangOpts().CPlusPlus) {
Richard Smithd75fb492012-03-15 00:41:48 +00001764 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001765 Info.Note(VD->getLocation(), diag::note_declared_at);
1766 } else {
Richard Smithd75fb492012-03-15 00:41:48 +00001767 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001768 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001769 return false;
1770 }
1771
1772 if (!isa<ParmVarDecl>(VD)) {
1773 if (VD->isConstexpr()) {
1774 // OK, we can read this variable.
1775 } else if (VT->isIntegralOrEnumerationType()) {
1776 if (!VT.isConstQualified()) {
1777 if (Info.getLangOpts().CPlusPlus) {
Richard Smithd75fb492012-03-15 00:41:48 +00001778 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001779 Info.Note(VD->getLocation(), diag::note_declared_at);
1780 } else {
Richard Smithd75fb492012-03-15 00:41:48 +00001781 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001782 }
1783 return false;
1784 }
1785 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1786 // We support folding of const floating-point types, in order to make
1787 // static const data members of such types (supported as an extension)
1788 // more useful.
1789 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smithd75fb492012-03-15 00:41:48 +00001790 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001791 Info.Note(VD->getLocation(), diag::note_declared_at);
1792 } else {
Richard Smithd75fb492012-03-15 00:41:48 +00001793 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001794 }
1795 } else {
1796 // FIXME: Allow folding of values of any literal type in all languages.
1797 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smithd75fb492012-03-15 00:41:48 +00001798 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001799 Info.Note(VD->getLocation(), diag::note_declared_at);
1800 } else {
Richard Smithd75fb492012-03-15 00:41:48 +00001801 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001802 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001803 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001804 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001805 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001806
Richard Smithf48fdb02011-12-09 22:58:01 +00001807 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001808 return false;
1809
Richard Smith47a1eed2011-10-29 20:57:55 +00001810 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001811 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001812
1813 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1814 // conversion. This happens when the declaration and the lvalue should be
1815 // considered synonymous, for instance when initializing an array of char
1816 // from a string literal. Continue as if the initializer lvalue was the
1817 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001818 assert(RVal.getLValueOffset().isZero() &&
1819 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001820 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001821
1822 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1823 Frame = Info.getCallFrame(CallIndex);
1824 if (!Frame) {
Richard Smithd75fb492012-03-15 00:41:48 +00001825 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001826 NoteLValueLocation(Info, RVal.getLValueBase());
1827 return false;
1828 }
1829 } else {
1830 Frame = 0;
1831 }
Richard Smithc49bd112011-10-28 17:51:58 +00001832 }
1833
Richard Smith7098cbd2011-12-21 05:04:46 +00001834 // Volatile temporary objects cannot be read in constant expressions.
1835 if (Base->getType().isVolatileQualified()) {
1836 if (Info.getLangOpts().CPlusPlus) {
Richard Smithd75fb492012-03-15 00:41:48 +00001837 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001838 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1839 } else {
Richard Smithd75fb492012-03-15 00:41:48 +00001840 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001841 }
1842 return false;
1843 }
1844
Richard Smithcc5d4f62011-11-07 09:22:26 +00001845 if (Frame) {
1846 // If this is a temporary expression with a nontrivial initializer, grab the
1847 // value from the relevant stack frame.
1848 RVal = Frame->Temporaries[Base];
1849 } else if (const CompoundLiteralExpr *CLE
1850 = dyn_cast<CompoundLiteralExpr>(Base)) {
1851 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1852 // initializer until now for such expressions. Such an expression can't be
1853 // an ICE in C, so this only matters for fold.
1854 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1855 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1856 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001857 } else if (isa<StringLiteral>(Base)) {
1858 // We represent a string literal array as an lvalue pointing at the
1859 // corresponding expression, rather than building an array of chars.
1860 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001861 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001862 } else {
Richard Smithd75fb492012-03-15 00:41:48 +00001863 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001864 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001865 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001866
Richard Smithf48fdb02011-12-09 22:58:01 +00001867 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1868 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001869}
1870
Richard Smith59efe262011-11-11 04:05:33 +00001871/// Build an lvalue for the object argument of a member function call.
1872static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1873 LValue &This) {
1874 if (Object->getType()->isPointerType())
1875 return EvaluatePointer(Object, This, Info);
1876
1877 if (Object->isGLValue())
1878 return EvaluateLValue(Object, This, Info);
1879
Richard Smithe24f5fc2011-11-17 22:56:20 +00001880 if (Object->getType()->isLiteralType())
1881 return EvaluateTemporary(Object, This, Info);
1882
1883 return false;
1884}
1885
1886/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1887/// lvalue referring to the result.
1888///
1889/// \param Info - Information about the ongoing evaluation.
1890/// \param BO - The member pointer access operation.
1891/// \param LV - Filled in with a reference to the resulting object.
1892/// \param IncludeMember - Specifies whether the member itself is included in
1893/// the resulting LValue subobject designator. This is not possible when
1894/// creating a bound member function.
1895/// \return The field or method declaration to which the member pointer refers,
1896/// or 0 if evaluation fails.
1897static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1898 const BinaryOperator *BO,
1899 LValue &LV,
1900 bool IncludeMember = true) {
1901 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1902
Richard Smith745f5142012-01-27 01:14:48 +00001903 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1904 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001905 return 0;
1906
1907 MemberPtr MemPtr;
1908 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1909 return 0;
1910
1911 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1912 // member value, the behavior is undefined.
1913 if (!MemPtr.getDecl())
1914 return 0;
1915
Richard Smith745f5142012-01-27 01:14:48 +00001916 if (!EvalObjOK)
1917 return 0;
1918
Richard Smithe24f5fc2011-11-17 22:56:20 +00001919 if (MemPtr.isDerivedMember()) {
1920 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001921 // The end of the derived-to-base path for the base object must match the
1922 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001923 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001924 LV.Designator.Entries.size())
1925 return 0;
1926 unsigned PathLengthToMember =
1927 LV.Designator.Entries.size() - MemPtr.Path.size();
1928 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1929 const CXXRecordDecl *LVDecl = getAsBaseClass(
1930 LV.Designator.Entries[PathLengthToMember + I]);
1931 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1932 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1933 return 0;
1934 }
1935
1936 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001937 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1938 PathLengthToMember))
1939 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001940 } else if (!MemPtr.Path.empty()) {
1941 // Extend the LValue path with the member pointer's path.
1942 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1943 MemPtr.Path.size() + IncludeMember);
1944
1945 // Walk down to the appropriate base class.
1946 QualType LVType = BO->getLHS()->getType();
1947 if (const PointerType *PT = LVType->getAs<PointerType>())
1948 LVType = PT->getPointeeType();
1949 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1950 assert(RD && "member pointer access on non-class-type expression");
1951 // The first class in the path is that of the lvalue.
1952 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1953 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001954 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001955 RD = Base;
1956 }
1957 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001958 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001959 }
1960
1961 // Add the member. Note that we cannot build bound member functions here.
1962 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001963 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1964 HandleLValueMember(Info, BO, LV, FD);
1965 else if (const IndirectFieldDecl *IFD =
1966 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1967 HandleLValueIndirectMember(Info, BO, LV, IFD);
1968 else
1969 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001970 }
1971
1972 return MemPtr.getDecl();
1973}
1974
1975/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1976/// the provided lvalue, which currently refers to the base object.
1977static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1978 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001979 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001980 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001981 return false;
1982
Richard Smithb4e85ed2012-01-06 16:39:00 +00001983 QualType TargetQT = E->getType();
1984 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1985 TargetQT = PT->getPointeeType();
1986
1987 // Check this cast lands within the final derived-to-base subobject path.
1988 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithd75fb492012-03-15 00:41:48 +00001989 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00001990 << D.MostDerivedType << TargetQT;
1991 return false;
1992 }
1993
Richard Smithe24f5fc2011-11-17 22:56:20 +00001994 // Check the type of the final cast. We don't need to check the path,
1995 // since a cast can only be formed if the path is unique.
1996 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001997 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1998 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001999 if (NewEntriesSize == D.MostDerivedPathLength)
2000 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2001 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002002 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002003 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithd75fb492012-03-15 00:41:48 +00002004 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002005 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002006 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002007 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002008
2009 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002010 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002011}
2012
Mike Stumpc4c90452009-10-27 22:09:17 +00002013namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002014enum EvalStmtResult {
2015 /// Evaluation failed.
2016 ESR_Failed,
2017 /// Hit a 'return' statement.
2018 ESR_Returned,
2019 /// Evaluation succeeded.
2020 ESR_Succeeded
2021};
2022}
2023
2024// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002025static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002026 const Stmt *S) {
2027 switch (S->getStmtClass()) {
2028 default:
2029 return ESR_Failed;
2030
2031 case Stmt::NullStmtClass:
2032 case Stmt::DeclStmtClass:
2033 return ESR_Succeeded;
2034
Richard Smithc1c5f272011-12-13 06:39:58 +00002035 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002036 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002037 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002038 return ESR_Failed;
2039 return ESR_Returned;
2040 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002041
2042 case Stmt::CompoundStmtClass: {
2043 const CompoundStmt *CS = cast<CompoundStmt>(S);
2044 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2045 BE = CS->body_end(); BI != BE; ++BI) {
2046 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2047 if (ESR != ESR_Succeeded)
2048 return ESR;
2049 }
2050 return ESR_Succeeded;
2051 }
2052 }
2053}
2054
Richard Smith61802452011-12-22 02:22:31 +00002055/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2056/// default constructor. If so, we'll fold it whether or not it's marked as
2057/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2058/// so we need special handling.
2059static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002060 const CXXConstructorDecl *CD,
2061 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002062 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2063 return false;
2064
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002065 // Value-initialization does not call a trivial default constructor, so such a
2066 // call is a core constant expression whether or not the constructor is
2067 // constexpr.
2068 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002069 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002070 // FIXME: If DiagDecl is an implicitly-declared special member function,
2071 // we should be much more explicit about why it's not constexpr.
2072 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2073 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2074 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002075 } else {
2076 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2077 }
2078 }
2079 return true;
2080}
2081
Richard Smithc1c5f272011-12-13 06:39:58 +00002082/// CheckConstexprFunction - Check that a function can be called in a constant
2083/// expression.
2084static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2085 const FunctionDecl *Declaration,
2086 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002087 // Potential constant expressions can contain calls to declared, but not yet
2088 // defined, constexpr functions.
2089 if (Info.CheckingPotentialConstantExpression && !Definition &&
2090 Declaration->isConstexpr())
2091 return false;
2092
Richard Smithc1c5f272011-12-13 06:39:58 +00002093 // Can we evaluate this function call?
2094 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2095 return true;
2096
2097 if (Info.getLangOpts().CPlusPlus0x) {
2098 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002099 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2100 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002101 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2102 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2103 << DiagDecl;
2104 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2105 } else {
2106 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2107 }
2108 return false;
2109}
2110
Richard Smith180f4792011-11-10 06:34:14 +00002111namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002112typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002113}
2114
2115/// EvaluateArgs - Evaluate the arguments to a function call.
2116static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2117 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002118 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002119 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002120 I != E; ++I) {
2121 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2122 // If we're checking for a potential constant expression, evaluate all
2123 // initializers even if some of them fail.
2124 if (!Info.keepEvaluatingAfterFailure())
2125 return false;
2126 Success = false;
2127 }
2128 }
2129 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002130}
2131
Richard Smithd0dccea2011-10-28 22:34:42 +00002132/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002133static bool HandleFunctionCall(SourceLocation CallLoc,
2134 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002135 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002136 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002137 ArgVector ArgValues(Args.size());
2138 if (!EvaluateArgs(Args, ArgValues, Info))
2139 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002140
Richard Smith745f5142012-01-27 01:14:48 +00002141 if (!Info.CheckCallLimit(CallLoc))
2142 return false;
2143
2144 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002145 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2146}
2147
Richard Smith180f4792011-11-10 06:34:14 +00002148/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002149static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002150 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002151 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002152 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002153 ArgVector ArgValues(Args.size());
2154 if (!EvaluateArgs(Args, ArgValues, Info))
2155 return false;
2156
Richard Smith745f5142012-01-27 01:14:48 +00002157 if (!Info.CheckCallLimit(CallLoc))
2158 return false;
2159
Richard Smith86c3ae42012-02-13 03:54:03 +00002160 const CXXRecordDecl *RD = Definition->getParent();
2161 if (RD->getNumVBases()) {
2162 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2163 return false;
2164 }
2165
Richard Smith745f5142012-01-27 01:14:48 +00002166 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002167
2168 // If it's a delegating constructor, just delegate.
2169 if (Definition->isDelegatingConstructor()) {
2170 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002171 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002172 }
2173
Richard Smith610a60c2012-01-10 04:32:03 +00002174 // For a trivial copy or move constructor, perform an APValue copy. This is
2175 // essential for unions, where the operations performed by the constructor
2176 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002177 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002178 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2179 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002180 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002181 RHS.setFrom(Info.Ctx, ArgValues[0]);
2182 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2183 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002184 }
2185
2186 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002187 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002188 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2189 std::distance(RD->field_begin(), RD->field_end()));
2190
2191 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2192
Richard Smith745f5142012-01-27 01:14:48 +00002193 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002194 unsigned BasesSeen = 0;
2195#ifndef NDEBUG
2196 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2197#endif
2198 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2199 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002200 LValue Subobject = This;
2201 APValue *Value = &Result;
2202
2203 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002204 if ((*I)->isBaseInitializer()) {
2205 QualType BaseType((*I)->getBaseClass(), 0);
2206#ifndef NDEBUG
2207 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002208 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002209 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2210 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2211 "base class initializers not in expected order");
2212 ++BaseIt;
2213#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002214 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002215 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002216 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002217 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002218 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002219 if (RD->isUnion()) {
2220 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002221 Value = &Result.getUnionValue();
2222 } else {
2223 Value = &Result.getStructField(FD->getFieldIndex());
2224 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002225 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002226 // Walk the indirect field decl's chain to find the object to initialize,
2227 // and make sure we've initialized every step along it.
2228 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2229 CE = IFD->chain_end();
2230 C != CE; ++C) {
2231 FieldDecl *FD = cast<FieldDecl>(*C);
2232 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2233 // Switch the union field if it differs. This happens if we had
2234 // preceding zero-initialization, and we're now initializing a union
2235 // subobject other than the first.
2236 // FIXME: In this case, the values of the other subobjects are
2237 // specified, since zero-initialization sets all padding bits to zero.
2238 if (Value->isUninit() ||
2239 (Value->isUnion() && Value->getUnionField() != FD)) {
2240 if (CD->isUnion())
2241 *Value = APValue(FD);
2242 else
2243 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2244 std::distance(CD->field_begin(), CD->field_end()));
2245 }
Richard Smith745f5142012-01-27 01:14:48 +00002246 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002247 if (CD->isUnion())
2248 Value = &Value->getUnionValue();
2249 else
2250 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002251 }
Richard Smith180f4792011-11-10 06:34:14 +00002252 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002253 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002254 }
Richard Smith745f5142012-01-27 01:14:48 +00002255
Richard Smith83587db2012-02-15 02:18:13 +00002256 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2257 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002258 ? CCEK_Constant : CCEK_MemberInit)) {
2259 // If we're checking for a potential constant expression, evaluate all
2260 // initializers even if some of them fail.
2261 if (!Info.keepEvaluatingAfterFailure())
2262 return false;
2263 Success = false;
2264 }
Richard Smith180f4792011-11-10 06:34:14 +00002265 }
2266
Richard Smith745f5142012-01-27 01:14:48 +00002267 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002268}
2269
Richard Smithd0dccea2011-10-28 22:34:42 +00002270namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002271class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002272 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002273 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002274public:
2275
Richard Smith1e12c592011-10-16 21:26:27 +00002276 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002277
2278 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002279 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002280 return true;
2281 }
2282
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002283 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2284 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002285 return Visit(E->getResultExpr());
2286 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002287 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002288 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002289 return true;
2290 return false;
2291 }
John McCallf85e1932011-06-15 23:02:42 +00002292 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002293 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002294 return true;
2295 return false;
2296 }
John McCallf85e1932011-06-15 23:02:42 +00002297
Mike Stumpc4c90452009-10-27 22:09:17 +00002298 // We don't want to evaluate BlockExprs multiple times, as they generate
2299 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002300 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2301 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2302 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002303 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002304 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2305 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2306 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2307 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2308 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2309 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002310 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002311 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002312 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002313 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002314 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002315 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2316 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2317 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2318 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002319 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002320 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2321 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2322 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2323 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2324 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002325 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002326 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002327 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002328 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002329 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002330
2331 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002332 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002333 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2334 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002335 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002336 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002337 return false;
2338 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002339
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002340 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002341};
2342
John McCall56ca35d2011-02-17 10:25:35 +00002343class OpaqueValueEvaluation {
2344 EvalInfo &info;
2345 OpaqueValueExpr *opaqueValue;
2346
2347public:
2348 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2349 Expr *value)
2350 : info(info), opaqueValue(opaqueValue) {
2351
2352 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002353 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002354 this->opaqueValue = 0;
2355 return;
2356 }
John McCall56ca35d2011-02-17 10:25:35 +00002357 }
2358
2359 bool hasError() const { return opaqueValue == 0; }
2360
2361 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002362 // FIXME: For a recursive constexpr call, an outer stack frame might have
2363 // been using this opaque value too, and will now have to re-evaluate the
2364 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002365 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2366 }
2367};
2368
Mike Stumpc4c90452009-10-27 22:09:17 +00002369} // end anonymous namespace
2370
Eli Friedman4efaa272008-11-12 09:44:48 +00002371//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002372// Generic Evaluation
2373//===----------------------------------------------------------------------===//
2374namespace {
2375
Richard Smithf48fdb02011-12-09 22:58:01 +00002376// FIXME: RetTy is always bool. Remove it.
2377template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002378class ExprEvaluatorBase
2379 : public ConstStmtVisitor<Derived, RetTy> {
2380private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002381 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002382 return static_cast<Derived*>(this)->Success(V, E);
2383 }
Richard Smith51201882011-12-30 21:15:51 +00002384 RetTy DerivedZeroInitialization(const Expr *E) {
2385 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002386 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002387
Richard Smith74e1ad92012-02-16 02:46:34 +00002388 // Check whether a conditional operator with a non-constant condition is a
2389 // potential constant expression. If neither arm is a potential constant
2390 // expression, then the conditional operator is not either.
2391 template<typename ConditionalOperator>
2392 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2393 assert(Info.CheckingPotentialConstantExpression);
2394
2395 // Speculatively evaluate both arms.
2396 {
2397 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2398 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2399
2400 StmtVisitorTy::Visit(E->getFalseExpr());
2401 if (Diag.empty())
2402 return;
2403
2404 Diag.clear();
2405 StmtVisitorTy::Visit(E->getTrueExpr());
2406 if (Diag.empty())
2407 return;
2408 }
2409
2410 Error(E, diag::note_constexpr_conditional_never_const);
2411 }
2412
2413
2414 template<typename ConditionalOperator>
2415 bool HandleConditionalOperator(const ConditionalOperator *E) {
2416 bool BoolResult;
2417 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2418 if (Info.CheckingPotentialConstantExpression)
2419 CheckPotentialConstantConditional(E);
2420 return false;
2421 }
2422
2423 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2424 return StmtVisitorTy::Visit(EvalExpr);
2425 }
2426
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002427protected:
2428 EvalInfo &Info;
2429 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2430 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2431
Richard Smithdd1f29b2011-12-12 09:28:41 +00002432 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd75fb492012-03-15 00:41:48 +00002433 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002434 }
2435
2436 /// Report an evaluation error. This should only be called when an error is
2437 /// first discovered. When propagating an error, just return false.
2438 bool Error(const Expr *E, diag::kind D) {
Richard Smithd75fb492012-03-15 00:41:48 +00002439 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002440 return false;
2441 }
2442 bool Error(const Expr *E) {
2443 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2444 }
2445
Richard Smith51201882011-12-30 21:15:51 +00002446 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002447
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002448public:
2449 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2450
2451 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002452 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002453 }
2454 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002455 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002456 }
2457
2458 RetTy VisitParenExpr(const ParenExpr *E)
2459 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2460 RetTy VisitUnaryExtension(const UnaryOperator *E)
2461 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2462 RetTy VisitUnaryPlus(const UnaryOperator *E)
2463 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2464 RetTy VisitChooseExpr(const ChooseExpr *E)
2465 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2466 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2467 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002468 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2469 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002470 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2471 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002472 // We cannot create any objects for which cleanups are required, so there is
2473 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2474 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2475 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002476
Richard Smithc216a012011-12-12 12:46:16 +00002477 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2478 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2479 return static_cast<Derived*>(this)->VisitCastExpr(E);
2480 }
2481 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2482 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2483 return static_cast<Derived*>(this)->VisitCastExpr(E);
2484 }
2485
Richard Smithe24f5fc2011-11-17 22:56:20 +00002486 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2487 switch (E->getOpcode()) {
2488 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002489 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002490
2491 case BO_Comma:
2492 VisitIgnoredValue(E->getLHS());
2493 return StmtVisitorTy::Visit(E->getRHS());
2494
2495 case BO_PtrMemD:
2496 case BO_PtrMemI: {
2497 LValue Obj;
2498 if (!HandleMemberPointerAccess(Info, E, Obj))
2499 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002500 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002501 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002502 return false;
2503 return DerivedSuccess(Result, E);
2504 }
2505 }
2506 }
2507
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002508 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002509 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002510 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2511 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002512 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002513
Richard Smith74e1ad92012-02-16 02:46:34 +00002514 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002515 }
2516
2517 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002518 bool IsBcpCall = false;
2519 // If the condition (ignoring parens) is a __builtin_constant_p call,
2520 // the result is a constant expression if it can be folded without
2521 // side-effects. This is an important GNU extension. See GCC PR38377
2522 // for discussion.
2523 if (const CallExpr *CallCE =
2524 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2525 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2526 IsBcpCall = true;
2527
2528 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2529 // constant expression; we can't check whether it's potentially foldable.
2530 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2531 return false;
2532
2533 FoldConstant Fold(Info);
2534
Richard Smith74e1ad92012-02-16 02:46:34 +00002535 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002536 return false;
2537
2538 if (IsBcpCall)
2539 Fold.Fold(Info);
2540
2541 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002542 }
2543
2544 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002545 const APValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002546 if (!Value) {
2547 const Expr *Source = E->getSourceExpr();
2548 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002549 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002550 if (Source == E) { // sanity checking.
2551 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002552 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002553 }
2554 return StmtVisitorTy::Visit(Source);
2555 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002556 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002557 }
Richard Smithf10d9172011-10-11 21:43:33 +00002558
Richard Smithd0dccea2011-10-28 22:34:42 +00002559 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002560 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002561 QualType CalleeType = Callee->getType();
2562
Richard Smithd0dccea2011-10-28 22:34:42 +00002563 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002564 LValue *This = 0, ThisVal;
2565 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002566 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002567
Richard Smith59efe262011-11-11 04:05:33 +00002568 // Extract function decl and 'this' pointer from the callee.
2569 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002570 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002571 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2572 // Explicit bound member calls, such as x.f() or p->g();
2573 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002574 return false;
2575 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002576 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002577 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002578 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2579 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002580 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2581 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002582 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002583 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002584 return Error(Callee);
2585
2586 FD = dyn_cast<FunctionDecl>(Member);
2587 if (!FD)
2588 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002589 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002590 LValue Call;
2591 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002592 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002593
Richard Smithb4e85ed2012-01-06 16:39:00 +00002594 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002595 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002596 FD = dyn_cast_or_null<FunctionDecl>(
2597 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002598 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002599 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002600
2601 // Overloaded operator calls to member functions are represented as normal
2602 // calls with '*this' as the first argument.
2603 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2604 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002605 // FIXME: When selecting an implicit conversion for an overloaded
2606 // operator delete, we sometimes try to evaluate calls to conversion
2607 // operators without a 'this' parameter!
2608 if (Args.empty())
2609 return Error(E);
2610
Richard Smith59efe262011-11-11 04:05:33 +00002611 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2612 return false;
2613 This = &ThisVal;
2614 Args = Args.slice(1);
2615 }
2616
2617 // Don't call function pointers which have been cast to some other type.
2618 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002619 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002620 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002621 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002622
Richard Smithb04035a2012-02-01 02:39:43 +00002623 if (This && !This->checkSubobject(Info, E, CSK_This))
2624 return false;
2625
Richard Smith86c3ae42012-02-13 03:54:03 +00002626 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2627 // calls to such functions in constant expressions.
2628 if (This && !HasQualifier &&
2629 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2630 return Error(E, diag::note_constexpr_virtual_call);
2631
Richard Smithc1c5f272011-12-13 06:39:58 +00002632 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002633 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002634 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002635
Richard Smithc1c5f272011-12-13 06:39:58 +00002636 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002637 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2638 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002639 return false;
2640
Richard Smith83587db2012-02-15 02:18:13 +00002641 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002642 }
2643
Richard Smithc49bd112011-10-28 17:51:58 +00002644 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2645 return StmtVisitorTy::Visit(E->getInitializer());
2646 }
Richard Smithf10d9172011-10-11 21:43:33 +00002647 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002648 if (E->getNumInits() == 0)
2649 return DerivedZeroInitialization(E);
2650 if (E->getNumInits() == 1)
2651 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002652 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002653 }
2654 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002655 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002656 }
2657 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002658 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002659 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002660 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002661 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002662 }
Richard Smithf10d9172011-10-11 21:43:33 +00002663
Richard Smith180f4792011-11-10 06:34:14 +00002664 /// A member expression where the object is a prvalue is itself a prvalue.
2665 RetTy VisitMemberExpr(const MemberExpr *E) {
2666 assert(!E->isArrow() && "missing call to bound member function?");
2667
Richard Smith1aa0be82012-03-03 22:46:17 +00002668 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002669 if (!Evaluate(Val, Info, E->getBase()))
2670 return false;
2671
2672 QualType BaseTy = E->getBase()->getType();
2673
2674 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002675 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002676 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2677 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2678 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2679
Richard Smithb4e85ed2012-01-06 16:39:00 +00002680 SubobjectDesignator Designator(BaseTy);
2681 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002682
Richard Smithf48fdb02011-12-09 22:58:01 +00002683 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002684 DerivedSuccess(Val, E);
2685 }
2686
Richard Smithc49bd112011-10-28 17:51:58 +00002687 RetTy VisitCastExpr(const CastExpr *E) {
2688 switch (E->getCastKind()) {
2689 default:
2690 break;
2691
David Chisnall7a7ee302012-01-16 17:27:18 +00002692 case CK_AtomicToNonAtomic:
2693 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002694 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002695 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002696 return StmtVisitorTy::Visit(E->getSubExpr());
2697
2698 case CK_LValueToRValue: {
2699 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002700 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2701 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002702 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002703 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2704 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2705 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002706 return false;
2707 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002708 }
2709 }
2710
Richard Smithf48fdb02011-12-09 22:58:01 +00002711 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002712 }
2713
Richard Smith8327fad2011-10-24 18:44:57 +00002714 /// Visit a value which is evaluated, but whose value is ignored.
2715 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002716 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002717 if (!Evaluate(Scratch, Info, E))
2718 Info.EvalStatus.HasSideEffects = true;
2719 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002720};
2721
2722}
2723
2724//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002725// Common base class for lvalue and temporary evaluation.
2726//===----------------------------------------------------------------------===//
2727namespace {
2728template<class Derived>
2729class LValueExprEvaluatorBase
2730 : public ExprEvaluatorBase<Derived, bool> {
2731protected:
2732 LValue &Result;
2733 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2734 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2735
2736 bool Success(APValue::LValueBase B) {
2737 Result.set(B);
2738 return true;
2739 }
2740
2741public:
2742 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2743 ExprEvaluatorBaseTy(Info), Result(Result) {}
2744
Richard Smith1aa0be82012-03-03 22:46:17 +00002745 bool Success(const APValue &V, const Expr *E) {
2746 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002747 return true;
2748 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002749
Richard Smithe24f5fc2011-11-17 22:56:20 +00002750 bool VisitMemberExpr(const MemberExpr *E) {
2751 // Handle non-static data members.
2752 QualType BaseTy;
2753 if (E->isArrow()) {
2754 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2755 return false;
2756 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002757 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002758 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002759 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2760 return false;
2761 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002762 } else {
2763 if (!this->Visit(E->getBase()))
2764 return false;
2765 BaseTy = E->getBase()->getType();
2766 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002767
Richard Smithd9b02e72012-01-25 22:15:11 +00002768 const ValueDecl *MD = E->getMemberDecl();
2769 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2770 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2771 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2772 (void)BaseTy;
2773 HandleLValueMember(this->Info, E, Result, FD);
2774 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2775 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2776 } else
2777 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002778
Richard Smithd9b02e72012-01-25 22:15:11 +00002779 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002780 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002781 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002782 RefValue))
2783 return false;
2784 return Success(RefValue, E);
2785 }
2786 return true;
2787 }
2788
2789 bool VisitBinaryOperator(const BinaryOperator *E) {
2790 switch (E->getOpcode()) {
2791 default:
2792 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2793
2794 case BO_PtrMemD:
2795 case BO_PtrMemI:
2796 return HandleMemberPointerAccess(this->Info, E, Result);
2797 }
2798 }
2799
2800 bool VisitCastExpr(const CastExpr *E) {
2801 switch (E->getCastKind()) {
2802 default:
2803 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2804
2805 case CK_DerivedToBase:
2806 case CK_UncheckedDerivedToBase: {
2807 if (!this->Visit(E->getSubExpr()))
2808 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002809
2810 // Now figure out the necessary offset to add to the base LV to get from
2811 // the derived class to the base class.
2812 QualType Type = E->getSubExpr()->getType();
2813
2814 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2815 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002816 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002817 *PathI))
2818 return false;
2819 Type = (*PathI)->getType();
2820 }
2821
2822 return true;
2823 }
2824 }
2825 }
2826};
2827}
2828
2829//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002830// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002831//
2832// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2833// function designators (in C), decl references to void objects (in C), and
2834// temporaries (if building with -Wno-address-of-temporary).
2835//
2836// LValue evaluation produces values comprising a base expression of one of the
2837// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002838// - Declarations
2839// * VarDecl
2840// * FunctionDecl
2841// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002842// * CompoundLiteralExpr in C
2843// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002844// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002845// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002846// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002847// * ObjCEncodeExpr
2848// * AddrLabelExpr
2849// * BlockExpr
2850// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002851// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002852// * Any Expr, with a CallIndex indicating the function in which the temporary
2853// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002854// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002855//===----------------------------------------------------------------------===//
2856namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002857class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002858 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002859public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002860 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2861 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002862
Richard Smithc49bd112011-10-28 17:51:58 +00002863 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2864
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002865 bool VisitDeclRefExpr(const DeclRefExpr *E);
2866 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002867 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002868 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2869 bool VisitMemberExpr(const MemberExpr *E);
2870 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2871 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002872 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002873 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2874 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002875 bool VisitUnaryReal(const UnaryOperator *E);
2876 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002877
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002878 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002879 switch (E->getCastKind()) {
2880 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002881 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002882
Eli Friedmandb924222011-10-11 00:13:24 +00002883 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002884 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002885 if (!Visit(E->getSubExpr()))
2886 return false;
2887 Result.Designator.setInvalid();
2888 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002889
Richard Smithe24f5fc2011-11-17 22:56:20 +00002890 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002891 if (!Visit(E->getSubExpr()))
2892 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002893 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002894 }
2895 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002896};
2897} // end anonymous namespace
2898
Richard Smithc49bd112011-10-28 17:51:58 +00002899/// Evaluate an expression as an lvalue. This can be legitimately called on
2900/// expressions which are not glvalues, in a few cases:
2901/// * function designators in C,
2902/// * "extern void" objects,
2903/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002904static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002905 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2906 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2907 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002908 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002909}
2910
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002911bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002912 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2913 return Success(FD);
2914 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002915 return VisitVarDecl(E, VD);
2916 return Error(E);
2917}
Richard Smith436c8892011-10-24 23:14:33 +00002918
Richard Smithc49bd112011-10-28 17:51:58 +00002919bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002920 if (!VD->getType()->isReferenceType()) {
2921 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002922 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002923 return true;
2924 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002925 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002926 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002927
Richard Smith1aa0be82012-03-03 22:46:17 +00002928 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002929 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2930 return false;
2931 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002932}
2933
Richard Smithbd552ef2011-10-31 05:52:43 +00002934bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2935 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002936 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002937 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002938 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2939
Richard Smith83587db2012-02-15 02:18:13 +00002940 Result.set(E, Info.CurrentCall->Index);
2941 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2942 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002943 }
2944
2945 // Materialization of an lvalue temporary occurs when we need to force a copy
2946 // (for instance, if it's a bitfield).
2947 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2948 if (!Visit(E->GetTemporaryExpr()))
2949 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002950 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002951 Info.CurrentCall->Temporaries[E]))
2952 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002953 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002954 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002955}
2956
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002957bool
2958LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002959 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2960 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2961 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002962 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002963}
2964
Richard Smith47d21452011-12-27 12:18:28 +00002965bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2966 if (E->isTypeOperand())
2967 return Success(E);
2968 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2969 if (RD && RD->isPolymorphic()) {
Richard Smithd75fb492012-03-15 00:41:48 +00002970 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith47d21452011-12-27 12:18:28 +00002971 << E->getExprOperand()->getType()
2972 << E->getExprOperand()->getSourceRange();
2973 return false;
2974 }
2975 return Success(E);
2976}
2977
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002978bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002979 // Handle static data members.
2980 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2981 VisitIgnoredValue(E->getBase());
2982 return VisitVarDecl(E, VD);
2983 }
2984
Richard Smithd0dccea2011-10-28 22:34:42 +00002985 // Handle static member functions.
2986 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2987 if (MD->isStatic()) {
2988 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002989 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002990 }
2991 }
2992
Richard Smith180f4792011-11-10 06:34:14 +00002993 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002994 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002995}
2996
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002997bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002998 // FIXME: Deal with vectors as array subscript bases.
2999 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003000 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003001
Anders Carlsson3068d112008-11-16 19:01:22 +00003002 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003003 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003004
Anders Carlsson3068d112008-11-16 19:01:22 +00003005 APSInt Index;
3006 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003007 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003008 int64_t IndexValue
3009 = Index.isSigned() ? Index.getSExtValue()
3010 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003011
Richard Smithb4e85ed2012-01-06 16:39:00 +00003012 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003013}
Eli Friedman4efaa272008-11-12 09:44:48 +00003014
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003015bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003016 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003017}
3018
Richard Smith86024012012-02-18 22:04:06 +00003019bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3020 if (!Visit(E->getSubExpr()))
3021 return false;
3022 // __real is a no-op on scalar lvalues.
3023 if (E->getSubExpr()->getType()->isAnyComplexType())
3024 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3025 return true;
3026}
3027
3028bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3029 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3030 "lvalue __imag__ on scalar?");
3031 if (!Visit(E->getSubExpr()))
3032 return false;
3033 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3034 return true;
3035}
3036
Eli Friedman4efaa272008-11-12 09:44:48 +00003037//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003038// Pointer Evaluation
3039//===----------------------------------------------------------------------===//
3040
Anders Carlssonc754aa62008-07-08 05:13:58 +00003041namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003042class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003043 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003044 LValue &Result;
3045
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003046 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003047 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003048 return true;
3049 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003050public:
Mike Stump1eb44332009-09-09 15:08:12 +00003051
John McCallefdb83e2010-05-07 21:00:08 +00003052 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003053 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003054
Richard Smith1aa0be82012-03-03 22:46:17 +00003055 bool Success(const APValue &V, const Expr *E) {
3056 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003057 return true;
3058 }
Richard Smith51201882011-12-30 21:15:51 +00003059 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003060 return Success((Expr*)0);
3061 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003062
John McCallefdb83e2010-05-07 21:00:08 +00003063 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003064 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003065 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003066 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003067 { return Success(E); }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003068 bool VisitObjCNumericLiteral(const ObjCNumericLiteral *E)
3069 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003070 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003071 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003072 bool VisitCallExpr(const CallExpr *E);
3073 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003074 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003075 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003076 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003077 }
Richard Smith180f4792011-11-10 06:34:14 +00003078 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3079 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003080 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003081 Result = *Info.CurrentCall->This;
3082 return true;
3083 }
John McCall56ca35d2011-02-17 10:25:35 +00003084
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003085 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003086};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003087} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003088
John McCallefdb83e2010-05-07 21:00:08 +00003089static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003090 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003091 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003092}
3093
John McCallefdb83e2010-05-07 21:00:08 +00003094bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003095 if (E->getOpcode() != BO_Add &&
3096 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003097 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003098
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003099 const Expr *PExp = E->getLHS();
3100 const Expr *IExp = E->getRHS();
3101 if (IExp->getType()->isPointerType())
3102 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003103
Richard Smith745f5142012-01-27 01:14:48 +00003104 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3105 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003106 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003107
John McCallefdb83e2010-05-07 21:00:08 +00003108 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003109 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003110 return false;
3111 int64_t AdditionalOffset
3112 = Offset.isSigned() ? Offset.getSExtValue()
3113 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003114 if (E->getOpcode() == BO_Sub)
3115 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003116
Richard Smith180f4792011-11-10 06:34:14 +00003117 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003118 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3119 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003120}
Eli Friedman4efaa272008-11-12 09:44:48 +00003121
John McCallefdb83e2010-05-07 21:00:08 +00003122bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3123 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003124}
Mike Stump1eb44332009-09-09 15:08:12 +00003125
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003126bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3127 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003128
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003129 switch (E->getCastKind()) {
3130 default:
3131 break;
3132
John McCall2de56d12010-08-25 11:45:40 +00003133 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003134 case CK_CPointerToObjCPointerCast:
3135 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003136 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003137 if (!Visit(SubExpr))
3138 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003139 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3140 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3141 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003142 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003143 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003144 if (SubExpr->getType()->isVoidPointerType())
3145 CCEDiag(E, diag::note_constexpr_invalid_cast)
3146 << 3 << SubExpr->getType();
3147 else
3148 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3149 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003150 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003151
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003152 case CK_DerivedToBase:
3153 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003154 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003155 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003156 if (!Result.Base && Result.Offset.isZero())
3157 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003158
Richard Smith180f4792011-11-10 06:34:14 +00003159 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003160 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003161 QualType Type =
3162 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003163
Richard Smith180f4792011-11-10 06:34:14 +00003164 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003165 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003166 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3167 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003168 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003169 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003170 }
3171
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003172 return true;
3173 }
3174
Richard Smithe24f5fc2011-11-17 22:56:20 +00003175 case CK_BaseToDerived:
3176 if (!Visit(E->getSubExpr()))
3177 return false;
3178 if (!Result.Base && Result.Offset.isZero())
3179 return true;
3180 return HandleBaseToDerivedCast(Info, E, Result);
3181
Richard Smith47a1eed2011-10-29 20:57:55 +00003182 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003183 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003184
John McCall2de56d12010-08-25 11:45:40 +00003185 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003186 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3187
Richard Smith1aa0be82012-03-03 22:46:17 +00003188 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003189 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003190 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003191
John McCallefdb83e2010-05-07 21:00:08 +00003192 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003193 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3194 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003195 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003196 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003197 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003198 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003199 return true;
3200 } else {
3201 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003202 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003203 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003204 }
3205 }
John McCall2de56d12010-08-25 11:45:40 +00003206 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003207 if (SubExpr->isGLValue()) {
3208 if (!EvaluateLValue(SubExpr, Result, Info))
3209 return false;
3210 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003211 Result.set(SubExpr, Info.CurrentCall->Index);
3212 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3213 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003214 return false;
3215 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003216 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003217 if (const ConstantArrayType *CAT
3218 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3219 Result.addArray(Info, E, CAT);
3220 else
3221 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003222 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003223
John McCall2de56d12010-08-25 11:45:40 +00003224 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003225 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003226 }
3227
Richard Smithc49bd112011-10-28 17:51:58 +00003228 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003229}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003230
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003231bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003232 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003233 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003234
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003235 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003236}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003237
3238//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003239// Member Pointer Evaluation
3240//===----------------------------------------------------------------------===//
3241
3242namespace {
3243class MemberPointerExprEvaluator
3244 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3245 MemberPtr &Result;
3246
3247 bool Success(const ValueDecl *D) {
3248 Result = MemberPtr(D);
3249 return true;
3250 }
3251public:
3252
3253 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3254 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3255
Richard Smith1aa0be82012-03-03 22:46:17 +00003256 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003257 Result.setFrom(V);
3258 return true;
3259 }
Richard Smith51201882011-12-30 21:15:51 +00003260 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003261 return Success((const ValueDecl*)0);
3262 }
3263
3264 bool VisitCastExpr(const CastExpr *E);
3265 bool VisitUnaryAddrOf(const UnaryOperator *E);
3266};
3267} // end anonymous namespace
3268
3269static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3270 EvalInfo &Info) {
3271 assert(E->isRValue() && E->getType()->isMemberPointerType());
3272 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3273}
3274
3275bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3276 switch (E->getCastKind()) {
3277 default:
3278 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3279
3280 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003281 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003282
3283 case CK_BaseToDerivedMemberPointer: {
3284 if (!Visit(E->getSubExpr()))
3285 return false;
3286 if (E->path_empty())
3287 return true;
3288 // Base-to-derived member pointer casts store the path in derived-to-base
3289 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3290 // the wrong end of the derived->base arc, so stagger the path by one class.
3291 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3292 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3293 PathI != PathE; ++PathI) {
3294 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3295 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3296 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003297 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003298 }
3299 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3300 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003301 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003302 return true;
3303 }
3304
3305 case CK_DerivedToBaseMemberPointer:
3306 if (!Visit(E->getSubExpr()))
3307 return false;
3308 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3309 PathE = E->path_end(); PathI != PathE; ++PathI) {
3310 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3311 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3312 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003313 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003314 }
3315 return true;
3316 }
3317}
3318
3319bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3320 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3321 // member can be formed.
3322 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3323}
3324
3325//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003326// Record Evaluation
3327//===----------------------------------------------------------------------===//
3328
3329namespace {
3330 class RecordExprEvaluator
3331 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3332 const LValue &This;
3333 APValue &Result;
3334 public:
3335
3336 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3337 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3338
Richard Smith1aa0be82012-03-03 22:46:17 +00003339 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003340 Result = V;
3341 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003342 }
Richard Smith51201882011-12-30 21:15:51 +00003343 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003344
Richard Smith59efe262011-11-11 04:05:33 +00003345 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003346 bool VisitInitListExpr(const InitListExpr *E);
3347 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3348 };
3349}
3350
Richard Smith51201882011-12-30 21:15:51 +00003351/// Perform zero-initialization on an object of non-union class type.
3352/// C++11 [dcl.init]p5:
3353/// To zero-initialize an object or reference of type T means:
3354/// [...]
3355/// -- if T is a (possibly cv-qualified) non-union class type,
3356/// each non-static data member and each base-class subobject is
3357/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003358static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3359 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003360 const LValue &This, APValue &Result) {
3361 assert(!RD->isUnion() && "Expected non-union class type");
3362 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3363 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3364 std::distance(RD->field_begin(), RD->field_end()));
3365
3366 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3367
3368 if (CD) {
3369 unsigned Index = 0;
3370 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003371 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003372 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3373 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003374 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3375 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003376 Result.getStructBase(Index)))
3377 return false;
3378 }
3379 }
3380
Richard Smithb4e85ed2012-01-06 16:39:00 +00003381 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3382 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003383 // -- if T is a reference type, no initialization is performed.
3384 if ((*I)->getType()->isReferenceType())
3385 continue;
3386
3387 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003388 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003389
3390 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003391 if (!EvaluateInPlace(
Richard Smith51201882011-12-30 21:15:51 +00003392 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3393 return false;
3394 }
3395
3396 return true;
3397}
3398
3399bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3400 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3401 if (RD->isUnion()) {
3402 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3403 // object's first non-static named data member is zero-initialized
3404 RecordDecl::field_iterator I = RD->field_begin();
3405 if (I == RD->field_end()) {
3406 Result = APValue((const FieldDecl*)0);
3407 return true;
3408 }
3409
3410 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003411 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003412 Result = APValue(*I);
3413 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003414 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003415 }
3416
Richard Smithce582fe2012-02-17 00:44:16 +00003417 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithd75fb492012-03-15 00:41:48 +00003418 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003419 return false;
3420 }
3421
Richard Smithb4e85ed2012-01-06 16:39:00 +00003422 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003423}
3424
Richard Smith59efe262011-11-11 04:05:33 +00003425bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3426 switch (E->getCastKind()) {
3427 default:
3428 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3429
3430 case CK_ConstructorConversion:
3431 return Visit(E->getSubExpr());
3432
3433 case CK_DerivedToBase:
3434 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003435 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003436 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003437 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003438 if (!DerivedObject.isStruct())
3439 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003440
3441 // Derived-to-base rvalue conversion: just slice off the derived part.
3442 APValue *Value = &DerivedObject;
3443 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3444 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3445 PathE = E->path_end(); PathI != PathE; ++PathI) {
3446 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3447 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3448 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3449 RD = Base;
3450 }
3451 Result = *Value;
3452 return true;
3453 }
3454 }
3455}
3456
Richard Smith180f4792011-11-10 06:34:14 +00003457bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003458 // Cannot constant-evaluate std::initializer_list inits.
3459 if (E->initializesStdInitializerList())
3460 return false;
3461
Richard Smith180f4792011-11-10 06:34:14 +00003462 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3463 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3464
3465 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003466 const FieldDecl *Field = E->getInitializedFieldInUnion();
3467 Result = APValue(Field);
3468 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003469 return true;
Richard Smithec789162012-01-12 18:54:33 +00003470
3471 // If the initializer list for a union does not contain any elements, the
3472 // first element of the union is value-initialized.
3473 ImplicitValueInitExpr VIE(Field->getType());
3474 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3475
Richard Smith180f4792011-11-10 06:34:14 +00003476 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003477 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith83587db2012-02-15 02:18:13 +00003478 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003479 }
3480
3481 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3482 "initializer list for class with base classes");
3483 Result = APValue(APValue::UninitStruct(), 0,
3484 std::distance(RD->field_begin(), RD->field_end()));
3485 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003486 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003487 for (RecordDecl::field_iterator Field = RD->field_begin(),
3488 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3489 // Anonymous bit-fields are not considered members of the class for
3490 // purposes of aggregate initialization.
3491 if (Field->isUnnamedBitfield())
3492 continue;
3493
3494 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003495
Richard Smith745f5142012-01-27 01:14:48 +00003496 bool HaveInit = ElementNo < E->getNumInits();
3497
3498 // FIXME: Diagnostics here should point to the end of the initializer
3499 // list, not the start.
3500 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3501 *Field, &Layout);
3502
3503 // Perform an implicit value-initialization for members beyond the end of
3504 // the initializer list.
3505 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3506
Richard Smith83587db2012-02-15 02:18:13 +00003507 if (!EvaluateInPlace(
Richard Smith745f5142012-01-27 01:14:48 +00003508 Result.getStructField((*Field)->getFieldIndex()),
3509 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3510 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003511 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003512 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003513 }
3514 }
3515
Richard Smith745f5142012-01-27 01:14:48 +00003516 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003517}
3518
3519bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3520 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003521 bool ZeroInit = E->requiresZeroInitialization();
3522 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003523 // If we've already performed zero-initialization, we're already done.
3524 if (!Result.isUninit())
3525 return true;
3526
Richard Smith51201882011-12-30 21:15:51 +00003527 if (ZeroInit)
3528 return ZeroInitialization(E);
3529
Richard Smith61802452011-12-22 02:22:31 +00003530 const CXXRecordDecl *RD = FD->getParent();
3531 if (RD->isUnion())
3532 Result = APValue((FieldDecl*)0);
3533 else
3534 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3535 std::distance(RD->field_begin(), RD->field_end()));
3536 return true;
3537 }
3538
Richard Smith180f4792011-11-10 06:34:14 +00003539 const FunctionDecl *Definition = 0;
3540 FD->getBody(Definition);
3541
Richard Smithc1c5f272011-12-13 06:39:58 +00003542 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3543 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003544
Richard Smith610a60c2012-01-10 04:32:03 +00003545 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003546 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003547 if (const MaterializeTemporaryExpr *ME
3548 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3549 return Visit(ME->GetTemporaryExpr());
3550
Richard Smith51201882011-12-30 21:15:51 +00003551 if (ZeroInit && !ZeroInitialization(E))
3552 return false;
3553
Richard Smith180f4792011-11-10 06:34:14 +00003554 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003555 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003556 cast<CXXConstructorDecl>(Definition), Info,
3557 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003558}
3559
3560static bool EvaluateRecord(const Expr *E, const LValue &This,
3561 APValue &Result, EvalInfo &Info) {
3562 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003563 "can't evaluate expression as a record rvalue");
3564 return RecordExprEvaluator(Info, This, Result).Visit(E);
3565}
3566
3567//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003568// Temporary Evaluation
3569//
3570// Temporaries are represented in the AST as rvalues, but generally behave like
3571// lvalues. The full-object of which the temporary is a subobject is implicitly
3572// materialized so that a reference can bind to it.
3573//===----------------------------------------------------------------------===//
3574namespace {
3575class TemporaryExprEvaluator
3576 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3577public:
3578 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3579 LValueExprEvaluatorBaseTy(Info, Result) {}
3580
3581 /// Visit an expression which constructs the value of this temporary.
3582 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003583 Result.set(E, Info.CurrentCall->Index);
3584 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003585 }
3586
3587 bool VisitCastExpr(const CastExpr *E) {
3588 switch (E->getCastKind()) {
3589 default:
3590 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3591
3592 case CK_ConstructorConversion:
3593 return VisitConstructExpr(E->getSubExpr());
3594 }
3595 }
3596 bool VisitInitListExpr(const InitListExpr *E) {
3597 return VisitConstructExpr(E);
3598 }
3599 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3600 return VisitConstructExpr(E);
3601 }
3602 bool VisitCallExpr(const CallExpr *E) {
3603 return VisitConstructExpr(E);
3604 }
3605};
3606} // end anonymous namespace
3607
3608/// Evaluate an expression of record type as a temporary.
3609static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003610 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003611 return TemporaryExprEvaluator(Info, Result).Visit(E);
3612}
3613
3614//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003615// Vector Evaluation
3616//===----------------------------------------------------------------------===//
3617
3618namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003619 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003620 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3621 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003622 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003623
Richard Smith07fc6572011-10-22 21:10:00 +00003624 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3625 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003626
Richard Smith07fc6572011-10-22 21:10:00 +00003627 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3628 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3629 // FIXME: remove this APValue copy.
3630 Result = APValue(V.data(), V.size());
3631 return true;
3632 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003633 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003634 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003635 Result = V;
3636 return true;
3637 }
Richard Smith51201882011-12-30 21:15:51 +00003638 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003639
Richard Smith07fc6572011-10-22 21:10:00 +00003640 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003641 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003642 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003643 bool VisitInitListExpr(const InitListExpr *E);
3644 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003645 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003646 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003647 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003648 };
3649} // end anonymous namespace
3650
3651static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003652 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003653 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003654}
3655
Richard Smith07fc6572011-10-22 21:10:00 +00003656bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3657 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003658 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003659
Richard Smithd62ca372011-12-06 22:44:34 +00003660 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003661 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003662
Eli Friedman46a52322011-03-25 00:43:55 +00003663 switch (E->getCastKind()) {
3664 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003665 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003666 if (SETy->isIntegerType()) {
3667 APSInt IntResult;
3668 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003669 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003670 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003671 } else if (SETy->isRealFloatingType()) {
3672 APFloat F(0.0);
3673 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003674 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003675 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003676 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003677 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003678 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003679
3680 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003681 SmallVector<APValue, 4> Elts(NElts, Val);
3682 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003683 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003684 case CK_BitCast: {
3685 // Evaluate the operand into an APInt we can extract from.
3686 llvm::APInt SValInt;
3687 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3688 return false;
3689 // Extract the elements
3690 QualType EltTy = VTy->getElementType();
3691 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3692 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3693 SmallVector<APValue, 4> Elts;
3694 if (EltTy->isRealFloatingType()) {
3695 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3696 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3697 unsigned FloatEltSize = EltSize;
3698 if (&Sem == &APFloat::x87DoubleExtended)
3699 FloatEltSize = 80;
3700 for (unsigned i = 0; i < NElts; i++) {
3701 llvm::APInt Elt;
3702 if (BigEndian)
3703 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3704 else
3705 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3706 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3707 }
3708 } else if (EltTy->isIntegerType()) {
3709 for (unsigned i = 0; i < NElts; i++) {
3710 llvm::APInt Elt;
3711 if (BigEndian)
3712 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3713 else
3714 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3715 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3716 }
3717 } else {
3718 return Error(E);
3719 }
3720 return Success(Elts, E);
3721 }
Eli Friedman46a52322011-03-25 00:43:55 +00003722 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003723 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003724 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003725}
3726
Richard Smith07fc6572011-10-22 21:10:00 +00003727bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003728VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003729 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003730 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003731 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003732
Nate Begeman59b5da62009-01-18 03:20:47 +00003733 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003734 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003735
Eli Friedman3edd5a92012-01-03 23:24:20 +00003736 // The number of initializers can be less than the number of
3737 // vector elements. For OpenCL, this can be due to nested vector
3738 // initialization. For GCC compatibility, missing trailing elements
3739 // should be initialized with zeroes.
3740 unsigned CountInits = 0, CountElts = 0;
3741 while (CountElts < NumElements) {
3742 // Handle nested vector initialization.
3743 if (CountInits < NumInits
3744 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3745 APValue v;
3746 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3747 return Error(E);
3748 unsigned vlen = v.getVectorLength();
3749 for (unsigned j = 0; j < vlen; j++)
3750 Elements.push_back(v.getVectorElt(j));
3751 CountElts += vlen;
3752 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003753 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003754 if (CountInits < NumInits) {
3755 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003756 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003757 } else // trailing integer zero.
3758 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3759 Elements.push_back(APValue(sInt));
3760 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003761 } else {
3762 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003763 if (CountInits < NumInits) {
3764 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003765 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003766 } else // trailing float zero.
3767 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3768 Elements.push_back(APValue(f));
3769 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003770 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003771 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003772 }
Richard Smith07fc6572011-10-22 21:10:00 +00003773 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003774}
3775
Richard Smith07fc6572011-10-22 21:10:00 +00003776bool
Richard Smith51201882011-12-30 21:15:51 +00003777VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003778 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003779 QualType EltTy = VT->getElementType();
3780 APValue ZeroElement;
3781 if (EltTy->isIntegerType())
3782 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3783 else
3784 ZeroElement =
3785 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3786
Chris Lattner5f9e2722011-07-23 10:55:15 +00003787 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003788 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003789}
3790
Richard Smith07fc6572011-10-22 21:10:00 +00003791bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003792 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003793 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003794}
3795
Nate Begeman59b5da62009-01-18 03:20:47 +00003796//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003797// Array Evaluation
3798//===----------------------------------------------------------------------===//
3799
3800namespace {
3801 class ArrayExprEvaluator
3802 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003803 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003804 APValue &Result;
3805 public:
3806
Richard Smith180f4792011-11-10 06:34:14 +00003807 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3808 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003809
3810 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003811 assert((V.isArray() || V.isLValue()) &&
3812 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003813 Result = V;
3814 return true;
3815 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003816
Richard Smith51201882011-12-30 21:15:51 +00003817 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003818 const ConstantArrayType *CAT =
3819 Info.Ctx.getAsConstantArrayType(E->getType());
3820 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003821 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003822
3823 Result = APValue(APValue::UninitArray(), 0,
3824 CAT->getSize().getZExtValue());
3825 if (!Result.hasArrayFiller()) return true;
3826
Richard Smith51201882011-12-30 21:15:51 +00003827 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003828 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003829 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003830 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003831 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003832 }
3833
Richard Smithcc5d4f62011-11-07 09:22:26 +00003834 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003835 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003836 };
3837} // end anonymous namespace
3838
Richard Smith180f4792011-11-10 06:34:14 +00003839static bool EvaluateArray(const Expr *E, const LValue &This,
3840 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003841 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003842 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003843}
3844
3845bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3846 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3847 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003848 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003849
Richard Smith974c5f92011-12-22 01:07:19 +00003850 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3851 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003852 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003853 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3854 LValue LV;
3855 if (!EvaluateLValue(E->getInit(0), LV, Info))
3856 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003857 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003858 LV.moveInto(Val);
3859 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003860 }
3861
Richard Smith745f5142012-01-27 01:14:48 +00003862 bool Success = true;
3863
Richard Smithcc5d4f62011-11-07 09:22:26 +00003864 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3865 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003866 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003867 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003868 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003869 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003870 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003871 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3872 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003873 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3874 CAT->getElementType(), 1)) {
3875 if (!Info.keepEvaluatingAfterFailure())
3876 return false;
3877 Success = false;
3878 }
Richard Smith180f4792011-11-10 06:34:14 +00003879 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003880
Richard Smith745f5142012-01-27 01:14:48 +00003881 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003882 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003883 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3884 // but sometimes does:
3885 // struct S { constexpr S() : p(&p) {} void *p; };
3886 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003887 return EvaluateInPlace(Result.getArrayFiller(), Info,
3888 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003889}
3890
Richard Smithe24f5fc2011-11-17 22:56:20 +00003891bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3892 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3893 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003894 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003895
Richard Smithec789162012-01-12 18:54:33 +00003896 bool HadZeroInit = !Result.isUninit();
3897 if (!HadZeroInit)
3898 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003899 if (!Result.hasArrayFiller())
3900 return true;
3901
3902 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003903
Richard Smith51201882011-12-30 21:15:51 +00003904 bool ZeroInit = E->requiresZeroInitialization();
3905 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003906 if (HadZeroInit)
3907 return true;
3908
Richard Smith51201882011-12-30 21:15:51 +00003909 if (ZeroInit) {
3910 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003911 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003912 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003913 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003914 }
3915
Richard Smith61802452011-12-22 02:22:31 +00003916 const CXXRecordDecl *RD = FD->getParent();
3917 if (RD->isUnion())
3918 Result.getArrayFiller() = APValue((FieldDecl*)0);
3919 else
3920 Result.getArrayFiller() =
3921 APValue(APValue::UninitStruct(), RD->getNumBases(),
3922 std::distance(RD->field_begin(), RD->field_end()));
3923 return true;
3924 }
3925
Richard Smithe24f5fc2011-11-17 22:56:20 +00003926 const FunctionDecl *Definition = 0;
3927 FD->getBody(Definition);
3928
Richard Smithc1c5f272011-12-13 06:39:58 +00003929 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3930 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003931
3932 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3933 // but sometimes does:
3934 // struct S { constexpr S() : p(&p) {} void *p; };
3935 // S s[10];
3936 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003937 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003938
Richard Smithec789162012-01-12 18:54:33 +00003939 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003940 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003941 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003942 return false;
3943 }
3944
Richard Smithe24f5fc2011-11-17 22:56:20 +00003945 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003946 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003947 cast<CXXConstructorDecl>(Definition),
3948 Info, Result.getArrayFiller());
3949}
3950
Richard Smithcc5d4f62011-11-07 09:22:26 +00003951//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003952// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003953//
3954// As a GNU extension, we support casting pointers to sufficiently-wide integer
3955// types and back in constant folding. Integer values are thus represented
3956// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003957//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003958
3959namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003960class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003961 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003962 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003963public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003964 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003965 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003966
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003967 bool Success(const llvm::APSInt &SI, const Expr *E) {
3968 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003969 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003970 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003971 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003972 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003973 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003974 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003975 return true;
3976 }
3977
Daniel Dunbar131eb432009-02-19 09:06:44 +00003978 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003979 assert(E->getType()->isIntegralOrEnumerationType() &&
3980 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003981 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003982 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003983 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003984 Result.getInt().setIsUnsigned(
3985 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003986 return true;
3987 }
3988
3989 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003990 assert(E->getType()->isIntegralOrEnumerationType() &&
3991 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003992 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003993 return true;
3994 }
3995
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003996 bool Success(CharUnits Size, const Expr *E) {
3997 return Success(Size.getQuantity(), E);
3998 }
3999
Richard Smith1aa0be82012-03-03 22:46:17 +00004000 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00004001 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00004002 Result = V;
4003 return true;
4004 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004005 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00004006 }
Mike Stump1eb44332009-09-09 15:08:12 +00004007
Richard Smith51201882011-12-30 21:15:51 +00004008 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00004009
Argyrios Kyrtzidisc1b66e62012-02-27 23:18:37 +00004010 // FIXME: See EvalInfo::IntExprEvaluatorDepth.
4011 bool Visit(const Expr *E) {
4012 SaveAndRestore<unsigned> Depth(Info.IntExprEvaluatorDepth,
4013 Info.IntExprEvaluatorDepth+1);
4014 const unsigned MaxDepth = 512;
4015 if (Depth.get() > MaxDepth) {
4016 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
4017 diag::err_intexpr_depth_limit_exceeded);
4018 return false;
4019 }
4020
4021 return ExprEvaluatorBaseTy::Visit(E);
4022 }
4023
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004024 //===--------------------------------------------------------------------===//
4025 // Visitor Methods
4026 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004027
Chris Lattner4c4867e2008-07-12 00:38:25 +00004028 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004029 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004030 }
4031 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004032 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004033 }
Eli Friedman04309752009-11-24 05:28:59 +00004034
4035 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4036 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004037 if (CheckReferencedDecl(E, E->getDecl()))
4038 return true;
4039
4040 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004041 }
4042 bool VisitMemberExpr(const MemberExpr *E) {
4043 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004044 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004045 return true;
4046 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004047
4048 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004049 }
4050
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004051 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004052 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004053 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004054 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004055
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004056 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004057 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004058
Anders Carlsson3068d112008-11-16 19:01:22 +00004059 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004060 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004061 }
Mike Stump1eb44332009-09-09 15:08:12 +00004062
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004063 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4064 return Success(E->getValue(), E);
4065 }
4066
Richard Smithf10d9172011-10-11 21:43:33 +00004067 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004068 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004069 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004070 }
4071
Sebastian Redl64b45f72009-01-05 20:52:13 +00004072 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004073 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004074 }
4075
Francois Pichet6ad6f282010-12-07 00:08:36 +00004076 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4077 return Success(E->getValue(), E);
4078 }
4079
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004080 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4081 return Success(E->getValue(), E);
4082 }
4083
John Wiegley21ff2e52011-04-28 00:16:57 +00004084 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4085 return Success(E->getValue(), E);
4086 }
4087
John Wiegley55262202011-04-25 06:54:41 +00004088 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4089 return Success(E->getValue(), E);
4090 }
4091
Eli Friedman722c7172009-02-28 03:59:05 +00004092 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004093 bool VisitUnaryImag(const UnaryOperator *E);
4094
Sebastian Redl295995c2010-09-10 20:55:47 +00004095 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004096 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004097
Chris Lattnerfcee0012008-07-11 21:24:13 +00004098private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004099 CharUnits GetAlignOfExpr(const Expr *E);
4100 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004101 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004102 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004103 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004104};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004105} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004106
Richard Smithc49bd112011-10-28 17:51:58 +00004107/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4108/// produce either the integer value or a pointer.
4109///
4110/// GCC has a heinous extension which folds casts between pointer types and
4111/// pointer-sized integral types. We support this by allowing the evaluation of
4112/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4113/// Some simple arithmetic on such values is supported (they are treated much
4114/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004115static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004116 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004117 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004118 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004119}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004120
Richard Smithf48fdb02011-12-09 22:58:01 +00004121static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004122 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004123 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004124 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004125 if (!Val.isInt()) {
4126 // FIXME: It would be better to produce the diagnostic for casting
4127 // a pointer to an integer.
Richard Smithd75fb492012-03-15 00:41:48 +00004128 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004129 return false;
4130 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004131 Result = Val.getInt();
4132 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004133}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004134
Richard Smithf48fdb02011-12-09 22:58:01 +00004135/// Check whether the given declaration can be directly converted to an integral
4136/// rvalue. If not, no diagnostic is produced; there are other things we can
4137/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004138bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004139 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004140 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004141 // Check for signedness/width mismatches between E type and ECD value.
4142 bool SameSign = (ECD->getInitVal().isSigned()
4143 == E->getType()->isSignedIntegerOrEnumerationType());
4144 bool SameWidth = (ECD->getInitVal().getBitWidth()
4145 == Info.Ctx.getIntWidth(E->getType()));
4146 if (SameSign && SameWidth)
4147 return Success(ECD->getInitVal(), E);
4148 else {
4149 // Get rid of mismatch (otherwise Success assertions will fail)
4150 // by computing a new value matching the type of E.
4151 llvm::APSInt Val = ECD->getInitVal();
4152 if (!SameSign)
4153 Val.setIsSigned(!ECD->getInitVal().isSigned());
4154 if (!SameWidth)
4155 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4156 return Success(Val, E);
4157 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004158 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004159 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004160}
4161
Chris Lattnera4d55d82008-10-06 06:40:35 +00004162/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4163/// as GCC.
4164static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4165 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004166 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004167 enum gcc_type_class {
4168 no_type_class = -1,
4169 void_type_class, integer_type_class, char_type_class,
4170 enumeral_type_class, boolean_type_class,
4171 pointer_type_class, reference_type_class, offset_type_class,
4172 real_type_class, complex_type_class,
4173 function_type_class, method_type_class,
4174 record_type_class, union_type_class,
4175 array_type_class, string_type_class,
4176 lang_type_class
4177 };
Mike Stump1eb44332009-09-09 15:08:12 +00004178
4179 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004180 // ideal, however it is what gcc does.
4181 if (E->getNumArgs() == 0)
4182 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004183
Chris Lattnera4d55d82008-10-06 06:40:35 +00004184 QualType ArgTy = E->getArg(0)->getType();
4185 if (ArgTy->isVoidType())
4186 return void_type_class;
4187 else if (ArgTy->isEnumeralType())
4188 return enumeral_type_class;
4189 else if (ArgTy->isBooleanType())
4190 return boolean_type_class;
4191 else if (ArgTy->isCharType())
4192 return string_type_class; // gcc doesn't appear to use char_type_class
4193 else if (ArgTy->isIntegerType())
4194 return integer_type_class;
4195 else if (ArgTy->isPointerType())
4196 return pointer_type_class;
4197 else if (ArgTy->isReferenceType())
4198 return reference_type_class;
4199 else if (ArgTy->isRealType())
4200 return real_type_class;
4201 else if (ArgTy->isComplexType())
4202 return complex_type_class;
4203 else if (ArgTy->isFunctionType())
4204 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004205 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004206 return record_type_class;
4207 else if (ArgTy->isUnionType())
4208 return union_type_class;
4209 else if (ArgTy->isArrayType())
4210 return array_type_class;
4211 else if (ArgTy->isUnionType())
4212 return union_type_class;
4213 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004214 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004215}
4216
Richard Smith80d4b552011-12-28 19:48:30 +00004217/// EvaluateBuiltinConstantPForLValue - Determine the result of
4218/// __builtin_constant_p when applied to the given lvalue.
4219///
4220/// An lvalue is only "constant" if it is a pointer or reference to the first
4221/// character of a string literal.
4222template<typename LValue>
4223static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004224 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004225 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4226}
4227
4228/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4229/// GCC as we can manage.
4230static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4231 QualType ArgType = Arg->getType();
4232
4233 // __builtin_constant_p always has one operand. The rules which gcc follows
4234 // are not precisely documented, but are as follows:
4235 //
4236 // - If the operand is of integral, floating, complex or enumeration type,
4237 // and can be folded to a known value of that type, it returns 1.
4238 // - If the operand and can be folded to a pointer to the first character
4239 // of a string literal (or such a pointer cast to an integral type), it
4240 // returns 1.
4241 //
4242 // Otherwise, it returns 0.
4243 //
4244 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4245 // its support for this does not currently work.
4246 if (ArgType->isIntegralOrEnumerationType()) {
4247 Expr::EvalResult Result;
4248 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4249 return false;
4250
4251 APValue &V = Result.Val;
4252 if (V.getKind() == APValue::Int)
4253 return true;
4254
4255 return EvaluateBuiltinConstantPForLValue(V);
4256 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4257 return Arg->isEvaluatable(Ctx);
4258 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4259 LValue LV;
4260 Expr::EvalStatus Status;
4261 EvalInfo Info(Ctx, Status);
4262 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4263 : EvaluatePointer(Arg, LV, Info)) &&
4264 !Status.HasSideEffects)
4265 return EvaluateBuiltinConstantPForLValue(LV);
4266 }
4267
4268 // Anything else isn't considered to be sufficiently constant.
4269 return false;
4270}
4271
John McCall42c8f872010-05-10 23:27:23 +00004272/// Retrieves the "underlying object type" of the given expression,
4273/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004274QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4275 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4276 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004277 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004278 } else if (const Expr *E = B.get<const Expr*>()) {
4279 if (isa<CompoundLiteralExpr>(E))
4280 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004281 }
4282
4283 return QualType();
4284}
4285
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004286bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004287 // TODO: Perhaps we should let LLVM lower this?
4288 LValue Base;
4289 if (!EvaluatePointer(E->getArg(0), Base, Info))
4290 return false;
4291
4292 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004293 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004294
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004295 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004296 if (T.isNull() ||
4297 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004298 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004299 T->isVariablyModifiedType() ||
4300 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004301 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004302
4303 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4304 CharUnits Offset = Base.getLValueOffset();
4305
4306 if (!Offset.isNegative() && Offset <= Size)
4307 Size -= Offset;
4308 else
4309 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004310 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004311}
4312
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004313bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004314 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004315 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004316 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004317
4318 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004319 if (TryEvaluateBuiltinObjectSize(E))
4320 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004321
Eric Christopherb2aaf512010-01-19 22:58:35 +00004322 // If evaluating the argument has side-effects we can't determine
4323 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004324 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004325 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004326 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004327 return Success(0, E);
4328 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004329
Richard Smithf48fdb02011-12-09 22:58:01 +00004330 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004331 }
4332
Chris Lattner019f4e82008-10-06 05:28:25 +00004333 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004334 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004335
Richard Smith80d4b552011-12-28 19:48:30 +00004336 case Builtin::BI__builtin_constant_p:
4337 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004338
Chris Lattner21fb98e2009-09-23 06:06:36 +00004339 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004340 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004341 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004342 return Success(Operand, E);
4343 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004344
4345 case Builtin::BI__builtin_expect:
4346 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004347
Douglas Gregor5726d402010-09-10 06:27:15 +00004348 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004349 // A call to strlen is not a constant expression.
4350 if (Info.getLangOpts().CPlusPlus0x)
Richard Smithd75fb492012-03-15 00:41:48 +00004351 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004352 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4353 else
Richard Smithd75fb492012-03-15 00:41:48 +00004354 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004355 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004356 case Builtin::BI__builtin_strlen:
4357 // As an extension, we support strlen() and __builtin_strlen() as constant
4358 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004359 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004360 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4361 // The string literal may have embedded null characters. Find the first
4362 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004363 StringRef Str = S->getString();
4364 StringRef::size_type Pos = Str.find(0);
4365 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004366 Str = Str.substr(0, Pos);
4367
4368 return Success(Str.size(), E);
4369 }
4370
Richard Smithf48fdb02011-12-09 22:58:01 +00004371 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004372
4373 case Builtin::BI__atomic_is_lock_free: {
4374 APSInt SizeVal;
4375 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4376 return false;
4377
4378 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4379 // of two less than the maximum inline atomic width, we know it is
4380 // lock-free. If the size isn't a power of two, or greater than the
4381 // maximum alignment where we promote atomics, we know it is not lock-free
4382 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4383 // the answer can only be determined at runtime; for example, 16-byte
4384 // atomics have lock-free implementations on some, but not all,
4385 // x86-64 processors.
4386
4387 // Check power-of-two.
4388 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4389 if (!Size.isPowerOfTwo())
4390#if 0
4391 // FIXME: Suppress this folding until the ABI for the promotion width
4392 // settles.
4393 return Success(0, E);
4394#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004395 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004396#endif
4397
4398#if 0
4399 // Check against promotion width.
4400 // FIXME: Suppress this folding until the ABI for the promotion width
4401 // settles.
4402 unsigned PromoteWidthBits =
4403 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4404 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4405 return Success(0, E);
4406#endif
4407
4408 // Check against inlining width.
4409 unsigned InlineWidthBits =
4410 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4411 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4412 return Success(1, E);
4413
Richard Smithf48fdb02011-12-09 22:58:01 +00004414 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004415 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004416 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004417}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004418
Richard Smith625b8072011-10-31 01:37:14 +00004419static bool HasSameBase(const LValue &A, const LValue &B) {
4420 if (!A.getLValueBase())
4421 return !B.getLValueBase();
4422 if (!B.getLValueBase())
4423 return false;
4424
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004425 if (A.getLValueBase().getOpaqueValue() !=
4426 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004427 const Decl *ADecl = GetLValueBaseDecl(A);
4428 if (!ADecl)
4429 return false;
4430 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004431 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004432 return false;
4433 }
4434
4435 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004436 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004437}
4438
Richard Smith7b48a292012-02-01 05:53:12 +00004439/// Perform the given integer operation, which is known to need at most BitWidth
4440/// bits, and check for overflow in the original type (if that type was not an
4441/// unsigned type).
4442template<typename Operation>
4443static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4444 const APSInt &LHS, const APSInt &RHS,
4445 unsigned BitWidth, Operation Op) {
4446 if (LHS.isUnsigned())
4447 return Op(LHS, RHS);
4448
4449 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4450 APSInt Result = Value.trunc(LHS.getBitWidth());
4451 if (Result.extend(BitWidth) != Value)
4452 HandleOverflow(Info, E, Value, E->getType());
4453 return Result;
4454}
4455
Chris Lattnerb542afe2008-07-11 19:10:17 +00004456bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004457 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004458 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004459
John McCall2de56d12010-08-25 11:45:40 +00004460 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004461 VisitIgnoredValue(E->getLHS());
4462 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004463 }
4464
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004465 if (E->isLogicalOp()) {
4466 // These need to be handled specially because the operands aren't
4467 // necessarily integral nor evaluated.
4468 bool lhsResult, rhsResult;
4469
4470 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
4471 // We were able to evaluate the LHS, see if we can get away with not
4472 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
4473 if (lhsResult == (E->getOpcode() == BO_LOr))
4474 return Success(lhsResult, E);
4475
4476 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4477 if (E->getOpcode() == BO_LOr)
4478 return Success(lhsResult || rhsResult, E);
4479 else
4480 return Success(lhsResult && rhsResult, E);
4481 }
4482 } else {
4483 // Since we weren't able to evaluate the left hand side, it
4484 // must have had side effects.
4485 Info.EvalStatus.HasSideEffects = true;
4486
4487 // Suppress diagnostics from this arm.
4488 SpeculativeEvaluationRAII Speculative(Info);
4489 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4490 // We can't evaluate the LHS; however, sometimes the result
4491 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4492 if (rhsResult == (E->getOpcode() == BO_LOr))
4493 return Success(rhsResult, E);
4494 }
4495 }
4496
4497 return false;
4498 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004499
Anders Carlsson286f85e2008-11-16 07:17:21 +00004500 QualType LHSTy = E->getLHS()->getType();
4501 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004502
4503 if (LHSTy->isAnyComplexType()) {
4504 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004505 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004506
Richard Smith745f5142012-01-27 01:14:48 +00004507 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4508 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004509 return false;
4510
Richard Smith745f5142012-01-27 01:14:48 +00004511 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004512 return false;
4513
4514 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004515 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004516 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004517 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004518 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4519
John McCall2de56d12010-08-25 11:45:40 +00004520 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004521 return Success((CR_r == APFloat::cmpEqual &&
4522 CR_i == APFloat::cmpEqual), E);
4523 else {
John McCall2de56d12010-08-25 11:45:40 +00004524 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004525 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004526 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004527 CR_r == APFloat::cmpLessThan ||
4528 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004529 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004530 CR_i == APFloat::cmpLessThan ||
4531 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004532 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004533 } else {
John McCall2de56d12010-08-25 11:45:40 +00004534 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004535 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4536 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4537 else {
John McCall2de56d12010-08-25 11:45:40 +00004538 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004539 "Invalid compex comparison.");
4540 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4541 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4542 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004543 }
4544 }
Mike Stump1eb44332009-09-09 15:08:12 +00004545
Anders Carlsson286f85e2008-11-16 07:17:21 +00004546 if (LHSTy->isRealFloatingType() &&
4547 RHSTy->isRealFloatingType()) {
4548 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004549
Richard Smith745f5142012-01-27 01:14:48 +00004550 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4551 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004552 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004553
Richard Smith745f5142012-01-27 01:14:48 +00004554 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004555 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004556
Anders Carlsson286f85e2008-11-16 07:17:21 +00004557 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004558
Anders Carlsson286f85e2008-11-16 07:17:21 +00004559 switch (E->getOpcode()) {
4560 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004561 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004562 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004563 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004564 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004565 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004566 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004567 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004568 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004569 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004570 E);
John McCall2de56d12010-08-25 11:45:40 +00004571 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004572 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004573 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004574 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004575 || CR == APFloat::cmpLessThan
4576 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004577 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004578 }
Mike Stump1eb44332009-09-09 15:08:12 +00004579
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004580 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004581 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004582 LValue LHSValue, RHSValue;
4583
4584 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4585 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004586 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004587
Richard Smith745f5142012-01-27 01:14:48 +00004588 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004589 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004590
Richard Smith625b8072011-10-31 01:37:14 +00004591 // Reject differing bases from the normal codepath; we special-case
4592 // comparisons to null.
4593 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004594 if (E->getOpcode() == BO_Sub) {
4595 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004596 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4597 return false;
4598 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4599 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4600 if (!LHSExpr || !RHSExpr)
4601 return false;
4602 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4603 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4604 if (!LHSAddrExpr || !RHSAddrExpr)
4605 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004606 // Make sure both labels come from the same function.
4607 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4608 RHSAddrExpr->getLabel()->getDeclContext())
4609 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004610 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004611 return true;
4612 }
Richard Smith9e36b532011-10-31 05:11:32 +00004613 // Inequalities and subtractions between unrelated pointers have
4614 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004615 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004616 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004617 // A constant address may compare equal to the address of a symbol.
4618 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004619 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004620 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4621 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004622 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004623 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004624 // distinct addresses. In clang, the result of such a comparison is
4625 // unspecified, so it is not a constant expression. However, we do know
4626 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004627 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4628 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004629 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004630 // We can't tell whether weak symbols will end up pointing to the same
4631 // object.
4632 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004633 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004634 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004635 // (Note that clang defaults to -fmerge-all-constants, which can
4636 // lead to inconsistent results for comparisons involving the address
4637 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004638 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004639 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004640
Richard Smith15efc4d2012-02-01 08:10:20 +00004641 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4642 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4643
Richard Smithf15fda02012-02-02 01:16:57 +00004644 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4645 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4646
John McCall2de56d12010-08-25 11:45:40 +00004647 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004648 // C++11 [expr.add]p6:
4649 // Unless both pointers point to elements of the same array object, or
4650 // one past the last element of the array object, the behavior is
4651 // undefined.
4652 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4653 !AreElementsOfSameArray(getType(LHSValue.Base),
4654 LHSDesignator, RHSDesignator))
4655 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4656
Chris Lattner4992bdd2010-04-20 17:13:14 +00004657 QualType Type = E->getLHS()->getType();
4658 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004659
Richard Smith180f4792011-11-10 06:34:14 +00004660 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004661 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004662 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004663
Richard Smith15efc4d2012-02-01 08:10:20 +00004664 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4665 // and produce incorrect results when it overflows. Such behavior
4666 // appears to be non-conforming, but is common, so perhaps we should
4667 // assume the standard intended for such cases to be undefined behavior
4668 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004669
Richard Smith15efc4d2012-02-01 08:10:20 +00004670 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4671 // overflow in the final conversion to ptrdiff_t.
4672 APSInt LHS(
4673 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4674 APSInt RHS(
4675 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4676 APSInt ElemSize(
4677 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4678 APSInt TrueResult = (LHS - RHS) / ElemSize;
4679 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4680
4681 if (Result.extend(65) != TrueResult)
4682 HandleOverflow(Info, E, TrueResult, E->getType());
4683 return Success(Result, E);
4684 }
Richard Smith82f28582012-01-31 06:41:30 +00004685
4686 // C++11 [expr.rel]p3:
4687 // Pointers to void (after pointer conversions) can be compared, with a
4688 // result defined as follows: If both pointers represent the same
4689 // address or are both the null pointer value, the result is true if the
4690 // operator is <= or >= and false otherwise; otherwise the result is
4691 // unspecified.
4692 // We interpret this as applying to pointers to *cv* void.
4693 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004694 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004695 CCEDiag(E, diag::note_constexpr_void_comparison);
4696
Richard Smithf15fda02012-02-02 01:16:57 +00004697 // C++11 [expr.rel]p2:
4698 // - If two pointers point to non-static data members of the same object,
4699 // or to subobjects or array elements fo such members, recursively, the
4700 // pointer to the later declared member compares greater provided the
4701 // two members have the same access control and provided their class is
4702 // not a union.
4703 // [...]
4704 // - Otherwise pointer comparisons are unspecified.
4705 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4706 E->isRelationalOp()) {
4707 bool WasArrayIndex;
4708 unsigned Mismatch =
4709 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4710 RHSDesignator, WasArrayIndex);
4711 // At the point where the designators diverge, the comparison has a
4712 // specified value if:
4713 // - we are comparing array indices
4714 // - we are comparing fields of a union, or fields with the same access
4715 // Otherwise, the result is unspecified and thus the comparison is not a
4716 // constant expression.
4717 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4718 Mismatch < RHSDesignator.Entries.size()) {
4719 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4720 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4721 if (!LF && !RF)
4722 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4723 else if (!LF)
4724 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4725 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4726 << RF->getParent() << RF;
4727 else if (!RF)
4728 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4729 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4730 << LF->getParent() << LF;
4731 else if (!LF->getParent()->isUnion() &&
4732 LF->getAccess() != RF->getAccess())
4733 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4734 << LF << LF->getAccess() << RF << RF->getAccess()
4735 << LF->getParent();
4736 }
4737 }
4738
Richard Smith625b8072011-10-31 01:37:14 +00004739 switch (E->getOpcode()) {
4740 default: llvm_unreachable("missing comparison operator");
4741 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4742 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4743 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4744 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4745 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4746 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004747 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004748 }
4749 }
Richard Smithb02e4622012-02-01 01:42:44 +00004750
4751 if (LHSTy->isMemberPointerType()) {
4752 assert(E->isEqualityOp() && "unexpected member pointer operation");
4753 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4754
4755 MemberPtr LHSValue, RHSValue;
4756
4757 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4758 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4759 return false;
4760
4761 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4762 return false;
4763
4764 // C++11 [expr.eq]p2:
4765 // If both operands are null, they compare equal. Otherwise if only one is
4766 // null, they compare unequal.
4767 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4768 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4769 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4770 }
4771
4772 // Otherwise if either is a pointer to a virtual member function, the
4773 // result is unspecified.
4774 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4775 if (MD->isVirtual())
4776 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4777 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4778 if (MD->isVirtual())
4779 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4780
4781 // Otherwise they compare equal if and only if they would refer to the
4782 // same member of the same most derived object or the same subobject if
4783 // they were dereferenced with a hypothetical object of the associated
4784 // class type.
4785 bool Equal = LHSValue == RHSValue;
4786 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4787 }
4788
Richard Smith26f2cac2012-02-14 22:35:28 +00004789 if (LHSTy->isNullPtrType()) {
4790 assert(E->isComparisonOp() && "unexpected nullptr operation");
4791 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
4792 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
4793 // are compared, the result is true of the operator is <=, >= or ==, and
4794 // false otherwise.
4795 BinaryOperator::Opcode Opcode = E->getOpcode();
4796 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
4797 }
4798
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004799 if (!LHSTy->isIntegralOrEnumerationType() ||
4800 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004801 // We can't continue from here for non-integral types.
4802 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004803 }
4804
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004805 // The LHS of a constant expr is always evaluated and needed.
Richard Smith1aa0be82012-03-03 22:46:17 +00004806 APValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004807
4808 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4809 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004810 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004811
Richard Smith745f5142012-01-27 01:14:48 +00004812 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004813 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004814
Richard Smith1aa0be82012-03-03 22:46:17 +00004815 APValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004816
4817 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004818 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004819 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4820 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004821 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004822 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004823 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004824 LHSVal.getLValueOffset() -= AdditionalOffset;
4825 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004826 return true;
4827 }
4828
4829 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004830 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004831 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004832 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4833 LHSVal.getInt().getZExtValue());
4834 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004835 return true;
4836 }
4837
Eli Friedman65639282012-01-04 23:13:47 +00004838 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4839 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004840 if (!LHSVal.getLValueOffset().isZero() ||
4841 !RHSVal.getLValueOffset().isZero())
4842 return false;
4843 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4844 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4845 if (!LHSExpr || !RHSExpr)
4846 return false;
4847 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4848 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4849 if (!LHSAddrExpr || !RHSAddrExpr)
4850 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004851 // Make sure both labels come from the same function.
4852 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4853 RHSAddrExpr->getLabel()->getDeclContext())
4854 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004855 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004856 return true;
4857 }
4858
Eli Friedman42edd0d2009-03-24 01:14:50 +00004859 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004860 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004861 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004862
Richard Smithc49bd112011-10-28 17:51:58 +00004863 APSInt &LHS = LHSVal.getInt();
4864 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004865
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004866 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004867 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004868 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004869 case BO_Mul:
4870 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4871 LHS.getBitWidth() * 2,
4872 std::multiplies<APSInt>()), E);
4873 case BO_Add:
4874 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4875 LHS.getBitWidth() + 1,
4876 std::plus<APSInt>()), E);
4877 case BO_Sub:
4878 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4879 LHS.getBitWidth() + 1,
4880 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004881 case BO_And: return Success(LHS & RHS, E);
4882 case BO_Xor: return Success(LHS ^ RHS, E);
4883 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004884 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004885 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004886 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004887 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004888 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4889 // actually undefined behavior in C++11 due to a language defect.
4890 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4891 LHS.isSigned() && LHS.isMinSignedValue())
4892 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4893 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004894 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004895 // During constant-folding, a negative shift is an opposite shift. Such a
4896 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004897 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004898 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004899 RHS = -RHS;
4900 goto shift_right;
4901 }
4902
4903 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004904 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4905 // shifted type.
4906 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4907 if (SA != RHS) {
4908 CCEDiag(E, diag::note_constexpr_large_shift)
4909 << RHS << E->getType() << LHS.getBitWidth();
4910 } else if (LHS.isSigned()) {
4911 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
Richard Smith925d8e72012-02-08 06:14:53 +00004912 // operand, and must not overflow the corresponding unsigned type.
Richard Smith789f9b62012-01-31 04:08:20 +00004913 if (LHS.isNegative())
4914 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
Richard Smith925d8e72012-02-08 06:14:53 +00004915 else if (LHS.countLeadingZeros() < SA)
4916 CCEDiag(E, diag::note_constexpr_lshift_discards);
Richard Smith789f9b62012-01-31 04:08:20 +00004917 }
4918
Richard Smithc49bd112011-10-28 17:51:58 +00004919 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004920 }
John McCall2de56d12010-08-25 11:45:40 +00004921 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004922 // During constant-folding, a negative shift is an opposite shift. Such a
4923 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004924 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004925 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004926 RHS = -RHS;
4927 goto shift_left;
4928 }
4929
4930 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004931 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4932 // shifted type.
4933 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4934 if (SA != RHS)
4935 CCEDiag(E, diag::note_constexpr_large_shift)
4936 << RHS << E->getType() << LHS.getBitWidth();
4937
Richard Smithc49bd112011-10-28 17:51:58 +00004938 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004939 }
Mike Stump1eb44332009-09-09 15:08:12 +00004940
Richard Smithc49bd112011-10-28 17:51:58 +00004941 case BO_LT: return Success(LHS < RHS, E);
4942 case BO_GT: return Success(LHS > RHS, E);
4943 case BO_LE: return Success(LHS <= RHS, E);
4944 case BO_GE: return Success(LHS >= RHS, E);
4945 case BO_EQ: return Success(LHS == RHS, E);
4946 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004947 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004948}
4949
Ken Dyck8b752f12010-01-27 17:10:57 +00004950CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004951 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4952 // result shall be the alignment of the referenced type."
4953 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4954 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004955
4956 // __alignof is defined to return the preferred alignment.
4957 return Info.Ctx.toCharUnitsFromBits(
4958 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004959}
4960
Ken Dyck8b752f12010-01-27 17:10:57 +00004961CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004962 E = E->IgnoreParens();
4963
4964 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004965 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004966 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004967 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4968 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004969
Chris Lattneraf707ab2009-01-24 21:53:27 +00004970 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004971 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4972 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004973
Chris Lattnere9feb472009-01-24 21:09:06 +00004974 return GetAlignOfType(E->getType());
4975}
4976
4977
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004978/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4979/// a result as the expression's type.
4980bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4981 const UnaryExprOrTypeTraitExpr *E) {
4982 switch(E->getKind()) {
4983 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004984 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004985 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004986 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004987 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004988 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004989
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004990 case UETT_VecStep: {
4991 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004992
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004993 if (Ty->isVectorType()) {
4994 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004995
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004996 // The vec_step built-in functions that take a 3-component
4997 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4998 if (n == 3)
4999 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005000
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005001 return Success(n, E);
5002 } else
5003 return Success(1, E);
5004 }
5005
5006 case UETT_SizeOf: {
5007 QualType SrcTy = E->getTypeOfArgument();
5008 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5009 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005010 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5011 SrcTy = Ref->getPointeeType();
5012
Richard Smith180f4792011-11-10 06:34:14 +00005013 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005014 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005015 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005016 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005017 }
5018 }
5019
5020 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005021}
5022
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005023bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005024 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005025 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005026 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005027 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005028 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005029 for (unsigned i = 0; i != n; ++i) {
5030 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5031 switch (ON.getKind()) {
5032 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005033 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005034 APSInt IdxResult;
5035 if (!EvaluateInteger(Idx, IdxResult, Info))
5036 return false;
5037 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5038 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005039 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005040 CurrentType = AT->getElementType();
5041 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5042 Result += IdxResult.getSExtValue() * ElementSize;
5043 break;
5044 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005045
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005046 case OffsetOfExpr::OffsetOfNode::Field: {
5047 FieldDecl *MemberDecl = ON.getField();
5048 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005049 if (!RT)
5050 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005051 RecordDecl *RD = RT->getDecl();
5052 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005053 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005054 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005055 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005056 CurrentType = MemberDecl->getType().getNonReferenceType();
5057 break;
5058 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005059
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005060 case OffsetOfExpr::OffsetOfNode::Identifier:
5061 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005062
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005063 case OffsetOfExpr::OffsetOfNode::Base: {
5064 CXXBaseSpecifier *BaseSpec = ON.getBase();
5065 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005066 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005067
5068 // Find the layout of the class whose base we are looking into.
5069 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005070 if (!RT)
5071 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005072 RecordDecl *RD = RT->getDecl();
5073 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5074
5075 // Find the base class itself.
5076 CurrentType = BaseSpec->getType();
5077 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5078 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005079 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005080
5081 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005082 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005083 break;
5084 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005085 }
5086 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005087 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005088}
5089
Chris Lattnerb542afe2008-07-11 19:10:17 +00005090bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005091 switch (E->getOpcode()) {
5092 default:
5093 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5094 // See C99 6.6p3.
5095 return Error(E);
5096 case UO_Extension:
5097 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5098 // If so, we could clear the diagnostic ID.
5099 return Visit(E->getSubExpr());
5100 case UO_Plus:
5101 // The result is just the value.
5102 return Visit(E->getSubExpr());
5103 case UO_Minus: {
5104 if (!Visit(E->getSubExpr()))
5105 return false;
5106 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005107 const APSInt &Value = Result.getInt();
5108 if (Value.isSigned() && Value.isMinSignedValue())
5109 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5110 E->getType());
5111 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005112 }
5113 case UO_Not: {
5114 if (!Visit(E->getSubExpr()))
5115 return false;
5116 if (!Result.isInt()) return Error(E);
5117 return Success(~Result.getInt(), E);
5118 }
5119 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005120 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005121 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005122 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005123 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005124 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005125 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005126}
Mike Stump1eb44332009-09-09 15:08:12 +00005127
Chris Lattner732b2232008-07-12 01:15:53 +00005128/// HandleCast - This is used to evaluate implicit or explicit casts where the
5129/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005130bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5131 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005132 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005133 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005134
Eli Friedman46a52322011-03-25 00:43:55 +00005135 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005136 case CK_BaseToDerived:
5137 case CK_DerivedToBase:
5138 case CK_UncheckedDerivedToBase:
5139 case CK_Dynamic:
5140 case CK_ToUnion:
5141 case CK_ArrayToPointerDecay:
5142 case CK_FunctionToPointerDecay:
5143 case CK_NullToPointer:
5144 case CK_NullToMemberPointer:
5145 case CK_BaseToDerivedMemberPointer:
5146 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005147 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005148 case CK_ConstructorConversion:
5149 case CK_IntegralToPointer:
5150 case CK_ToVoid:
5151 case CK_VectorSplat:
5152 case CK_IntegralToFloating:
5153 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005154 case CK_CPointerToObjCPointerCast:
5155 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005156 case CK_AnyPointerToBlockPointerCast:
5157 case CK_ObjCObjectLValueCast:
5158 case CK_FloatingRealToComplex:
5159 case CK_FloatingComplexToReal:
5160 case CK_FloatingComplexCast:
5161 case CK_FloatingComplexToIntegralComplex:
5162 case CK_IntegralRealToComplex:
5163 case CK_IntegralComplexCast:
5164 case CK_IntegralComplexToFloatingComplex:
5165 llvm_unreachable("invalid cast kind for integral value");
5166
Eli Friedmane50c2972011-03-25 19:07:11 +00005167 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005168 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005169 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005170 case CK_ARCProduceObject:
5171 case CK_ARCConsumeObject:
5172 case CK_ARCReclaimReturnedObject:
5173 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005174 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005175 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005176
Richard Smith7d580a42012-01-17 21:17:26 +00005177 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005178 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005179 case CK_AtomicToNonAtomic:
5180 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005181 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005182 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005183
5184 case CK_MemberPointerToBoolean:
5185 case CK_PointerToBoolean:
5186 case CK_IntegralToBoolean:
5187 case CK_FloatingToBoolean:
5188 case CK_FloatingComplexToBoolean:
5189 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005190 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005191 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005192 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005193 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005194 }
5195
Eli Friedman46a52322011-03-25 00:43:55 +00005196 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005197 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005198 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005199
Eli Friedmanbe265702009-02-20 01:15:07 +00005200 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005201 // Allow casts of address-of-label differences if they are no-ops
5202 // or narrowing. (The narrowing case isn't actually guaranteed to
5203 // be constant-evaluatable except in some narrow cases which are hard
5204 // to detect here. We let it through on the assumption the user knows
5205 // what they are doing.)
5206 if (Result.isAddrLabelDiff())
5207 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005208 // Only allow casts of lvalues if they are lossless.
5209 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5210 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005211
Richard Smithf72fccf2012-01-30 22:27:01 +00005212 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5213 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005214 }
Mike Stump1eb44332009-09-09 15:08:12 +00005215
Eli Friedman46a52322011-03-25 00:43:55 +00005216 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005217 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5218
John McCallefdb83e2010-05-07 21:00:08 +00005219 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005220 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005221 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005222
Daniel Dunbardd211642009-02-19 22:24:01 +00005223 if (LV.getLValueBase()) {
5224 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005225 // FIXME: Allow a larger integer size than the pointer size, and allow
5226 // narrowing back down to pointer width in subsequent integral casts.
5227 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005228 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005229 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005230
Richard Smithb755a9d2011-11-16 07:18:12 +00005231 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005232 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005233 return true;
5234 }
5235
Ken Dycka7305832010-01-15 12:37:54 +00005236 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5237 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005238 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005239 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005240
Eli Friedman46a52322011-03-25 00:43:55 +00005241 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005242 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005243 if (!EvaluateComplex(SubExpr, C, Info))
5244 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005245 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005246 }
Eli Friedman2217c872009-02-22 11:46:18 +00005247
Eli Friedman46a52322011-03-25 00:43:55 +00005248 case CK_FloatingToIntegral: {
5249 APFloat F(0.0);
5250 if (!EvaluateFloat(SubExpr, F, Info))
5251 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005252
Richard Smithc1c5f272011-12-13 06:39:58 +00005253 APSInt Value;
5254 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5255 return false;
5256 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005257 }
5258 }
Mike Stump1eb44332009-09-09 15:08:12 +00005259
Eli Friedman46a52322011-03-25 00:43:55 +00005260 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005261}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005262
Eli Friedman722c7172009-02-28 03:59:05 +00005263bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5264 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005265 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005266 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5267 return false;
5268 if (!LV.isComplexInt())
5269 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005270 return Success(LV.getComplexIntReal(), E);
5271 }
5272
5273 return Visit(E->getSubExpr());
5274}
5275
Eli Friedman664a1042009-02-27 04:45:43 +00005276bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005277 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005278 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005279 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5280 return false;
5281 if (!LV.isComplexInt())
5282 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005283 return Success(LV.getComplexIntImag(), E);
5284 }
5285
Richard Smith8327fad2011-10-24 18:44:57 +00005286 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005287 return Success(0, E);
5288}
5289
Douglas Gregoree8aff02011-01-04 17:33:58 +00005290bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5291 return Success(E->getPackLength(), E);
5292}
5293
Sebastian Redl295995c2010-09-10 20:55:47 +00005294bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5295 return Success(E->getValue(), E);
5296}
5297
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005298//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005299// Float Evaluation
5300//===----------------------------------------------------------------------===//
5301
5302namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005303class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005304 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005305 APFloat &Result;
5306public:
5307 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005308 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005309
Richard Smith1aa0be82012-03-03 22:46:17 +00005310 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005311 Result = V.getFloat();
5312 return true;
5313 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005314
Richard Smith51201882011-12-30 21:15:51 +00005315 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005316 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5317 return true;
5318 }
5319
Chris Lattner019f4e82008-10-06 05:28:25 +00005320 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005321
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005322 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005323 bool VisitBinaryOperator(const BinaryOperator *E);
5324 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005325 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005326
John McCallabd3a852010-05-07 22:08:54 +00005327 bool VisitUnaryReal(const UnaryOperator *E);
5328 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005329
Richard Smith51201882011-12-30 21:15:51 +00005330 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005331};
5332} // end anonymous namespace
5333
5334static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005335 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005336 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005337}
5338
Jay Foad4ba2a172011-01-12 09:06:06 +00005339static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005340 QualType ResultTy,
5341 const Expr *Arg,
5342 bool SNaN,
5343 llvm::APFloat &Result) {
5344 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5345 if (!S) return false;
5346
5347 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5348
5349 llvm::APInt fill;
5350
5351 // Treat empty strings as if they were zero.
5352 if (S->getString().empty())
5353 fill = llvm::APInt(32, 0);
5354 else if (S->getString().getAsInteger(0, fill))
5355 return false;
5356
5357 if (SNaN)
5358 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5359 else
5360 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5361 return true;
5362}
5363
Chris Lattner019f4e82008-10-06 05:28:25 +00005364bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005365 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005366 default:
5367 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5368
Chris Lattner019f4e82008-10-06 05:28:25 +00005369 case Builtin::BI__builtin_huge_val:
5370 case Builtin::BI__builtin_huge_valf:
5371 case Builtin::BI__builtin_huge_vall:
5372 case Builtin::BI__builtin_inf:
5373 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005374 case Builtin::BI__builtin_infl: {
5375 const llvm::fltSemantics &Sem =
5376 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005377 Result = llvm::APFloat::getInf(Sem);
5378 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005379 }
Mike Stump1eb44332009-09-09 15:08:12 +00005380
John McCalldb7b72a2010-02-28 13:00:19 +00005381 case Builtin::BI__builtin_nans:
5382 case Builtin::BI__builtin_nansf:
5383 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005384 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5385 true, Result))
5386 return Error(E);
5387 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005388
Chris Lattner9e621712008-10-06 06:31:58 +00005389 case Builtin::BI__builtin_nan:
5390 case Builtin::BI__builtin_nanf:
5391 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005392 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005393 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005394 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5395 false, Result))
5396 return Error(E);
5397 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005398
5399 case Builtin::BI__builtin_fabs:
5400 case Builtin::BI__builtin_fabsf:
5401 case Builtin::BI__builtin_fabsl:
5402 if (!EvaluateFloat(E->getArg(0), Result, Info))
5403 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005404
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005405 if (Result.isNegative())
5406 Result.changeSign();
5407 return true;
5408
Mike Stump1eb44332009-09-09 15:08:12 +00005409 case Builtin::BI__builtin_copysign:
5410 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005411 case Builtin::BI__builtin_copysignl: {
5412 APFloat RHS(0.);
5413 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5414 !EvaluateFloat(E->getArg(1), RHS, Info))
5415 return false;
5416 Result.copySign(RHS);
5417 return true;
5418 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005419 }
5420}
5421
John McCallabd3a852010-05-07 22:08:54 +00005422bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005423 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5424 ComplexValue CV;
5425 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5426 return false;
5427 Result = CV.FloatReal;
5428 return true;
5429 }
5430
5431 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005432}
5433
5434bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005435 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5436 ComplexValue CV;
5437 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5438 return false;
5439 Result = CV.FloatImag;
5440 return true;
5441 }
5442
Richard Smith8327fad2011-10-24 18:44:57 +00005443 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005444 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5445 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005446 return true;
5447}
5448
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005449bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005450 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005451 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005452 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005453 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005454 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005455 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5456 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005457 Result.changeSign();
5458 return true;
5459 }
5460}
Chris Lattner019f4e82008-10-06 05:28:25 +00005461
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005462bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005463 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5464 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005465
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005466 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005467 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5468 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005469 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005470 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005471 return false;
5472
5473 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005474 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005475 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005476 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005477 break;
John McCall2de56d12010-08-25 11:45:40 +00005478 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005479 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005480 break;
John McCall2de56d12010-08-25 11:45:40 +00005481 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005482 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005483 break;
John McCall2de56d12010-08-25 11:45:40 +00005484 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005485 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005486 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005487 }
Richard Smith7b48a292012-02-01 05:53:12 +00005488
5489 if (Result.isInfinity() || Result.isNaN())
5490 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5491 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005492}
5493
5494bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5495 Result = E->getValue();
5496 return true;
5497}
5498
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005499bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5500 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005501
Eli Friedman2a523ee2011-03-25 00:54:52 +00005502 switch (E->getCastKind()) {
5503 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005504 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005505
5506 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005507 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005508 return EvaluateInteger(SubExpr, IntResult, Info) &&
5509 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5510 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005511 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005512
5513 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005514 if (!Visit(SubExpr))
5515 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005516 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5517 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005518 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005519
Eli Friedman2a523ee2011-03-25 00:54:52 +00005520 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005521 ComplexValue V;
5522 if (!EvaluateComplex(SubExpr, V, Info))
5523 return false;
5524 Result = V.getComplexFloatReal();
5525 return true;
5526 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005527 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005528}
5529
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005530//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005531// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005532//===----------------------------------------------------------------------===//
5533
5534namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005535class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005536 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005537 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005538
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005539public:
John McCallf4cf1a12010-05-07 17:22:02 +00005540 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005541 : ExprEvaluatorBaseTy(info), Result(Result) {}
5542
Richard Smith1aa0be82012-03-03 22:46:17 +00005543 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005544 Result.setFrom(V);
5545 return true;
5546 }
Mike Stump1eb44332009-09-09 15:08:12 +00005547
Eli Friedman7ead5c72012-01-10 04:58:17 +00005548 bool ZeroInitialization(const Expr *E);
5549
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005550 //===--------------------------------------------------------------------===//
5551 // Visitor Methods
5552 //===--------------------------------------------------------------------===//
5553
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005554 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005555 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005556 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005557 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005558 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005559};
5560} // end anonymous namespace
5561
John McCallf4cf1a12010-05-07 17:22:02 +00005562static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5563 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005564 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005565 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005566}
5567
Eli Friedman7ead5c72012-01-10 04:58:17 +00005568bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005569 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005570 if (ElemTy->isRealFloatingType()) {
5571 Result.makeComplexFloat();
5572 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5573 Result.FloatReal = Zero;
5574 Result.FloatImag = Zero;
5575 } else {
5576 Result.makeComplexInt();
5577 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5578 Result.IntReal = Zero;
5579 Result.IntImag = Zero;
5580 }
5581 return true;
5582}
5583
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005584bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5585 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005586
5587 if (SubExpr->getType()->isRealFloatingType()) {
5588 Result.makeComplexFloat();
5589 APFloat &Imag = Result.FloatImag;
5590 if (!EvaluateFloat(SubExpr, Imag, Info))
5591 return false;
5592
5593 Result.FloatReal = APFloat(Imag.getSemantics());
5594 return true;
5595 } else {
5596 assert(SubExpr->getType()->isIntegerType() &&
5597 "Unexpected imaginary literal.");
5598
5599 Result.makeComplexInt();
5600 APSInt &Imag = Result.IntImag;
5601 if (!EvaluateInteger(SubExpr, Imag, Info))
5602 return false;
5603
5604 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5605 return true;
5606 }
5607}
5608
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005609bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005610
John McCall8786da72010-12-14 17:51:41 +00005611 switch (E->getCastKind()) {
5612 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005613 case CK_BaseToDerived:
5614 case CK_DerivedToBase:
5615 case CK_UncheckedDerivedToBase:
5616 case CK_Dynamic:
5617 case CK_ToUnion:
5618 case CK_ArrayToPointerDecay:
5619 case CK_FunctionToPointerDecay:
5620 case CK_NullToPointer:
5621 case CK_NullToMemberPointer:
5622 case CK_BaseToDerivedMemberPointer:
5623 case CK_DerivedToBaseMemberPointer:
5624 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005625 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005626 case CK_ConstructorConversion:
5627 case CK_IntegralToPointer:
5628 case CK_PointerToIntegral:
5629 case CK_PointerToBoolean:
5630 case CK_ToVoid:
5631 case CK_VectorSplat:
5632 case CK_IntegralCast:
5633 case CK_IntegralToBoolean:
5634 case CK_IntegralToFloating:
5635 case CK_FloatingToIntegral:
5636 case CK_FloatingToBoolean:
5637 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005638 case CK_CPointerToObjCPointerCast:
5639 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005640 case CK_AnyPointerToBlockPointerCast:
5641 case CK_ObjCObjectLValueCast:
5642 case CK_FloatingComplexToReal:
5643 case CK_FloatingComplexToBoolean:
5644 case CK_IntegralComplexToReal:
5645 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005646 case CK_ARCProduceObject:
5647 case CK_ARCConsumeObject:
5648 case CK_ARCReclaimReturnedObject:
5649 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005650 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005651 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005652
John McCall8786da72010-12-14 17:51:41 +00005653 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005654 case CK_AtomicToNonAtomic:
5655 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005656 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005657 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005658
5659 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005660 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005661 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005662 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005663
5664 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005665 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005666 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005667 return false;
5668
John McCall8786da72010-12-14 17:51:41 +00005669 Result.makeComplexFloat();
5670 Result.FloatImag = APFloat(Real.getSemantics());
5671 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005672 }
5673
John McCall8786da72010-12-14 17:51:41 +00005674 case CK_FloatingComplexCast: {
5675 if (!Visit(E->getSubExpr()))
5676 return false;
5677
5678 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5679 QualType From
5680 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5681
Richard Smithc1c5f272011-12-13 06:39:58 +00005682 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5683 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005684 }
5685
5686 case CK_FloatingComplexToIntegralComplex: {
5687 if (!Visit(E->getSubExpr()))
5688 return false;
5689
5690 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5691 QualType From
5692 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5693 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005694 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5695 To, Result.IntReal) &&
5696 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5697 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005698 }
5699
5700 case CK_IntegralRealToComplex: {
5701 APSInt &Real = Result.IntReal;
5702 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5703 return false;
5704
5705 Result.makeComplexInt();
5706 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5707 return true;
5708 }
5709
5710 case CK_IntegralComplexCast: {
5711 if (!Visit(E->getSubExpr()))
5712 return false;
5713
5714 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5715 QualType From
5716 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5717
Richard Smithf72fccf2012-01-30 22:27:01 +00005718 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5719 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005720 return true;
5721 }
5722
5723 case CK_IntegralComplexToFloatingComplex: {
5724 if (!Visit(E->getSubExpr()))
5725 return false;
5726
5727 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5728 QualType From
5729 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5730 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005731 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5732 To, Result.FloatReal) &&
5733 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5734 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005735 }
5736 }
5737
5738 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005739}
5740
John McCallf4cf1a12010-05-07 17:22:02 +00005741bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005742 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005743 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5744
Richard Smith745f5142012-01-27 01:14:48 +00005745 bool LHSOK = Visit(E->getLHS());
5746 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005747 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005748
John McCallf4cf1a12010-05-07 17:22:02 +00005749 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005750 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005751 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005752
Daniel Dunbar3f279872009-01-29 01:32:56 +00005753 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5754 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005755 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005756 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005757 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005758 if (Result.isComplexFloat()) {
5759 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5760 APFloat::rmNearestTiesToEven);
5761 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5762 APFloat::rmNearestTiesToEven);
5763 } else {
5764 Result.getComplexIntReal() += RHS.getComplexIntReal();
5765 Result.getComplexIntImag() += RHS.getComplexIntImag();
5766 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005767 break;
John McCall2de56d12010-08-25 11:45:40 +00005768 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005769 if (Result.isComplexFloat()) {
5770 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5771 APFloat::rmNearestTiesToEven);
5772 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5773 APFloat::rmNearestTiesToEven);
5774 } else {
5775 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5776 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5777 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005778 break;
John McCall2de56d12010-08-25 11:45:40 +00005779 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005780 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005781 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005782 APFloat &LHS_r = LHS.getComplexFloatReal();
5783 APFloat &LHS_i = LHS.getComplexFloatImag();
5784 APFloat &RHS_r = RHS.getComplexFloatReal();
5785 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005786
Daniel Dunbar3f279872009-01-29 01:32:56 +00005787 APFloat Tmp = LHS_r;
5788 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5789 Result.getComplexFloatReal() = Tmp;
5790 Tmp = LHS_i;
5791 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5792 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5793
5794 Tmp = LHS_r;
5795 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5796 Result.getComplexFloatImag() = Tmp;
5797 Tmp = LHS_i;
5798 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5799 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5800 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005801 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005802 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005803 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5804 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005805 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005806 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5807 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5808 }
5809 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005810 case BO_Div:
5811 if (Result.isComplexFloat()) {
5812 ComplexValue LHS = Result;
5813 APFloat &LHS_r = LHS.getComplexFloatReal();
5814 APFloat &LHS_i = LHS.getComplexFloatImag();
5815 APFloat &RHS_r = RHS.getComplexFloatReal();
5816 APFloat &RHS_i = RHS.getComplexFloatImag();
5817 APFloat &Res_r = Result.getComplexFloatReal();
5818 APFloat &Res_i = Result.getComplexFloatImag();
5819
5820 APFloat Den = RHS_r;
5821 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5822 APFloat Tmp = RHS_i;
5823 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5824 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5825
5826 Res_r = LHS_r;
5827 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5828 Tmp = LHS_i;
5829 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5830 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5831 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5832
5833 Res_i = LHS_i;
5834 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5835 Tmp = LHS_r;
5836 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5837 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5838 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5839 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005840 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5841 return Error(E, diag::note_expr_divide_by_zero);
5842
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005843 ComplexValue LHS = Result;
5844 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5845 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5846 Result.getComplexIntReal() =
5847 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5848 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5849 Result.getComplexIntImag() =
5850 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5851 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5852 }
5853 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005854 }
5855
John McCallf4cf1a12010-05-07 17:22:02 +00005856 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005857}
5858
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005859bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5860 // Get the operand value into 'Result'.
5861 if (!Visit(E->getSubExpr()))
5862 return false;
5863
5864 switch (E->getOpcode()) {
5865 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005866 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005867 case UO_Extension:
5868 return true;
5869 case UO_Plus:
5870 // The result is always just the subexpr.
5871 return true;
5872 case UO_Minus:
5873 if (Result.isComplexFloat()) {
5874 Result.getComplexFloatReal().changeSign();
5875 Result.getComplexFloatImag().changeSign();
5876 }
5877 else {
5878 Result.getComplexIntReal() = -Result.getComplexIntReal();
5879 Result.getComplexIntImag() = -Result.getComplexIntImag();
5880 }
5881 return true;
5882 case UO_Not:
5883 if (Result.isComplexFloat())
5884 Result.getComplexFloatImag().changeSign();
5885 else
5886 Result.getComplexIntImag() = -Result.getComplexIntImag();
5887 return true;
5888 }
5889}
5890
Eli Friedman7ead5c72012-01-10 04:58:17 +00005891bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5892 if (E->getNumInits() == 2) {
5893 if (E->getType()->isComplexType()) {
5894 Result.makeComplexFloat();
5895 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5896 return false;
5897 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5898 return false;
5899 } else {
5900 Result.makeComplexInt();
5901 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5902 return false;
5903 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5904 return false;
5905 }
5906 return true;
5907 }
5908 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5909}
5910
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005911//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005912// Void expression evaluation, primarily for a cast to void on the LHS of a
5913// comma operator
5914//===----------------------------------------------------------------------===//
5915
5916namespace {
5917class VoidExprEvaluator
5918 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5919public:
5920 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5921
Richard Smith1aa0be82012-03-03 22:46:17 +00005922 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005923
5924 bool VisitCastExpr(const CastExpr *E) {
5925 switch (E->getCastKind()) {
5926 default:
5927 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5928 case CK_ToVoid:
5929 VisitIgnoredValue(E->getSubExpr());
5930 return true;
5931 }
5932 }
5933};
5934} // end anonymous namespace
5935
5936static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5937 assert(E->isRValue() && E->getType()->isVoidType());
5938 return VoidExprEvaluator(Info).Visit(E);
5939}
5940
5941//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005942// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005943//===----------------------------------------------------------------------===//
5944
Richard Smith1aa0be82012-03-03 22:46:17 +00005945static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005946 // In C, function designators are not lvalues, but we evaluate them as if they
5947 // are.
5948 if (E->isGLValue() || E->getType()->isFunctionType()) {
5949 LValue LV;
5950 if (!EvaluateLValue(E, LV, Info))
5951 return false;
5952 LV.moveInto(Result);
5953 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005954 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005955 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005956 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005957 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005958 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005959 } else if (E->getType()->hasPointerRepresentation()) {
5960 LValue LV;
5961 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005962 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005963 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005964 } else if (E->getType()->isRealFloatingType()) {
5965 llvm::APFloat F(0.0);
5966 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005967 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00005968 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005969 } else if (E->getType()->isAnyComplexType()) {
5970 ComplexValue C;
5971 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005972 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005973 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005974 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005975 MemberPtr P;
5976 if (!EvaluateMemberPointer(E, P, Info))
5977 return false;
5978 P.moveInto(Result);
5979 return true;
Richard Smith51201882011-12-30 21:15:51 +00005980 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005981 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005982 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005983 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005984 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005985 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005986 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005987 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005988 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005989 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5990 return false;
5991 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005992 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005993 if (Info.getLangOpts().CPlusPlus0x)
Richard Smithd75fb492012-03-15 00:41:48 +00005994 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00005995 << E->getType();
5996 else
Richard Smithd75fb492012-03-15 00:41:48 +00005997 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005998 if (!EvaluateVoid(E, Info))
5999 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006000 } else if (Info.getLangOpts().CPlusPlus0x) {
Richard Smithd75fb492012-03-15 00:41:48 +00006001 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006002 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006003 } else {
Richard Smithd75fb492012-03-15 00:41:48 +00006004 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006005 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006006 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006007
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006008 return true;
6009}
6010
Richard Smith83587db2012-02-15 02:18:13 +00006011/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6012/// cases, the in-place evaluation is essential, since later initializers for
6013/// an object can indirectly refer to subobjects which were initialized earlier.
6014static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6015 const Expr *E, CheckConstantExpressionKind CCEK,
6016 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006017 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006018 return false;
6019
6020 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006021 // Evaluate arrays and record types in-place, so that later initializers can
6022 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006023 if (E->getType()->isArrayType())
6024 return EvaluateArray(E, This, Result, Info);
6025 else if (E->getType()->isRecordType())
6026 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006027 }
6028
6029 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006030 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006031}
6032
Richard Smithf48fdb02011-12-09 22:58:01 +00006033/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6034/// lvalue-to-rvalue cast if it is an lvalue.
6035static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006036 if (!CheckLiteralType(Info, E))
6037 return false;
6038
Richard Smith1aa0be82012-03-03 22:46:17 +00006039 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006040 return false;
6041
6042 if (E->isGLValue()) {
6043 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006044 LV.setFrom(Info.Ctx, Result);
6045 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006046 return false;
6047 }
6048
Richard Smith1aa0be82012-03-03 22:46:17 +00006049 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006050 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006051}
Richard Smithc49bd112011-10-28 17:51:58 +00006052
Richard Smith51f47082011-10-29 00:50:52 +00006053/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006054/// any crazy technique (that has nothing to do with language standards) that
6055/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006056/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6057/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006058bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006059 // Fast-path evaluations of integer literals, since we sometimes see files
6060 // containing vast quantities of these.
6061 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6062 Result.Val = APValue(APSInt(L->getValue(),
6063 L->getType()->isUnsignedIntegerType()));
6064 return true;
6065 }
6066
Richard Smith2d6a5672012-01-14 04:30:29 +00006067 // FIXME: Evaluating values of large array and record types can cause
6068 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006069 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006070 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006071 return false;
6072
Richard Smithf48fdb02011-12-09 22:58:01 +00006073 EvalInfo Info(Ctx, Result);
6074 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006075}
6076
Jay Foad4ba2a172011-01-12 09:06:06 +00006077bool Expr::EvaluateAsBooleanCondition(bool &Result,
6078 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006079 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006080 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006081 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006082}
6083
Richard Smith80d4b552011-12-28 19:48:30 +00006084bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6085 SideEffectsKind AllowSideEffects) const {
6086 if (!getType()->isIntegralOrEnumerationType())
6087 return false;
6088
Richard Smithc49bd112011-10-28 17:51:58 +00006089 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006090 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6091 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006092 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006093
Richard Smithc49bd112011-10-28 17:51:58 +00006094 Result = ExprResult.Val.getInt();
6095 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006096}
6097
Jay Foad4ba2a172011-01-12 09:06:06 +00006098bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006099 EvalInfo Info(Ctx, Result);
6100
John McCallefdb83e2010-05-07 21:00:08 +00006101 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006102 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6103 !CheckLValueConstantExpression(Info, getExprLoc(),
6104 Ctx.getLValueReferenceType(getType()), LV))
6105 return false;
6106
Richard Smith1aa0be82012-03-03 22:46:17 +00006107 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006108 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006109}
6110
Richard Smith099e7f62011-12-19 06:19:21 +00006111bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6112 const VarDecl *VD,
6113 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006114 // FIXME: Evaluating initializers for large array and record types can cause
6115 // performance problems. Only do so in C++11 for now.
6116 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006117 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith2d6a5672012-01-14 04:30:29 +00006118 return false;
6119
Richard Smith099e7f62011-12-19 06:19:21 +00006120 Expr::EvalStatus EStatus;
6121 EStatus.Diag = &Notes;
6122
6123 EvalInfo InitInfo(Ctx, EStatus);
6124 InitInfo.setEvaluatingDecl(VD, Value);
6125
6126 LValue LVal;
6127 LVal.set(VD);
6128
Richard Smith51201882011-12-30 21:15:51 +00006129 // C++11 [basic.start.init]p2:
6130 // Variables with static storage duration or thread storage duration shall be
6131 // zero-initialized before any other initialization takes place.
6132 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006133 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006134 !VD->getType()->isReferenceType()) {
6135 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006136 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6137 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006138 return false;
6139 }
6140
Richard Smith83587db2012-02-15 02:18:13 +00006141 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6142 /*AllowNonLiteralTypes=*/true) ||
6143 EStatus.HasSideEffects)
6144 return false;
6145
6146 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6147 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006148}
6149
Richard Smith51f47082011-10-29 00:50:52 +00006150/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6151/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006152bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006153 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006154 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006155}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006156
Jay Foad4ba2a172011-01-12 09:06:06 +00006157bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006158 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006159}
6160
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006161APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006162 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006163 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006164 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006165 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006166 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006167
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006168 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006169}
John McCalld905f5a2010-05-07 05:32:02 +00006170
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006171 bool Expr::EvalResult::isGlobalLValue() const {
6172 assert(Val.isLValue());
6173 return IsGlobalLValue(Val.getLValueBase());
6174 }
6175
6176
John McCalld905f5a2010-05-07 05:32:02 +00006177/// isIntegerConstantExpr - this recursive routine will test if an expression is
6178/// an integer constant expression.
6179
6180/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6181/// comma, etc
6182///
6183/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6184/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6185/// cast+dereference.
6186
6187// CheckICE - This function does the fundamental ICE checking: the returned
6188// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6189// Note that to reduce code duplication, this helper does no evaluation
6190// itself; the caller checks whether the expression is evaluatable, and
6191// in the rare cases where CheckICE actually cares about the evaluated
6192// value, it calls into Evalute.
6193//
6194// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006195// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006196// 1: This expression is not an ICE, but if it isn't evaluated, it's
6197// a legal subexpression for an ICE. This return value is used to handle
6198// the comma operator in C99 mode.
6199// 2: This expression is not an ICE, and is not a legal subexpression for one.
6200
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006201namespace {
6202
John McCalld905f5a2010-05-07 05:32:02 +00006203struct ICEDiag {
6204 unsigned Val;
6205 SourceLocation Loc;
6206
6207 public:
6208 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6209 ICEDiag() : Val(0) {}
6210};
6211
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006212}
6213
6214static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006215
6216static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6217 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006218 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006219 !EVResult.Val.isInt()) {
6220 return ICEDiag(2, E->getLocStart());
6221 }
6222 return NoDiag();
6223}
6224
6225static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6226 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006227 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006228 return ICEDiag(2, E->getLocStart());
6229 }
6230
6231 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006232#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006233#define STMT(Node, Base) case Expr::Node##Class:
6234#define EXPR(Node, Base)
6235#include "clang/AST/StmtNodes.inc"
6236 case Expr::PredefinedExprClass:
6237 case Expr::FloatingLiteralClass:
6238 case Expr::ImaginaryLiteralClass:
6239 case Expr::StringLiteralClass:
6240 case Expr::ArraySubscriptExprClass:
6241 case Expr::MemberExprClass:
6242 case Expr::CompoundAssignOperatorClass:
6243 case Expr::CompoundLiteralExprClass:
6244 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006245 case Expr::DesignatedInitExprClass:
6246 case Expr::ImplicitValueInitExprClass:
6247 case Expr::ParenListExprClass:
6248 case Expr::VAArgExprClass:
6249 case Expr::AddrLabelExprClass:
6250 case Expr::StmtExprClass:
6251 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006252 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006253 case Expr::CXXDynamicCastExprClass:
6254 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006255 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006256 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006257 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006258 case Expr::CXXThisExprClass:
6259 case Expr::CXXThrowExprClass:
6260 case Expr::CXXNewExprClass:
6261 case Expr::CXXDeleteExprClass:
6262 case Expr::CXXPseudoDestructorExprClass:
6263 case Expr::UnresolvedLookupExprClass:
6264 case Expr::DependentScopeDeclRefExprClass:
6265 case Expr::CXXConstructExprClass:
6266 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006267 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006268 case Expr::CXXTemporaryObjectExprClass:
6269 case Expr::CXXUnresolvedConstructExprClass:
6270 case Expr::CXXDependentScopeMemberExprClass:
6271 case Expr::UnresolvedMemberExprClass:
6272 case Expr::ObjCStringLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006273 case Expr::ObjCNumericLiteralClass:
6274 case Expr::ObjCArrayLiteralClass:
6275 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006276 case Expr::ObjCEncodeExprClass:
6277 case Expr::ObjCMessageExprClass:
6278 case Expr::ObjCSelectorExprClass:
6279 case Expr::ObjCProtocolExprClass:
6280 case Expr::ObjCIvarRefExprClass:
6281 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006282 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006283 case Expr::ObjCIsaExprClass:
6284 case Expr::ShuffleVectorExprClass:
6285 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006286 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006287 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006288 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006289 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006290 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006291 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006292 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006293 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006294 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006295 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006296 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006297 return ICEDiag(2, E->getLocStart());
6298
Douglas Gregoree8aff02011-01-04 17:33:58 +00006299 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006300 case Expr::GNUNullExprClass:
6301 // GCC considers the GNU __null value to be an integral constant expression.
6302 return NoDiag();
6303
John McCall91a57552011-07-15 05:09:51 +00006304 case Expr::SubstNonTypeTemplateParmExprClass:
6305 return
6306 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6307
John McCalld905f5a2010-05-07 05:32:02 +00006308 case Expr::ParenExprClass:
6309 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006310 case Expr::GenericSelectionExprClass:
6311 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006312 case Expr::IntegerLiteralClass:
6313 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006314 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006315 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006316 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006317 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006318 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006319 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006320 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006321 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006322 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006323 return NoDiag();
6324 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006325 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006326 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6327 // constant expressions, but they can never be ICEs because an ICE cannot
6328 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006329 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006330 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006331 return CheckEvalInICE(E, Ctx);
6332 return ICEDiag(2, E->getLocStart());
6333 }
Richard Smith359c89d2012-02-24 22:12:32 +00006334 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006335 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6336 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006337 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006338 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006339 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006340 // Parameter variables are never constants. Without this check,
6341 // getAnyInitializer() can find a default argument, which leads
6342 // to chaos.
6343 if (isa<ParmVarDecl>(D))
6344 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6345
6346 // C++ 7.1.5.1p2
6347 // A variable of non-volatile const-qualified integral or enumeration
6348 // type initialized by an ICE can be used in ICEs.
6349 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006350 if (!Dcl->getType()->isIntegralOrEnumerationType())
6351 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6352
Richard Smith099e7f62011-12-19 06:19:21 +00006353 const VarDecl *VD;
6354 // Look for a declaration of this variable that has an initializer, and
6355 // check whether it is an ICE.
6356 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6357 return NoDiag();
6358 else
6359 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006360 }
6361 }
6362 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006363 }
John McCalld905f5a2010-05-07 05:32:02 +00006364 case Expr::UnaryOperatorClass: {
6365 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6366 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006367 case UO_PostInc:
6368 case UO_PostDec:
6369 case UO_PreInc:
6370 case UO_PreDec:
6371 case UO_AddrOf:
6372 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006373 // C99 6.6/3 allows increment and decrement within unevaluated
6374 // subexpressions of constant expressions, but they can never be ICEs
6375 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006376 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006377 case UO_Extension:
6378 case UO_LNot:
6379 case UO_Plus:
6380 case UO_Minus:
6381 case UO_Not:
6382 case UO_Real:
6383 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006384 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006385 }
6386
6387 // OffsetOf falls through here.
6388 }
6389 case Expr::OffsetOfExprClass: {
6390 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006391 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006392 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006393 // compliance: we should warn earlier for offsetof expressions with
6394 // array subscripts that aren't ICEs, and if the array subscripts
6395 // are ICEs, the value of the offsetof must be an integer constant.
6396 return CheckEvalInICE(E, Ctx);
6397 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006398 case Expr::UnaryExprOrTypeTraitExprClass: {
6399 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6400 if ((Exp->getKind() == UETT_SizeOf) &&
6401 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006402 return ICEDiag(2, E->getLocStart());
6403 return NoDiag();
6404 }
6405 case Expr::BinaryOperatorClass: {
6406 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6407 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006408 case BO_PtrMemD:
6409 case BO_PtrMemI:
6410 case BO_Assign:
6411 case BO_MulAssign:
6412 case BO_DivAssign:
6413 case BO_RemAssign:
6414 case BO_AddAssign:
6415 case BO_SubAssign:
6416 case BO_ShlAssign:
6417 case BO_ShrAssign:
6418 case BO_AndAssign:
6419 case BO_XorAssign:
6420 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006421 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6422 // constant expressions, but they can never be ICEs because an ICE cannot
6423 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006424 return ICEDiag(2, E->getLocStart());
6425
John McCall2de56d12010-08-25 11:45:40 +00006426 case BO_Mul:
6427 case BO_Div:
6428 case BO_Rem:
6429 case BO_Add:
6430 case BO_Sub:
6431 case BO_Shl:
6432 case BO_Shr:
6433 case BO_LT:
6434 case BO_GT:
6435 case BO_LE:
6436 case BO_GE:
6437 case BO_EQ:
6438 case BO_NE:
6439 case BO_And:
6440 case BO_Xor:
6441 case BO_Or:
6442 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006443 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6444 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006445 if (Exp->getOpcode() == BO_Div ||
6446 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006447 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006448 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006449 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006450 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006451 if (REval == 0)
6452 return ICEDiag(1, E->getLocStart());
6453 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006454 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006455 if (LEval.isMinSignedValue())
6456 return ICEDiag(1, E->getLocStart());
6457 }
6458 }
6459 }
John McCall2de56d12010-08-25 11:45:40 +00006460 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006461 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006462 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6463 // if it isn't evaluated.
6464 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6465 return ICEDiag(1, E->getLocStart());
6466 } else {
6467 // In both C89 and C++, commas in ICEs are illegal.
6468 return ICEDiag(2, E->getLocStart());
6469 }
6470 }
6471 if (LHSResult.Val >= RHSResult.Val)
6472 return LHSResult;
6473 return RHSResult;
6474 }
John McCall2de56d12010-08-25 11:45:40 +00006475 case BO_LAnd:
6476 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006477 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6478 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6479 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6480 // Rare case where the RHS has a comma "side-effect"; we need
6481 // to actually check the condition to see whether the side
6482 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006483 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006484 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006485 return RHSResult;
6486 return NoDiag();
6487 }
6488
6489 if (LHSResult.Val >= RHSResult.Val)
6490 return LHSResult;
6491 return RHSResult;
6492 }
6493 }
6494 }
6495 case Expr::ImplicitCastExprClass:
6496 case Expr::CStyleCastExprClass:
6497 case Expr::CXXFunctionalCastExprClass:
6498 case Expr::CXXStaticCastExprClass:
6499 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006500 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006501 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006502 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006503 if (isa<ExplicitCastExpr>(E)) {
6504 if (const FloatingLiteral *FL
6505 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6506 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6507 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6508 APSInt IgnoredVal(DestWidth, !DestSigned);
6509 bool Ignored;
6510 // If the value does not fit in the destination type, the behavior is
6511 // undefined, so we are not required to treat it as a constant
6512 // expression.
6513 if (FL->getValue().convertToInteger(IgnoredVal,
6514 llvm::APFloat::rmTowardZero,
6515 &Ignored) & APFloat::opInvalidOp)
6516 return ICEDiag(2, E->getLocStart());
6517 return NoDiag();
6518 }
6519 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006520 switch (cast<CastExpr>(E)->getCastKind()) {
6521 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006522 case CK_AtomicToNonAtomic:
6523 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006524 case CK_NoOp:
6525 case CK_IntegralToBoolean:
6526 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006527 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006528 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006529 return ICEDiag(2, E->getLocStart());
6530 }
John McCalld905f5a2010-05-07 05:32:02 +00006531 }
John McCall56ca35d2011-02-17 10:25:35 +00006532 case Expr::BinaryConditionalOperatorClass: {
6533 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6534 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6535 if (CommonResult.Val == 2) return CommonResult;
6536 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6537 if (FalseResult.Val == 2) return FalseResult;
6538 if (CommonResult.Val == 1) return CommonResult;
6539 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006540 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006541 return FalseResult;
6542 }
John McCalld905f5a2010-05-07 05:32:02 +00006543 case Expr::ConditionalOperatorClass: {
6544 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6545 // If the condition (ignoring parens) is a __builtin_constant_p call,
6546 // then only the true side is actually considered in an integer constant
6547 // expression, and it is fully evaluated. This is an important GNU
6548 // extension. See GCC PR38377 for discussion.
6549 if (const CallExpr *CallCE
6550 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006551 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6552 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006553 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006554 if (CondResult.Val == 2)
6555 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006556
Richard Smithf48fdb02011-12-09 22:58:01 +00006557 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6558 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006559
John McCalld905f5a2010-05-07 05:32:02 +00006560 if (TrueResult.Val == 2)
6561 return TrueResult;
6562 if (FalseResult.Val == 2)
6563 return FalseResult;
6564 if (CondResult.Val == 1)
6565 return CondResult;
6566 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6567 return NoDiag();
6568 // Rare case where the diagnostics depend on which side is evaluated
6569 // Note that if we get here, CondResult is 0, and at least one of
6570 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006571 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006572 return FalseResult;
6573 }
6574 return TrueResult;
6575 }
6576 case Expr::CXXDefaultArgExprClass:
6577 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6578 case Expr::ChooseExprClass: {
6579 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6580 }
6581 }
6582
David Blaikie30263482012-01-20 21:50:17 +00006583 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006584}
6585
Richard Smithf48fdb02011-12-09 22:58:01 +00006586/// Evaluate an expression as a C++11 integral constant expression.
6587static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6588 const Expr *E,
6589 llvm::APSInt *Value,
6590 SourceLocation *Loc) {
6591 if (!E->getType()->isIntegralOrEnumerationType()) {
6592 if (Loc) *Loc = E->getExprLoc();
6593 return false;
6594 }
6595
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006596 APValue Result;
6597 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006598 return false;
6599
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006600 assert(Result.isInt() && "pointer cast to int is not an ICE");
6601 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006602 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006603}
6604
Richard Smithdd1f29b2011-12-12 09:28:41 +00006605bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006606 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006607 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6608
John McCalld905f5a2010-05-07 05:32:02 +00006609 ICEDiag d = CheckICE(this, Ctx);
6610 if (d.Val != 0) {
6611 if (Loc) *Loc = d.Loc;
6612 return false;
6613 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006614 return true;
6615}
6616
6617bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6618 SourceLocation *Loc, bool isEvaluated) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006619 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006620 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6621
6622 if (!isIntegerConstantExpr(Ctx, Loc))
6623 return false;
6624 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006625 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006626 return true;
6627}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006628
Richard Smith70488e22012-02-14 21:38:30 +00006629bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6630 return CheckICE(this, Ctx).Val == 0;
6631}
6632
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006633bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6634 SourceLocation *Loc) const {
6635 // We support this checking in C++98 mode in order to diagnose compatibility
6636 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006637 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006638
Richard Smith70488e22012-02-14 21:38:30 +00006639 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006640 Expr::EvalStatus Status;
6641 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6642 Status.Diag = &Diags;
6643 EvalInfo Info(Ctx, Status);
6644
6645 APValue Scratch;
6646 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6647
6648 if (!Diags.empty()) {
6649 IsConstExpr = false;
6650 if (Loc) *Loc = Diags[0].first;
6651 } else if (!IsConstExpr) {
6652 // FIXME: This shouldn't happen.
6653 if (Loc) *Loc = getExprLoc();
6654 }
6655
6656 return IsConstExpr;
6657}
Richard Smith745f5142012-01-27 01:14:48 +00006658
6659bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6660 llvm::SmallVectorImpl<
6661 PartialDiagnosticAt> &Diags) {
6662 // FIXME: It would be useful to check constexpr function templates, but at the
6663 // moment the constant expression evaluator cannot cope with the non-rigorous
6664 // ASTs which we build for dependent expressions.
6665 if (FD->isDependentContext())
6666 return true;
6667
6668 Expr::EvalStatus Status;
6669 Status.Diag = &Diags;
6670
6671 EvalInfo Info(FD->getASTContext(), Status);
6672 Info.CheckingPotentialConstantExpression = true;
6673
6674 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6675 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6676
6677 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6678 // is a temporary being used as the 'this' pointer.
6679 LValue This;
6680 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006681 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006682
Richard Smith745f5142012-01-27 01:14:48 +00006683 ArrayRef<const Expr*> Args;
6684
6685 SourceLocation Loc = FD->getLocation();
6686
Richard Smith1aa0be82012-03-03 22:46:17 +00006687 APValue Scratch;
6688 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006689 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006690 else
Richard Smith745f5142012-01-27 01:14:48 +00006691 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6692 Args, FD->getBody(), Info, Scratch);
6693
6694 return Diags.empty();
6695}