blob: e9cce9f23aee254fac5d7245b1e3dd649a0e24de [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"
Mike Stump4572bab2009-05-30 03:56:50 +000047#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000048#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000049
Anders Carlssonc44eec62008-07-03 04:20:39 +000050using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000051using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000052using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000053
Richard Smith83587db2012-02-15 02:18:13 +000054static bool IsGlobalLValue(APValue::LValueBase B);
55
John McCallf4cf1a12010-05-07 17:22:02 +000056namespace {
Richard Smith180f4792011-11-10 06:34:14 +000057 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000058 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000059 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000060
Richard Smith83587db2012-02-15 02:18:13 +000061 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +000062 if (!B) return QualType();
63 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
64 return D->getType();
65 return B.get<const Expr*>()->getType();
66 }
67
Richard Smith180f4792011-11-10 06:34:14 +000068 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000069 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000070 static
Richard Smithf15fda02012-02-02 01:16:57 +000071 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000072 APValue::BaseOrMemberType Value;
73 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000074 return Value;
75 }
76
77 /// Get an LValue path entry, which is known to not be an array index, as a
78 /// field declaration.
Richard Smith83587db2012-02-15 02:18:13 +000079 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000080 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000081 }
82 /// Get an LValue path entry, which is known to not be an array index, as a
83 /// base class declaration.
Richard Smith83587db2012-02-15 02:18:13 +000084 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000085 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000086 }
87 /// Determine whether this LValue path entry for a base class names a virtual
88 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +000089 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000090 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +000091 }
92
Richard Smithb4e85ed2012-01-06 16:39:00 +000093 /// Find the path length and type of the most-derived subobject in the given
94 /// path, and find the size of the containing array, if any.
95 static
96 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
97 ArrayRef<APValue::LValuePathEntry> Path,
98 uint64_t &ArraySize, QualType &Type) {
99 unsigned MostDerivedLength = 0;
100 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000101 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000102 if (Type->isArrayType()) {
103 const ConstantArrayType *CAT =
104 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
105 Type = CAT->getElementType();
106 ArraySize = CAT->getSize().getZExtValue();
107 MostDerivedLength = I + 1;
Richard Smith86024012012-02-18 22:04:06 +0000108 } else if (Type->isAnyComplexType()) {
109 const ComplexType *CT = Type->castAs<ComplexType>();
110 Type = CT->getElementType();
111 ArraySize = 2;
112 MostDerivedLength = I + 1;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000113 } else if (const FieldDecl *FD = getAsField(Path[I])) {
114 Type = FD->getType();
115 ArraySize = 0;
116 MostDerivedLength = I + 1;
117 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000118 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000119 ArraySize = 0;
120 }
Richard Smith9a17a682011-11-07 05:07:52 +0000121 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000122 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000123 }
124
Richard Smithb4e85ed2012-01-06 16:39:00 +0000125 // The order of this enum is important for diagnostics.
126 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000127 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith86024012012-02-18 22:04:06 +0000128 CSK_This, CSK_Real, CSK_Imag
Richard Smithb4e85ed2012-01-06 16:39:00 +0000129 };
130
Richard Smith0a3bdb62011-11-04 02:25:55 +0000131 /// A path from a glvalue to a subobject of that glvalue.
132 struct SubobjectDesignator {
133 /// True if the subobject was named in a manner not supported by C++11. Such
134 /// lvalues can still be folded, but they are not core constant expressions
135 /// and we cannot perform lvalue-to-rvalue conversions on them.
136 bool Invalid : 1;
137
Richard Smithb4e85ed2012-01-06 16:39:00 +0000138 /// Is this a pointer one past the end of an object?
139 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000140
Richard Smithb4e85ed2012-01-06 16:39:00 +0000141 /// The length of the path to the most-derived object of which this is a
142 /// subobject.
143 unsigned MostDerivedPathLength : 30;
144
145 /// The size of the array of which the most-derived object is an element, or
146 /// 0 if the most-derived object is not an array element.
147 uint64_t MostDerivedArraySize;
148
149 /// The type of the most derived object referred to by this address.
150 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000151
Richard Smith9a17a682011-11-07 05:07:52 +0000152 typedef APValue::LValuePathEntry PathEntry;
153
Richard Smith0a3bdb62011-11-04 02:25:55 +0000154 /// The entries on the path from the glvalue to the designated subobject.
155 SmallVector<PathEntry, 8> Entries;
156
Richard Smithb4e85ed2012-01-06 16:39:00 +0000157 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000158
Richard Smithb4e85ed2012-01-06 16:39:00 +0000159 explicit SubobjectDesignator(QualType T)
160 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
161 MostDerivedArraySize(0), MostDerivedType(T) {}
162
163 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
164 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
165 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000166 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000167 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000168 ArrayRef<PathEntry> VEntries = V.getLValuePath();
169 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
170 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000171 MostDerivedPathLength =
172 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
173 V.getLValuePath(), MostDerivedArraySize,
174 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000175 }
176 }
177
Richard Smith0a3bdb62011-11-04 02:25:55 +0000178 void setInvalid() {
179 Invalid = true;
180 Entries.clear();
181 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000182
183 /// Determine whether this is a one-past-the-end pointer.
184 bool isOnePastTheEnd() const {
185 if (IsOnePastTheEnd)
186 return true;
187 if (MostDerivedArraySize &&
188 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
189 return true;
190 return false;
191 }
192
193 /// Check that this refers to a valid subobject.
194 bool isValidSubobject() const {
195 if (Invalid)
196 return false;
197 return !isOnePastTheEnd();
198 }
199 /// Check that this refers to a valid subobject, and if not, produce a
200 /// relevant diagnostic and set the designator as invalid.
201 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
202
203 /// Update this designator to refer to the first element within this array.
204 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000205 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000206 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000207 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000208
209 // This is a most-derived object.
210 MostDerivedType = CAT->getElementType();
211 MostDerivedArraySize = CAT->getSize().getZExtValue();
212 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000213 }
214 /// Update this designator to refer to the given base or member of this
215 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000216 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000217 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000218 APValue::BaseOrMemberType Value(D, Virtual);
219 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000220 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000221
222 // If this isn't a base class, it's a new most-derived object.
223 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
224 MostDerivedType = FD->getType();
225 MostDerivedArraySize = 0;
226 MostDerivedPathLength = Entries.size();
227 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000228 }
Richard Smith86024012012-02-18 22:04:06 +0000229 /// Update this designator to refer to the given complex component.
230 void addComplexUnchecked(QualType EltTy, bool Imag) {
231 PathEntry Entry;
232 Entry.ArrayIndex = Imag;
233 Entries.push_back(Entry);
234
235 // This is technically a most-derived object, though in practice this
236 // is unlikely to matter.
237 MostDerivedType = EltTy;
238 MostDerivedArraySize = 2;
239 MostDerivedPathLength = Entries.size();
240 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000241 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000242 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000243 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000244 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000245 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000246 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000247 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
248 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
249 setInvalid();
250 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000251 return;
252 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000253 // [expr.add]p4: For the purposes of these operators, a pointer to a
254 // nonarray object behaves the same as a pointer to the first element of
255 // an array of length one with the type of the object as its element type.
256 if (IsOnePastTheEnd && N == (uint64_t)-1)
257 IsOnePastTheEnd = false;
258 else if (!IsOnePastTheEnd && N == 1)
259 IsOnePastTheEnd = true;
260 else if (N != 0) {
261 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000262 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000263 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000264 }
265 };
266
Richard Smithd0dccea2011-10-28 22:34:42 +0000267 /// A stack frame in the constexpr call stack.
268 struct CallStackFrame {
269 EvalInfo &Info;
270
271 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000272 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000273
Richard Smith08d6e032011-12-16 19:06:07 +0000274 /// CallLoc - The location of the call expression for this call.
275 SourceLocation CallLoc;
276
277 /// Callee - The function which was called.
278 const FunctionDecl *Callee;
279
Richard Smith83587db2012-02-15 02:18:13 +0000280 /// Index - The call index of this call.
281 unsigned Index;
282
Richard Smith180f4792011-11-10 06:34:14 +0000283 /// This - The binding for the this pointer in this call, if any.
284 const LValue *This;
285
Richard Smithd0dccea2011-10-28 22:34:42 +0000286 /// ParmBindings - Parameter bindings for this function call, indexed by
287 /// parameters' function scope indices.
Richard Smith1aa0be82012-03-03 22:46:17 +0000288 const APValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000289
Richard Smith1aa0be82012-03-03 22:46:17 +0000290 typedef llvm::DenseMap<const Expr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000291 typedef MapTy::const_iterator temp_iterator;
292 /// Temporaries - Temporary lvalues materialized within this stack frame.
293 MapTy Temporaries;
294
Richard Smith08d6e032011-12-16 19:06:07 +0000295 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
296 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000297 const APValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000298 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000299 };
300
Richard Smithdd1f29b2011-12-12 09:28:41 +0000301 /// A partial diagnostic which we might know in advance that we are not going
302 /// to emit.
303 class OptionalDiagnostic {
304 PartialDiagnostic *Diag;
305
306 public:
307 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
308
309 template<typename T>
310 OptionalDiagnostic &operator<<(const T &v) {
311 if (Diag)
312 *Diag << v;
313 return *this;
314 }
Richard Smith789f9b62012-01-31 04:08:20 +0000315
316 OptionalDiagnostic &operator<<(const APSInt &I) {
317 if (Diag) {
318 llvm::SmallVector<char, 32> Buffer;
319 I.toString(Buffer);
320 *Diag << StringRef(Buffer.data(), Buffer.size());
321 }
322 return *this;
323 }
324
325 OptionalDiagnostic &operator<<(const APFloat &F) {
326 if (Diag) {
327 llvm::SmallVector<char, 32> Buffer;
328 F.toString(Buffer);
329 *Diag << StringRef(Buffer.data(), Buffer.size());
330 }
331 return *this;
332 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000333 };
334
Richard Smith83587db2012-02-15 02:18:13 +0000335 /// EvalInfo - This is a private struct used by the evaluator to capture
336 /// information about a subexpression as it is folded. It retains information
337 /// about the AST context, but also maintains information about the folded
338 /// expression.
339 ///
340 /// If an expression could be evaluated, it is still possible it is not a C
341 /// "integer constant expression" or constant expression. If not, this struct
342 /// captures information about how and why not.
343 ///
344 /// One bit of information passed *into* the request for constant folding
345 /// indicates whether the subexpression is "evaluated" or not according to C
346 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
347 /// evaluate the expression regardless of what the RHS is, but C only allows
348 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000349 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000350 ASTContext &Ctx;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000351
Richard Smithbd552ef2011-10-31 05:52:43 +0000352 /// EvalStatus - Contains information about the evaluation.
353 Expr::EvalStatus &EvalStatus;
354
355 /// CurrentCall - The top of the constexpr call stack.
356 CallStackFrame *CurrentCall;
357
Richard Smithbd552ef2011-10-31 05:52:43 +0000358 /// CallStackDepth - The number of calls in the call stack right now.
359 unsigned CallStackDepth;
360
Richard Smith83587db2012-02-15 02:18:13 +0000361 /// NextCallIndex - The next call index to assign.
362 unsigned NextCallIndex;
363
Richard Smith1aa0be82012-03-03 22:46:17 +0000364 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000365 /// OpaqueValues - Values used as the common expression in a
366 /// BinaryConditionalOperator.
367 MapTy OpaqueValues;
368
369 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000370 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000371 CallStackFrame BottomFrame;
372
Richard Smith180f4792011-11-10 06:34:14 +0000373 /// EvaluatingDecl - This is the declaration whose initializer is being
374 /// evaluated, if any.
375 const VarDecl *EvaluatingDecl;
376
377 /// EvaluatingDeclValue - This is the value being constructed for the
378 /// declaration whose initializer is being evaluated, if any.
379 APValue *EvaluatingDeclValue;
380
Richard Smithc1c5f272011-12-13 06:39:58 +0000381 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
382 /// notes attached to it will also be stored, otherwise they will not be.
383 bool HasActiveDiagnostic;
384
Richard Smith745f5142012-01-27 01:14:48 +0000385 /// CheckingPotentialConstantExpression - Are we checking whether the
386 /// expression is a potential constant expression? If so, some diagnostics
387 /// are suppressed.
388 bool CheckingPotentialConstantExpression;
389
Richard Smithbd552ef2011-10-31 05:52:43 +0000390 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000391 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000392 CallStackDepth(0), NextCallIndex(1),
393 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000394 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Argyrios Kyrtzidis649dfbc2012-03-15 18:07:13 +0000395 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000396
Richard Smith1aa0be82012-03-03 22:46:17 +0000397 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
Richard Smithbd552ef2011-10-31 05:52:43 +0000398 MapTy::const_iterator i = OpaqueValues.find(e);
399 if (i == OpaqueValues.end()) return 0;
400 return &i->second;
401 }
402
Richard Smith180f4792011-11-10 06:34:14 +0000403 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
404 EvaluatingDecl = VD;
405 EvaluatingDeclValue = &Value;
406 }
407
David Blaikie4e4d0842012-03-11 07:00:24 +0000408 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000409
Richard Smithc1c5f272011-12-13 06:39:58 +0000410 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000411 // Don't perform any constexpr calls (other than the call we're checking)
412 // when checking a potential constant expression.
413 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
414 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000415 if (NextCallIndex == 0) {
416 // NextCallIndex has wrapped around.
417 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
418 return false;
419 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000420 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
421 return true;
422 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
423 << getLangOpts().ConstexprCallDepth;
424 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000425 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000426
Richard Smith83587db2012-02-15 02:18:13 +0000427 CallStackFrame *getCallFrame(unsigned CallIndex) {
428 assert(CallIndex && "no call index in getCallFrame");
429 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
430 // be null in this loop.
431 CallStackFrame *Frame = CurrentCall;
432 while (Frame->Index > CallIndex)
433 Frame = Frame->Caller;
434 return (Frame->Index == CallIndex) ? Frame : 0;
435 }
436
Richard Smithc1c5f272011-12-13 06:39:58 +0000437 private:
438 /// Add a diagnostic to the diagnostics list.
439 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
440 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
441 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
442 return EvalStatus.Diag->back().second;
443 }
444
Richard Smith08d6e032011-12-16 19:06:07 +0000445 /// Add notes containing a call stack to the current point of evaluation.
446 void addCallStack(unsigned Limit);
447
Richard Smithc1c5f272011-12-13 06:39:58 +0000448 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000449 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000450 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
451 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000452 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000453 // If we have a prior diagnostic, it will be noting that the expression
454 // isn't a constant expression. This diagnostic is more important.
455 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000456 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000457 unsigned CallStackNotes = CallStackDepth - 1;
458 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
459 if (Limit)
460 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000461 if (CheckingPotentialConstantExpression)
462 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000463
Richard Smithc1c5f272011-12-13 06:39:58 +0000464 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000465 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000466 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
467 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000468 if (!CheckingPotentialConstantExpression)
469 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000470 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000471 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000472 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000473 return OptionalDiagnostic();
474 }
475
Richard Smith5cfc7d82012-03-15 04:53:45 +0000476 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
477 = diag::note_invalid_subexpr_in_const_expr,
478 unsigned ExtraNotes = 0) {
479 if (EvalStatus.Diag)
480 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
481 HasActiveDiagnostic = false;
482 return OptionalDiagnostic();
483 }
484
Richard Smithdd1f29b2011-12-12 09:28:41 +0000485 /// Diagnose that the evaluation does not produce a C++11 core constant
486 /// expression.
Richard Smith5cfc7d82012-03-15 04:53:45 +0000487 template<typename LocArg>
488 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000489 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000490 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000491 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000492 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
493 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000494 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000495 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000496 return Diag(Loc, DiagId, ExtraNotes);
497 }
498
499 /// Add a note to a prior diagnostic.
500 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
501 if (!HasActiveDiagnostic)
502 return OptionalDiagnostic();
503 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000504 }
Richard Smith099e7f62011-12-19 06:19:21 +0000505
506 /// Add a stack of notes to a prior diagnostic.
507 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
508 if (HasActiveDiagnostic) {
509 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
510 Diags.begin(), Diags.end());
511 }
512 }
Richard Smith745f5142012-01-27 01:14:48 +0000513
514 /// Should we continue evaluation as much as possible after encountering a
515 /// construct which can't be folded?
516 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000517 return CheckingPotentialConstantExpression &&
518 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000519 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000520 };
Richard Smithf15fda02012-02-02 01:16:57 +0000521
522 /// Object used to treat all foldable expressions as constant expressions.
523 struct FoldConstant {
524 bool Enabled;
525
526 explicit FoldConstant(EvalInfo &Info)
527 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
528 !Info.EvalStatus.HasSideEffects) {
529 }
530 // Treat the value we've computed since this object was created as constant.
531 void Fold(EvalInfo &Info) {
532 if (Enabled && !Info.EvalStatus.Diag->empty() &&
533 !Info.EvalStatus.HasSideEffects)
534 Info.EvalStatus.Diag->clear();
535 }
536 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000537
538 /// RAII object used to suppress diagnostics and side-effects from a
539 /// speculative evaluation.
540 class SpeculativeEvaluationRAII {
541 EvalInfo &Info;
542 Expr::EvalStatus Old;
543
544 public:
545 SpeculativeEvaluationRAII(EvalInfo &Info,
546 llvm::SmallVectorImpl<PartialDiagnosticAt>
547 *NewDiag = 0)
548 : Info(Info), Old(Info.EvalStatus) {
549 Info.EvalStatus.Diag = NewDiag;
550 }
551 ~SpeculativeEvaluationRAII() {
552 Info.EvalStatus = Old;
553 }
554 };
Richard Smith08d6e032011-12-16 19:06:07 +0000555}
Richard Smithbd552ef2011-10-31 05:52:43 +0000556
Richard Smithb4e85ed2012-01-06 16:39:00 +0000557bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
558 CheckSubobjectKind CSK) {
559 if (Invalid)
560 return false;
561 if (isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000562 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000563 << CSK;
564 setInvalid();
565 return false;
566 }
567 return true;
568}
569
570void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
571 const Expr *E, uint64_t N) {
572 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000573 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000574 << static_cast<int>(N) << /*array*/ 0
575 << static_cast<unsigned>(MostDerivedArraySize);
576 else
Richard Smith5cfc7d82012-03-15 04:53:45 +0000577 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000578 << static_cast<int>(N) << /*non-array*/ 1;
579 setInvalid();
580}
581
Richard Smith08d6e032011-12-16 19:06:07 +0000582CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
583 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000584 const APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000585 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000586 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000587 Info.CurrentCall = this;
588 ++Info.CallStackDepth;
589}
590
591CallStackFrame::~CallStackFrame() {
592 assert(Info.CurrentCall == this && "calls retired out of order");
593 --Info.CallStackDepth;
594 Info.CurrentCall = Caller;
595}
596
597/// Produce a string describing the given constexpr call.
598static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
599 unsigned ArgIndex = 0;
600 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000601 !isa<CXXConstructorDecl>(Frame->Callee) &&
602 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000603
604 if (!IsMemberCall)
605 Out << *Frame->Callee << '(';
606
607 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
608 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000609 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000610 Out << ", ";
611
612 const ParmVarDecl *Param = *I;
Richard Smith1aa0be82012-03-03 22:46:17 +0000613 const APValue &Arg = Frame->Arguments[ArgIndex];
614 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smith08d6e032011-12-16 19:06:07 +0000615
616 if (ArgIndex == 0 && IsMemberCall)
617 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000618 }
619
Richard Smith08d6e032011-12-16 19:06:07 +0000620 Out << ')';
621}
622
623void EvalInfo::addCallStack(unsigned Limit) {
624 // Determine which calls to skip, if any.
625 unsigned ActiveCalls = CallStackDepth - 1;
626 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
627 if (Limit && Limit < ActiveCalls) {
628 SkipStart = Limit / 2 + Limit % 2;
629 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000630 }
631
Richard Smith08d6e032011-12-16 19:06:07 +0000632 // Walk the call stack and add the diagnostics.
633 unsigned CallIdx = 0;
634 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
635 Frame = Frame->Caller, ++CallIdx) {
636 // Skip this call?
637 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
638 if (CallIdx == SkipStart) {
639 // Note that we're skipping calls.
640 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
641 << unsigned(ActiveCalls - Limit);
642 }
643 continue;
644 }
645
646 llvm::SmallVector<char, 128> Buffer;
647 llvm::raw_svector_ostream Out(Buffer);
648 describeCall(Frame, Out);
649 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
650 }
651}
652
653namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000654 struct ComplexValue {
655 private:
656 bool IsInt;
657
658 public:
659 APSInt IntReal, IntImag;
660 APFloat FloatReal, FloatImag;
661
662 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
663
664 void makeComplexFloat() { IsInt = false; }
665 bool isComplexFloat() const { return !IsInt; }
666 APFloat &getComplexFloatReal() { return FloatReal; }
667 APFloat &getComplexFloatImag() { return FloatImag; }
668
669 void makeComplexInt() { IsInt = true; }
670 bool isComplexInt() const { return IsInt; }
671 APSInt &getComplexIntReal() { return IntReal; }
672 APSInt &getComplexIntImag() { return IntImag; }
673
Richard Smith1aa0be82012-03-03 22:46:17 +0000674 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000675 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000676 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000677 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000678 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000679 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000680 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000681 assert(v.isComplexFloat() || v.isComplexInt());
682 if (v.isComplexFloat()) {
683 makeComplexFloat();
684 FloatReal = v.getComplexFloatReal();
685 FloatImag = v.getComplexFloatImag();
686 } else {
687 makeComplexInt();
688 IntReal = v.getComplexIntReal();
689 IntImag = v.getComplexIntImag();
690 }
691 }
John McCallf4cf1a12010-05-07 17:22:02 +0000692 };
John McCallefdb83e2010-05-07 21:00:08 +0000693
694 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000695 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000696 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000697 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000698 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000699
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000700 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000701 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000702 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000703 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000704 SubobjectDesignator &getLValueDesignator() { return Designator; }
705 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000706
Richard Smith1aa0be82012-03-03 22:46:17 +0000707 void moveInto(APValue &V) const {
708 if (Designator.Invalid)
709 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
710 else
711 V = APValue(Base, Offset, Designator.Entries,
712 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000713 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000714 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000715 assert(V.isLValue());
716 Base = V.getLValueBase();
717 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000718 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000719 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000720 }
721
Richard Smith83587db2012-02-15 02:18:13 +0000722 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000723 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000724 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000725 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000726 Designator = SubobjectDesignator(getType(B));
727 }
728
729 // Check that this LValue is not based on a null pointer. If it is, produce
730 // a diagnostic and mark the designator as invalid.
731 bool checkNullPointer(EvalInfo &Info, const Expr *E,
732 CheckSubobjectKind CSK) {
733 if (Designator.Invalid)
734 return false;
735 if (!Base) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000736 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000737 << CSK;
738 Designator.setInvalid();
739 return false;
740 }
741 return true;
742 }
743
744 // Check this LValue refers to an object. If not, set the designator to be
745 // invalid and emit a diagnostic.
746 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000747 // Outside C++11, do not build a designator referring to a subobject of
748 // any object: we won't use such a designator for anything.
749 if (!Info.getLangOpts().CPlusPlus0x)
750 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000751 return checkNullPointer(Info, E, CSK) &&
752 Designator.checkSubobject(Info, E, CSK);
753 }
754
755 void addDecl(EvalInfo &Info, const Expr *E,
756 const Decl *D, bool Virtual = false) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000757 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
758 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000759 }
760 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000761 if (checkSubobject(Info, E, CSK_ArrayToPointer))
762 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000763 }
Richard Smith86024012012-02-18 22:04:06 +0000764 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000765 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
766 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000767 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000768 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000769 if (checkNullPointer(Info, E, CSK_ArrayIndex))
770 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000771 }
John McCallefdb83e2010-05-07 21:00:08 +0000772 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000773
774 struct MemberPtr {
775 MemberPtr() {}
776 explicit MemberPtr(const ValueDecl *Decl) :
777 DeclAndIsDerivedMember(Decl, false), Path() {}
778
779 /// The member or (direct or indirect) field referred to by this member
780 /// pointer, or 0 if this is a null member pointer.
781 const ValueDecl *getDecl() const {
782 return DeclAndIsDerivedMember.getPointer();
783 }
784 /// Is this actually a member of some type derived from the relevant class?
785 bool isDerivedMember() const {
786 return DeclAndIsDerivedMember.getInt();
787 }
788 /// Get the class which the declaration actually lives in.
789 const CXXRecordDecl *getContainingRecord() const {
790 return cast<CXXRecordDecl>(
791 DeclAndIsDerivedMember.getPointer()->getDeclContext());
792 }
793
Richard Smith1aa0be82012-03-03 22:46:17 +0000794 void moveInto(APValue &V) const {
795 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000796 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000797 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000798 assert(V.isMemberPointer());
799 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
800 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
801 Path.clear();
802 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
803 Path.insert(Path.end(), P.begin(), P.end());
804 }
805
806 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
807 /// whether the member is a member of some class derived from the class type
808 /// of the member pointer.
809 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
810 /// Path - The path of base/derived classes from the member declaration's
811 /// class (exclusive) to the class type of the member pointer (inclusive).
812 SmallVector<const CXXRecordDecl*, 4> Path;
813
814 /// Perform a cast towards the class of the Decl (either up or down the
815 /// hierarchy).
816 bool castBack(const CXXRecordDecl *Class) {
817 assert(!Path.empty());
818 const CXXRecordDecl *Expected;
819 if (Path.size() >= 2)
820 Expected = Path[Path.size() - 2];
821 else
822 Expected = getContainingRecord();
823 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
824 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
825 // if B does not contain the original member and is not a base or
826 // derived class of the class containing the original member, the result
827 // of the cast is undefined.
828 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
829 // (D::*). We consider that to be a language defect.
830 return false;
831 }
832 Path.pop_back();
833 return true;
834 }
835 /// Perform a base-to-derived member pointer cast.
836 bool castToDerived(const CXXRecordDecl *Derived) {
837 if (!getDecl())
838 return true;
839 if (!isDerivedMember()) {
840 Path.push_back(Derived);
841 return true;
842 }
843 if (!castBack(Derived))
844 return false;
845 if (Path.empty())
846 DeclAndIsDerivedMember.setInt(false);
847 return true;
848 }
849 /// Perform a derived-to-base member pointer cast.
850 bool castToBase(const CXXRecordDecl *Base) {
851 if (!getDecl())
852 return true;
853 if (Path.empty())
854 DeclAndIsDerivedMember.setInt(true);
855 if (isDerivedMember()) {
856 Path.push_back(Base);
857 return true;
858 }
859 return castBack(Base);
860 }
861 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000862
Richard Smithb02e4622012-02-01 01:42:44 +0000863 /// Compare two member pointers, which are assumed to be of the same type.
864 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
865 if (!LHS.getDecl() || !RHS.getDecl())
866 return !LHS.getDecl() && !RHS.getDecl();
867 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
868 return false;
869 return LHS.Path == RHS.Path;
870 }
871
Richard Smithc1c5f272011-12-13 06:39:58 +0000872 /// Kinds of constant expression checking, for diagnostics.
873 enum CheckConstantExpressionKind {
874 CCEK_Constant, ///< A normal constant.
875 CCEK_ReturnValue, ///< A constexpr function return value.
876 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
877 };
John McCallf4cf1a12010-05-07 17:22:02 +0000878}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000879
Richard Smith1aa0be82012-03-03 22:46:17 +0000880static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000881static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
882 const LValue &This, const Expr *E,
883 CheckConstantExpressionKind CCEK = CCEK_Constant,
884 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000885static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
886static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000887static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
888 EvalInfo &Info);
889static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000890static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000891static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000892 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000893static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000894static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000895
896//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000897// Misc utilities
898//===----------------------------------------------------------------------===//
899
Richard Smith180f4792011-11-10 06:34:14 +0000900/// Should this call expression be treated as a string literal?
901static bool IsStringLiteralCall(const CallExpr *E) {
902 unsigned Builtin = E->isBuiltinCall();
903 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
904 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
905}
906
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000907static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000908 // C++11 [expr.const]p3 An address constant expression is a prvalue core
909 // constant expression of pointer type that evaluates to...
910
911 // ... a null pointer value, or a prvalue core constant expression of type
912 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000913 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000914
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000915 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
916 // ... the address of an object with static storage duration,
917 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
918 return VD->hasGlobalStorage();
919 // ... the address of a function,
920 return isa<FunctionDecl>(D);
921 }
922
923 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000924 switch (E->getStmtClass()) {
925 default:
926 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000927 case Expr::CompoundLiteralExprClass: {
928 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
929 return CLE->isFileScope() && CLE->isLValue();
930 }
Richard Smith180f4792011-11-10 06:34:14 +0000931 // A string literal has static storage duration.
932 case Expr::StringLiteralClass:
933 case Expr::PredefinedExprClass:
934 case Expr::ObjCStringLiteralClass:
935 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000936 case Expr::CXXTypeidExprClass:
Francois Pichete275a182012-04-16 04:08:35 +0000937 case Expr::CXXUuidofExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000938 return true;
939 case Expr::CallExprClass:
940 return IsStringLiteralCall(cast<CallExpr>(E));
941 // For GCC compatibility, &&label has static storage duration.
942 case Expr::AddrLabelExprClass:
943 return true;
944 // A Block literal expression may be used as the initialization value for
945 // Block variables at global or local static scope.
946 case Expr::BlockExprClass:
947 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000948 case Expr::ImplicitValueInitExprClass:
949 // FIXME:
950 // We can never form an lvalue with an implicit value initialization as its
951 // base through expression evaluation, so these only appear in one case: the
952 // implicit variable declaration we invent when checking whether a constexpr
953 // constructor can produce a constant expression. We must assume that such
954 // an expression might be a global lvalue.
955 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000956 }
John McCall42c8f872010-05-10 23:27:23 +0000957}
958
Richard Smith83587db2012-02-15 02:18:13 +0000959static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
960 assert(Base && "no location for a null lvalue");
961 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
962 if (VD)
963 Info.Note(VD->getLocation(), diag::note_declared_at);
964 else
965 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
966 diag::note_constexpr_temporary_here);
967}
968
Richard Smith9a17a682011-11-07 05:07:52 +0000969/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000970/// value for an address or reference constant expression. Return true if we
971/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000972static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
973 QualType Type, const LValue &LVal) {
974 bool IsReferenceType = Type->isReferenceType();
975
Richard Smithc1c5f272011-12-13 06:39:58 +0000976 APValue::LValueBase Base = LVal.getLValueBase();
977 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
978
Richard Smithb78ae972012-02-18 04:58:18 +0000979 // Check that the object is a global. Note that the fake 'this' object we
980 // manufacture when checking potential constant expressions is conservatively
981 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000982 if (!IsGlobalLValue(Base)) {
983 if (Info.getLangOpts().CPlusPlus0x) {
984 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000985 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
986 << IsReferenceType << !Designator.Entries.empty()
987 << !!VD << VD;
988 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000989 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000990 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000991 }
Richard Smith61e61622012-01-12 06:08:57 +0000992 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000993 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000994 }
Richard Smith83587db2012-02-15 02:18:13 +0000995 assert((Info.CheckingPotentialConstantExpression ||
996 LVal.getLValueCallIndex() == 0) &&
997 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +0000998
999 // Allow address constant expressions to be past-the-end pointers. This is
1000 // an extension: the standard requires them to point to an object.
1001 if (!IsReferenceType)
1002 return true;
1003
1004 // A reference constant expression must refer to an object.
1005 if (!Base) {
1006 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001007 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001008 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001009 }
1010
Richard Smithc1c5f272011-12-13 06:39:58 +00001011 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001012 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001013 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001014 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001015 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001016 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001017 }
1018
Richard Smith9a17a682011-11-07 05:07:52 +00001019 return true;
1020}
1021
Richard Smith51201882011-12-30 21:15:51 +00001022/// Check that this core constant expression is of literal type, and if not,
1023/// produce an appropriate diagnostic.
1024static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1025 if (!E->isRValue() || E->getType()->isLiteralType())
1026 return true;
1027
1028 // Prvalue constant expressions must be of literal types.
1029 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001030 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001031 << E->getType();
1032 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001033 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001034 return false;
1035}
1036
Richard Smith47a1eed2011-10-29 20:57:55 +00001037/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001038/// constant expression. If not, report an appropriate diagnostic. Does not
1039/// check that the expression is of literal type.
1040static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1041 QualType Type, const APValue &Value) {
1042 // Core issue 1454: For a literal constant expression of array or class type,
1043 // each subobject of its value shall have been initialized by a constant
1044 // expression.
1045 if (Value.isArray()) {
1046 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1047 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1048 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1049 Value.getArrayInitializedElt(I)))
1050 return false;
1051 }
1052 if (!Value.hasArrayFiller())
1053 return true;
1054 return CheckConstantExpression(Info, DiagLoc, EltTy,
1055 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001056 }
Richard Smith83587db2012-02-15 02:18:13 +00001057 if (Value.isUnion() && Value.getUnionField()) {
1058 return CheckConstantExpression(Info, DiagLoc,
1059 Value.getUnionField()->getType(),
1060 Value.getUnionValue());
1061 }
1062 if (Value.isStruct()) {
1063 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1064 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1065 unsigned BaseIndex = 0;
1066 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1067 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1068 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1069 Value.getStructBase(BaseIndex)))
1070 return false;
1071 }
1072 }
1073 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1074 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001075 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1076 Value.getStructField(I->getFieldIndex())))
Richard Smith83587db2012-02-15 02:18:13 +00001077 return false;
1078 }
1079 }
1080
1081 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001082 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001083 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001084 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1085 }
1086
1087 // Everything else is fine.
1088 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001089}
1090
Richard Smith9e36b532011-10-31 05:11:32 +00001091const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001092 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001093}
1094
1095static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001096 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001097}
1098
Richard Smith65ac5982011-11-01 21:06:14 +00001099static bool IsWeakLValue(const LValue &Value) {
1100 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001101 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001102}
1103
Richard Smith1aa0be82012-03-03 22:46:17 +00001104static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001105 // A null base expression indicates a null pointer. These are always
1106 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001107 if (!Value.getLValueBase()) {
1108 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001109 return true;
1110 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001111
Richard Smithe24f5fc2011-11-17 22:56:20 +00001112 // We have a non-null base. These are generally known to be true, but if it's
1113 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001114 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001115 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001116 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001117}
1118
Richard Smith1aa0be82012-03-03 22:46:17 +00001119static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001120 switch (Val.getKind()) {
1121 case APValue::Uninitialized:
1122 return false;
1123 case APValue::Int:
1124 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001125 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001126 case APValue::Float:
1127 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001128 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001129 case APValue::ComplexInt:
1130 Result = Val.getComplexIntReal().getBoolValue() ||
1131 Val.getComplexIntImag().getBoolValue();
1132 return true;
1133 case APValue::ComplexFloat:
1134 Result = !Val.getComplexFloatReal().isZero() ||
1135 !Val.getComplexFloatImag().isZero();
1136 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001137 case APValue::LValue:
1138 return EvalPointerValueAsBool(Val, Result);
1139 case APValue::MemberPointer:
1140 Result = Val.getMemberPointerDecl();
1141 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001142 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001143 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001144 case APValue::Struct:
1145 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001146 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001147 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001148 }
1149
Richard Smithc49bd112011-10-28 17:51:58 +00001150 llvm_unreachable("unknown APValue kind");
1151}
1152
1153static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1154 EvalInfo &Info) {
1155 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001156 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001157 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001158 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001159 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001160}
1161
Richard Smithc1c5f272011-12-13 06:39:58 +00001162template<typename T>
1163static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1164 const T &SrcValue, QualType DestType) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001165 Info.Diag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001166 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001167 return false;
1168}
1169
1170static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1171 QualType SrcType, const APFloat &Value,
1172 QualType DestType, APSInt &Result) {
1173 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001174 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001175 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Richard Smithc1c5f272011-12-13 06:39:58 +00001177 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001178 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001179 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1180 & APFloat::opInvalidOp)
1181 return HandleOverflow(Info, E, Value, DestType);
1182 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001183}
1184
Richard Smithc1c5f272011-12-13 06:39:58 +00001185static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1186 QualType SrcType, QualType DestType,
1187 APFloat &Result) {
1188 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001189 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001190 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1191 APFloat::rmNearestTiesToEven, &ignored)
1192 & APFloat::opOverflow)
1193 return HandleOverflow(Info, E, Value, DestType);
1194 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001195}
1196
Richard Smithf72fccf2012-01-30 22:27:01 +00001197static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1198 QualType DestType, QualType SrcType,
1199 APSInt &Value) {
1200 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001201 APSInt Result = Value;
1202 // Figure out if this is a truncate, extend or noop cast.
1203 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001204 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001205 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001206 return Result;
1207}
1208
Richard Smithc1c5f272011-12-13 06:39:58 +00001209static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1210 QualType SrcType, const APSInt &Value,
1211 QualType DestType, APFloat &Result) {
1212 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1213 if (Result.convertFromAPInt(Value, Value.isSigned(),
1214 APFloat::rmNearestTiesToEven)
1215 & APFloat::opOverflow)
1216 return HandleOverflow(Info, E, Value, DestType);
1217 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001218}
1219
Eli Friedmane6a24e82011-12-22 03:51:45 +00001220static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1221 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001222 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001223 if (!Evaluate(SVal, Info, E))
1224 return false;
1225 if (SVal.isInt()) {
1226 Res = SVal.getInt();
1227 return true;
1228 }
1229 if (SVal.isFloat()) {
1230 Res = SVal.getFloat().bitcastToAPInt();
1231 return true;
1232 }
1233 if (SVal.isVector()) {
1234 QualType VecTy = E->getType();
1235 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1236 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1237 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1238 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1239 Res = llvm::APInt::getNullValue(VecSize);
1240 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1241 APValue &Elt = SVal.getVectorElt(i);
1242 llvm::APInt EltAsInt;
1243 if (Elt.isInt()) {
1244 EltAsInt = Elt.getInt();
1245 } else if (Elt.isFloat()) {
1246 EltAsInt = Elt.getFloat().bitcastToAPInt();
1247 } else {
1248 // Don't try to handle vectors of anything other than int or float
1249 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001250 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001251 return false;
1252 }
1253 unsigned BaseEltSize = EltAsInt.getBitWidth();
1254 if (BigEndian)
1255 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1256 else
1257 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1258 }
1259 return true;
1260 }
1261 // Give up if the input isn't an int, float, or vector. For example, we
1262 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001263 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001264 return false;
1265}
1266
Richard Smithb4e85ed2012-01-06 16:39:00 +00001267/// Cast an lvalue referring to a base subobject to a derived class, by
1268/// truncating the lvalue's path to the given length.
1269static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1270 const RecordDecl *TruncatedType,
1271 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001272 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001273
1274 // Check we actually point to a derived class object.
1275 if (TruncatedElements == D.Entries.size())
1276 return true;
1277 assert(TruncatedElements >= D.MostDerivedPathLength &&
1278 "not casting to a derived class");
1279 if (!Result.checkSubobject(Info, E, CSK_Derived))
1280 return false;
1281
1282 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001283 const RecordDecl *RD = TruncatedType;
1284 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCall8d59dee2012-05-01 00:38:49 +00001285 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001286 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1287 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001288 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001289 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001290 else
Richard Smith180f4792011-11-10 06:34:14 +00001291 Result.Offset -= Layout.getBaseClassOffset(Base);
1292 RD = Base;
1293 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001294 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001295 return true;
1296}
1297
John McCall8d59dee2012-05-01 00:38:49 +00001298static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001299 const CXXRecordDecl *Derived,
1300 const CXXRecordDecl *Base,
1301 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001302 if (!RL) {
1303 if (Derived->isInvalidDecl()) return false;
1304 RL = &Info.Ctx.getASTRecordLayout(Derived);
1305 }
1306
Richard Smith180f4792011-11-10 06:34:14 +00001307 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001308 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCall8d59dee2012-05-01 00:38:49 +00001309 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001310}
1311
Richard Smithb4e85ed2012-01-06 16:39:00 +00001312static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001313 const CXXRecordDecl *DerivedDecl,
1314 const CXXBaseSpecifier *Base) {
1315 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1316
John McCall8d59dee2012-05-01 00:38:49 +00001317 if (!Base->isVirtual())
1318 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001319
Richard Smithb4e85ed2012-01-06 16:39:00 +00001320 SubobjectDesignator &D = Obj.Designator;
1321 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001322 return false;
1323
Richard Smithb4e85ed2012-01-06 16:39:00 +00001324 // Extract most-derived object and corresponding type.
1325 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1326 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1327 return false;
1328
1329 // Find the virtual base class.
John McCall8d59dee2012-05-01 00:38:49 +00001330 if (DerivedDecl->isInvalidDecl()) return false;
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.
John McCall8d59dee2012-05-01 00:38:49 +00001339static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001340 const FieldDecl *FD,
1341 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001342 if (!RL) {
1343 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001344 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCall8d59dee2012-05-01 00:38:49 +00001345 }
Richard Smith180f4792011-11-10 06:34:14 +00001346
1347 unsigned I = FD->getFieldIndex();
1348 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001349 LVal.addDecl(Info, E, FD);
John McCall8d59dee2012-05-01 00:38:49 +00001350 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001351}
1352
Richard Smithd9b02e72012-01-25 22:15:11 +00001353/// Update LVal to refer to the given indirect field.
John McCall8d59dee2012-05-01 00:38:49 +00001354static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smithd9b02e72012-01-25 22:15:11 +00001355 LValue &LVal,
1356 const IndirectFieldDecl *IFD) {
1357 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1358 CE = IFD->chain_end(); C != CE; ++C)
John McCall8d59dee2012-05-01 00:38:49 +00001359 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1360 return false;
1361 return true;
Richard Smithd9b02e72012-01-25 22:15:11 +00001362}
1363
Richard Smith180f4792011-11-10 06:34:14 +00001364/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001365static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1366 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001367 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1368 // extension.
1369 if (Type->isVoidType() || Type->isFunctionType()) {
1370 Size = CharUnits::One();
1371 return true;
1372 }
1373
1374 if (!Type->isConstantSizeType()) {
1375 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001376 // FIXME: Better diagnostic.
1377 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001378 return false;
1379 }
1380
1381 Size = Info.Ctx.getTypeSizeInChars(Type);
1382 return true;
1383}
1384
1385/// Update a pointer value to model pointer arithmetic.
1386/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001387/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001388/// \param LVal - The pointer value to be updated.
1389/// \param EltTy - The pointee type represented by LVal.
1390/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001391static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1392 LValue &LVal, QualType EltTy,
1393 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001394 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001395 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001396 return false;
1397
1398 // Compute the new offset in the appropriate width.
1399 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001400 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001401 return true;
1402}
1403
Richard Smith86024012012-02-18 22:04:06 +00001404/// Update an lvalue to refer to a component of a complex number.
1405/// \param Info - Information about the ongoing evaluation.
1406/// \param LVal - The lvalue to be updated.
1407/// \param EltTy - The complex number's component type.
1408/// \param Imag - False for the real component, true for the imaginary.
1409static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1410 LValue &LVal, QualType EltTy,
1411 bool Imag) {
1412 if (Imag) {
1413 CharUnits SizeOfComponent;
1414 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1415 return false;
1416 LVal.Offset += SizeOfComponent;
1417 }
1418 LVal.addComplex(Info, E, EltTy, Imag);
1419 return true;
1420}
1421
Richard Smith03f96112011-10-24 17:54:18 +00001422/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001423static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1424 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001425 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001426 // If this is a parameter to an active constexpr function call, perform
1427 // argument substitution.
1428 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001429 // Assume arguments of a potential constant expression are unknown
1430 // constant expressions.
1431 if (Info.CheckingPotentialConstantExpression)
1432 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001433 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001434 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001435 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001436 }
Richard Smith177dce72011-11-01 16:57:24 +00001437 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1438 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001439 }
Richard Smith03f96112011-10-24 17:54:18 +00001440
Richard Smith099e7f62011-12-19 06:19:21 +00001441 // Dig out the initializer, and use the declaration which it's attached to.
1442 const Expr *Init = VD->getAnyInitializer(VD);
1443 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001444 // If we're checking a potential constant expression, the variable could be
1445 // initialized later.
1446 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001447 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001448 return false;
1449 }
1450
Richard Smith180f4792011-11-10 06:34:14 +00001451 // If we're currently evaluating the initializer of this declaration, use that
1452 // in-flight value.
1453 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001454 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001455 return !Result.isUninit();
1456 }
1457
Richard Smith65ac5982011-11-01 21:06:14 +00001458 // Never evaluate the initializer of a weak variable. We can't be sure that
1459 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001460 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001461 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001462 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001463 }
Richard Smith65ac5982011-11-01 21:06:14 +00001464
Richard Smith099e7f62011-12-19 06:19:21 +00001465 // Check that we can fold the initializer. In C++, we will have already done
1466 // this in the cases where it matters for conformance.
1467 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1468 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001469 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001470 Notes.size() + 1) << VD;
1471 Info.Note(VD->getLocation(), diag::note_declared_at);
1472 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001473 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001474 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001475 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001476 Notes.size() + 1) << VD;
1477 Info.Note(VD->getLocation(), diag::note_declared_at);
1478 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001479 }
Richard Smith03f96112011-10-24 17:54:18 +00001480
Richard Smith1aa0be82012-03-03 22:46:17 +00001481 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001482 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001483}
1484
Richard Smithc49bd112011-10-28 17:51:58 +00001485static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001486 Qualifiers Quals = T.getQualifiers();
1487 return Quals.hasConst() && !Quals.hasVolatile();
1488}
1489
Richard Smith59efe262011-11-11 04:05:33 +00001490/// Get the base index of the given base class within an APValue representing
1491/// the given derived class.
1492static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1493 const CXXRecordDecl *Base) {
1494 Base = Base->getCanonicalDecl();
1495 unsigned Index = 0;
1496 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1497 E = Derived->bases_end(); I != E; ++I, ++Index) {
1498 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1499 return Index;
1500 }
1501
1502 llvm_unreachable("base class missing from derived class's bases list");
1503}
1504
Richard Smithfe587202012-04-15 02:50:59 +00001505/// Extract the value of a character from a string literal. CharType is used to
1506/// determine the expected signedness of the result -- a string literal used to
1507/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1508/// of the wrong signedness.
Richard Smithf3908f22012-02-17 03:35:37 +00001509static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smithfe587202012-04-15 02:50:59 +00001510 uint64_t Index, QualType CharType) {
Richard Smithf3908f22012-02-17 03:35:37 +00001511 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1512 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1513 assert(S && "unexpected string literal expression kind");
Richard Smithfe587202012-04-15 02:50:59 +00001514 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smithf3908f22012-02-17 03:35:37 +00001515
1516 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smithfe587202012-04-15 02:50:59 +00001517 CharType->isUnsignedIntegerType());
Richard Smithf3908f22012-02-17 03:35:37 +00001518 if (Index < S->getLength())
1519 Value = S->getCodeUnit(Index);
1520 return Value;
1521}
1522
Richard Smithcc5d4f62011-11-07 09:22:26 +00001523/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001524static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001525 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001526 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001527 if (Sub.Invalid)
1528 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001529 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001530 if (Sub.isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001531 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001532 (unsigned)diag::note_constexpr_read_past_end :
1533 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001534 return false;
1535 }
Richard Smithf64699e2011-11-11 08:28:03 +00001536 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001537 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001538 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1539 // This object might be initialized later.
1540 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001541
Richard Smith0069b842012-03-10 00:28:11 +00001542 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001543 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001544 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001545 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001546 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001547 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001548 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001549 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001550 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001551 // Note, it should not be possible to form a pointer with a valid
1552 // designator which points more than one past the end of the array.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001553 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001554 (unsigned)diag::note_constexpr_read_past_end :
1555 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001556 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001557 }
Richard Smithf3908f22012-02-17 03:35:37 +00001558 // An array object is represented as either an Array APValue or as an
1559 // LValue which refers to a string literal.
1560 if (O->isLValue()) {
1561 assert(I == N - 1 && "extracting subobject of character?");
1562 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001563 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithfe587202012-04-15 02:50:59 +00001564 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smithf3908f22012-02-17 03:35:37 +00001565 return true;
1566 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001567 O = &O->getArrayInitializedElt(Index);
1568 else
1569 O = &O->getArrayFiller();
1570 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001571 } else if (ObjType->isAnyComplexType()) {
1572 // Next subobject is a complex number.
1573 uint64_t Index = Sub.Entries[I].ArrayIndex;
1574 if (Index > 1) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001575 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Richard Smith86024012012-02-18 22:04:06 +00001576 (unsigned)diag::note_constexpr_read_past_end :
1577 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1578 return false;
1579 }
1580 assert(I == N - 1 && "extracting subobject of scalar?");
1581 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001582 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001583 : O->getComplexIntReal());
1584 } else {
1585 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001586 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001587 : O->getComplexFloatReal());
1588 }
1589 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001590 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001591 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001592 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001593 << Field;
1594 Info.Note(Field->getLocation(), diag::note_declared_at);
1595 return false;
1596 }
1597
Richard Smith180f4792011-11-10 06:34:14 +00001598 // Next subobject is a class, struct or union field.
1599 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1600 if (RD->isUnion()) {
1601 const FieldDecl *UnionField = O->getUnionField();
1602 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001603 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001604 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001605 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001606 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001607 }
Richard Smith180f4792011-11-10 06:34:14 +00001608 O = &O->getUnionValue();
1609 } else
1610 O = &O->getStructField(Field->getFieldIndex());
1611 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001612
1613 if (ObjType.isVolatileQualified()) {
1614 if (Info.getLangOpts().CPlusPlus) {
1615 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001616 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001617 << 2 << Field;
1618 Info.Note(Field->getLocation(), diag::note_declared_at);
1619 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001620 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001621 }
1622 return false;
1623 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001624 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001625 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001626 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1627 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1628 O = &O->getStructBase(getBaseIndex(Derived, Base));
1629 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001630 }
Richard Smith180f4792011-11-10 06:34:14 +00001631
Richard Smithf48fdb02011-12-09 22:58:01 +00001632 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001633 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001634 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001635 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001636 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001637 }
1638
Richard Smith0069b842012-03-10 00:28:11 +00001639 // This may look super-stupid, but it serves an important purpose: if we just
1640 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1641 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1642 // object, which is destroyed by Tmp's destructor.
1643 APValue Tmp;
1644 O->swap(Tmp);
1645 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001646 return true;
1647}
1648
Richard Smithf15fda02012-02-02 01:16:57 +00001649/// Find the position where two subobject designators diverge, or equivalently
1650/// the length of the common initial subsequence.
1651static unsigned FindDesignatorMismatch(QualType ObjType,
1652 const SubobjectDesignator &A,
1653 const SubobjectDesignator &B,
1654 bool &WasArrayIndex) {
1655 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1656 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001657 if (!ObjType.isNull() &&
1658 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001659 // Next subobject is an array element.
1660 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1661 WasArrayIndex = true;
1662 return I;
1663 }
Richard Smith86024012012-02-18 22:04:06 +00001664 if (ObjType->isAnyComplexType())
1665 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1666 else
1667 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001668 } else {
1669 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1670 WasArrayIndex = false;
1671 return I;
1672 }
1673 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1674 // Next subobject is a field.
1675 ObjType = FD->getType();
1676 else
1677 // Next subobject is a base class.
1678 ObjType = QualType();
1679 }
1680 }
1681 WasArrayIndex = false;
1682 return I;
1683}
1684
1685/// Determine whether the given subobject designators refer to elements of the
1686/// same array object.
1687static bool AreElementsOfSameArray(QualType ObjType,
1688 const SubobjectDesignator &A,
1689 const SubobjectDesignator &B) {
1690 if (A.Entries.size() != B.Entries.size())
1691 return false;
1692
1693 bool IsArray = A.MostDerivedArraySize != 0;
1694 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1695 // A is a subobject of the array element.
1696 return false;
1697
1698 // If A (and B) designates an array element, the last entry will be the array
1699 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1700 // of length 1' case, and the entire path must match.
1701 bool WasArrayIndex;
1702 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1703 return CommonLength >= A.Entries.size() - IsArray;
1704}
1705
Richard Smith180f4792011-11-10 06:34:14 +00001706/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1707/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1708/// for looking up the glvalue referred to by an entity of reference type.
1709///
1710/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001711/// \param Conv - The expression for which we are performing the conversion.
1712/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001713/// \param Type - The type we expect this conversion to produce, before
1714/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001715/// \param LVal - The glvalue on which we are attempting to perform this action.
1716/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001717static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1718 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001719 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001720 if (LVal.Designator.Invalid)
1721 // A diagnostic will have already been produced.
1722 return false;
1723
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001724 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001725
Richard Smithf48fdb02011-12-09 22:58:01 +00001726 if (!LVal.Base) {
1727 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001728 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001729 return false;
1730 }
1731
Richard Smith83587db2012-02-15 02:18:13 +00001732 CallStackFrame *Frame = 0;
1733 if (LVal.CallIndex) {
1734 Frame = Info.getCallFrame(LVal.CallIndex);
1735 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001736 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001737 NoteLValueLocation(Info, LVal.Base);
1738 return false;
1739 }
1740 }
1741
Richard Smith7098cbd2011-12-21 05:04:46 +00001742 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1743 // is not a constant expression (even if the object is non-volatile). We also
1744 // apply this rule to C++98, in order to conform to the expected 'volatile'
1745 // semantics.
1746 if (Type.isVolatileQualified()) {
1747 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001748 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001749 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001750 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001751 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001752 }
Richard Smithc49bd112011-10-28 17:51:58 +00001753
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001754 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001755 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1756 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001757 // expressions are constant expressions too. Inside constexpr functions,
1758 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001759 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001760 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregord2008e22012-04-06 22:40:38 +00001761 if (VD) {
1762 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1763 VD = VDef;
1764 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001765 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001766 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001767 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001768 }
1769
Richard Smith7098cbd2011-12-21 05:04:46 +00001770 // DR1313: If the object is volatile-qualified but the glvalue was not,
1771 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001772 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001773 if (VT.isVolatileQualified()) {
1774 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001775 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001776 Info.Note(VD->getLocation(), diag::note_declared_at);
1777 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001778 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001779 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001780 return false;
1781 }
1782
1783 if (!isa<ParmVarDecl>(VD)) {
1784 if (VD->isConstexpr()) {
1785 // OK, we can read this variable.
1786 } else if (VT->isIntegralOrEnumerationType()) {
1787 if (!VT.isConstQualified()) {
1788 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001789 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001790 Info.Note(VD->getLocation(), diag::note_declared_at);
1791 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001792 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001793 }
1794 return false;
1795 }
1796 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1797 // We support folding of const floating-point types, in order to make
1798 // static const data members of such types (supported as an extension)
1799 // more useful.
1800 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001801 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001802 Info.Note(VD->getLocation(), diag::note_declared_at);
1803 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001804 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001805 }
1806 } else {
1807 // FIXME: Allow folding of values of any literal type in all languages.
1808 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001809 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001810 Info.Note(VD->getLocation(), diag::note_declared_at);
1811 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001812 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001813 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001814 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001815 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001816 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001817
Richard Smithf48fdb02011-12-09 22:58:01 +00001818 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001819 return false;
1820
Richard Smith47a1eed2011-10-29 20:57:55 +00001821 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001822 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001823
1824 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1825 // conversion. This happens when the declaration and the lvalue should be
1826 // considered synonymous, for instance when initializing an array of char
1827 // from a string literal. Continue as if the initializer lvalue was the
1828 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001829 assert(RVal.getLValueOffset().isZero() &&
1830 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001831 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001832
1833 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1834 Frame = Info.getCallFrame(CallIndex);
1835 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001836 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001837 NoteLValueLocation(Info, RVal.getLValueBase());
1838 return false;
1839 }
1840 } else {
1841 Frame = 0;
1842 }
Richard Smithc49bd112011-10-28 17:51:58 +00001843 }
1844
Richard Smith7098cbd2011-12-21 05:04:46 +00001845 // Volatile temporary objects cannot be read in constant expressions.
1846 if (Base->getType().isVolatileQualified()) {
1847 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001848 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001849 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1850 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001851 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001852 }
1853 return false;
1854 }
1855
Richard Smithcc5d4f62011-11-07 09:22:26 +00001856 if (Frame) {
1857 // If this is a temporary expression with a nontrivial initializer, grab the
1858 // value from the relevant stack frame.
1859 RVal = Frame->Temporaries[Base];
1860 } else if (const CompoundLiteralExpr *CLE
1861 = dyn_cast<CompoundLiteralExpr>(Base)) {
1862 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1863 // initializer until now for such expressions. Such an expression can't be
1864 // an ICE in C, so this only matters for fold.
1865 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1866 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1867 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001868 } else if (isa<StringLiteral>(Base)) {
1869 // We represent a string literal array as an lvalue pointing at the
1870 // corresponding expression, rather than building an array of chars.
1871 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001872 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001873 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001874 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001875 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001876 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001877
Richard Smithf48fdb02011-12-09 22:58:01 +00001878 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1879 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001880}
1881
Richard Smith59efe262011-11-11 04:05:33 +00001882/// Build an lvalue for the object argument of a member function call.
1883static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1884 LValue &This) {
1885 if (Object->getType()->isPointerType())
1886 return EvaluatePointer(Object, This, Info);
1887
1888 if (Object->isGLValue())
1889 return EvaluateLValue(Object, This, Info);
1890
Richard Smithe24f5fc2011-11-17 22:56:20 +00001891 if (Object->getType()->isLiteralType())
1892 return EvaluateTemporary(Object, This, Info);
1893
1894 return false;
1895}
1896
1897/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1898/// lvalue referring to the result.
1899///
1900/// \param Info - Information about the ongoing evaluation.
1901/// \param BO - The member pointer access operation.
1902/// \param LV - Filled in with a reference to the resulting object.
1903/// \param IncludeMember - Specifies whether the member itself is included in
1904/// the resulting LValue subobject designator. This is not possible when
1905/// creating a bound member function.
1906/// \return The field or method declaration to which the member pointer refers,
1907/// or 0 if evaluation fails.
1908static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1909 const BinaryOperator *BO,
1910 LValue &LV,
1911 bool IncludeMember = true) {
1912 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1913
Richard Smith745f5142012-01-27 01:14:48 +00001914 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1915 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001916 return 0;
1917
1918 MemberPtr MemPtr;
1919 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1920 return 0;
1921
1922 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1923 // member value, the behavior is undefined.
1924 if (!MemPtr.getDecl())
1925 return 0;
1926
Richard Smith745f5142012-01-27 01:14:48 +00001927 if (!EvalObjOK)
1928 return 0;
1929
Richard Smithe24f5fc2011-11-17 22:56:20 +00001930 if (MemPtr.isDerivedMember()) {
1931 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001932 // The end of the derived-to-base path for the base object must match the
1933 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001934 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001935 LV.Designator.Entries.size())
1936 return 0;
1937 unsigned PathLengthToMember =
1938 LV.Designator.Entries.size() - MemPtr.Path.size();
1939 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1940 const CXXRecordDecl *LVDecl = getAsBaseClass(
1941 LV.Designator.Entries[PathLengthToMember + I]);
1942 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1943 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1944 return 0;
1945 }
1946
1947 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001948 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1949 PathLengthToMember))
1950 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001951 } else if (!MemPtr.Path.empty()) {
1952 // Extend the LValue path with the member pointer's path.
1953 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1954 MemPtr.Path.size() + IncludeMember);
1955
1956 // Walk down to the appropriate base class.
1957 QualType LVType = BO->getLHS()->getType();
1958 if (const PointerType *PT = LVType->getAs<PointerType>())
1959 LVType = PT->getPointeeType();
1960 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1961 assert(RD && "member pointer access on non-class-type expression");
1962 // The first class in the path is that of the lvalue.
1963 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1964 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCall8d59dee2012-05-01 00:38:49 +00001965 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1966 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001967 RD = Base;
1968 }
1969 // Finally cast to the class containing the member.
John McCall8d59dee2012-05-01 00:38:49 +00001970 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1971 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001972 }
1973
1974 // Add the member. Note that we cannot build bound member functions here.
1975 if (IncludeMember) {
John McCall8d59dee2012-05-01 00:38:49 +00001976 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
1977 if (!HandleLValueMember(Info, BO, LV, FD))
1978 return 0;
1979 } else if (const IndirectFieldDecl *IFD =
1980 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
1981 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
1982 return 0;
1983 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00001984 llvm_unreachable("can't construct reference to bound member function");
John McCall8d59dee2012-05-01 00:38:49 +00001985 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001986 }
1987
1988 return MemPtr.getDecl();
1989}
1990
1991/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1992/// the provided lvalue, which currently refers to the base object.
1993static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1994 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001995 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001996 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001997 return false;
1998
Richard Smithb4e85ed2012-01-06 16:39:00 +00001999 QualType TargetQT = E->getType();
2000 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2001 TargetQT = PT->getPointeeType();
2002
2003 // Check this cast lands within the final derived-to-base subobject path.
2004 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002005 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002006 << D.MostDerivedType << TargetQT;
2007 return false;
2008 }
2009
Richard Smithe24f5fc2011-11-17 22:56:20 +00002010 // Check the type of the final cast. We don't need to check the path,
2011 // since a cast can only be formed if the path is unique.
2012 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002013 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2014 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002015 if (NewEntriesSize == D.MostDerivedPathLength)
2016 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2017 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002018 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002019 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002020 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002021 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002022 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002023 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002024
2025 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002026 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002027}
2028
Mike Stumpc4c90452009-10-27 22:09:17 +00002029namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002030enum EvalStmtResult {
2031 /// Evaluation failed.
2032 ESR_Failed,
2033 /// Hit a 'return' statement.
2034 ESR_Returned,
2035 /// Evaluation succeeded.
2036 ESR_Succeeded
2037};
2038}
2039
2040// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002041static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002042 const Stmt *S) {
2043 switch (S->getStmtClass()) {
2044 default:
2045 return ESR_Failed;
2046
2047 case Stmt::NullStmtClass:
2048 case Stmt::DeclStmtClass:
2049 return ESR_Succeeded;
2050
Richard Smithc1c5f272011-12-13 06:39:58 +00002051 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002052 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002053 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002054 return ESR_Failed;
2055 return ESR_Returned;
2056 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002057
2058 case Stmt::CompoundStmtClass: {
2059 const CompoundStmt *CS = cast<CompoundStmt>(S);
2060 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2061 BE = CS->body_end(); BI != BE; ++BI) {
2062 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2063 if (ESR != ESR_Succeeded)
2064 return ESR;
2065 }
2066 return ESR_Succeeded;
2067 }
2068 }
2069}
2070
Richard Smith61802452011-12-22 02:22:31 +00002071/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2072/// default constructor. If so, we'll fold it whether or not it's marked as
2073/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2074/// so we need special handling.
2075static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002076 const CXXConstructorDecl *CD,
2077 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002078 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2079 return false;
2080
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002081 // Value-initialization does not call a trivial default constructor, so such a
2082 // call is a core constant expression whether or not the constructor is
2083 // constexpr.
2084 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002085 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002086 // FIXME: If DiagDecl is an implicitly-declared special member function,
2087 // we should be much more explicit about why it's not constexpr.
2088 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2089 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2090 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002091 } else {
2092 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2093 }
2094 }
2095 return true;
2096}
2097
Richard Smithc1c5f272011-12-13 06:39:58 +00002098/// CheckConstexprFunction - Check that a function can be called in a constant
2099/// expression.
2100static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2101 const FunctionDecl *Declaration,
2102 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002103 // Potential constant expressions can contain calls to declared, but not yet
2104 // defined, constexpr functions.
2105 if (Info.CheckingPotentialConstantExpression && !Definition &&
2106 Declaration->isConstexpr())
2107 return false;
2108
Richard Smithc1c5f272011-12-13 06:39:58 +00002109 // Can we evaluate this function call?
2110 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2111 return true;
2112
2113 if (Info.getLangOpts().CPlusPlus0x) {
2114 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002115 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2116 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002117 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2118 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2119 << DiagDecl;
2120 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2121 } else {
2122 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2123 }
2124 return false;
2125}
2126
Richard Smith180f4792011-11-10 06:34:14 +00002127namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002128typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002129}
2130
2131/// EvaluateArgs - Evaluate the arguments to a function call.
2132static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2133 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002134 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002135 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002136 I != E; ++I) {
2137 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2138 // If we're checking for a potential constant expression, evaluate all
2139 // initializers even if some of them fail.
2140 if (!Info.keepEvaluatingAfterFailure())
2141 return false;
2142 Success = false;
2143 }
2144 }
2145 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002146}
2147
Richard Smithd0dccea2011-10-28 22:34:42 +00002148/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002149static bool HandleFunctionCall(SourceLocation CallLoc,
2150 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002151 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +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;
Richard Smithd0dccea2011-10-28 22:34:42 +00002156
Richard Smith745f5142012-01-27 01:14:48 +00002157 if (!Info.CheckCallLimit(CallLoc))
2158 return false;
2159
2160 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002161 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2162}
2163
Richard Smith180f4792011-11-10 06:34:14 +00002164/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002165static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002166 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002167 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002168 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002169 ArgVector ArgValues(Args.size());
2170 if (!EvaluateArgs(Args, ArgValues, Info))
2171 return false;
2172
Richard Smith745f5142012-01-27 01:14:48 +00002173 if (!Info.CheckCallLimit(CallLoc))
2174 return false;
2175
Richard Smith86c3ae42012-02-13 03:54:03 +00002176 const CXXRecordDecl *RD = Definition->getParent();
2177 if (RD->getNumVBases()) {
2178 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2179 return false;
2180 }
2181
Richard Smith745f5142012-01-27 01:14:48 +00002182 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002183
2184 // If it's a delegating constructor, just delegate.
2185 if (Definition->isDelegatingConstructor()) {
2186 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002187 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002188 }
2189
Richard Smith610a60c2012-01-10 04:32:03 +00002190 // For a trivial copy or move constructor, perform an APValue copy. This is
2191 // essential for unions, where the operations performed by the constructor
2192 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002193 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002194 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2195 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002196 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002197 RHS.setFrom(Info.Ctx, ArgValues[0]);
2198 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2199 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002200 }
2201
2202 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002203 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002204 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2205 std::distance(RD->field_begin(), RD->field_end()));
2206
John McCall8d59dee2012-05-01 00:38:49 +00002207 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00002208 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2209
Richard Smith745f5142012-01-27 01:14:48 +00002210 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002211 unsigned BasesSeen = 0;
2212#ifndef NDEBUG
2213 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2214#endif
2215 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2216 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002217 LValue Subobject = This;
2218 APValue *Value = &Result;
2219
2220 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002221 if ((*I)->isBaseInitializer()) {
2222 QualType BaseType((*I)->getBaseClass(), 0);
2223#ifndef NDEBUG
2224 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002225 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002226 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2227 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2228 "base class initializers not in expected order");
2229 ++BaseIt;
2230#endif
John McCall8d59dee2012-05-01 00:38:49 +00002231 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2232 BaseType->getAsCXXRecordDecl(), &Layout))
2233 return false;
Richard Smith745f5142012-01-27 01:14:48 +00002234 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002235 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCall8d59dee2012-05-01 00:38:49 +00002236 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2237 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002238 if (RD->isUnion()) {
2239 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002240 Value = &Result.getUnionValue();
2241 } else {
2242 Value = &Result.getStructField(FD->getFieldIndex());
2243 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002244 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002245 // Walk the indirect field decl's chain to find the object to initialize,
2246 // and make sure we've initialized every step along it.
2247 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2248 CE = IFD->chain_end();
2249 C != CE; ++C) {
2250 FieldDecl *FD = cast<FieldDecl>(*C);
2251 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2252 // Switch the union field if it differs. This happens if we had
2253 // preceding zero-initialization, and we're now initializing a union
2254 // subobject other than the first.
2255 // FIXME: In this case, the values of the other subobjects are
2256 // specified, since zero-initialization sets all padding bits to zero.
2257 if (Value->isUninit() ||
2258 (Value->isUnion() && Value->getUnionField() != FD)) {
2259 if (CD->isUnion())
2260 *Value = APValue(FD);
2261 else
2262 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2263 std::distance(CD->field_begin(), CD->field_end()));
2264 }
John McCall8d59dee2012-05-01 00:38:49 +00002265 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2266 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002267 if (CD->isUnion())
2268 Value = &Value->getUnionValue();
2269 else
2270 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002271 }
Richard Smith180f4792011-11-10 06:34:14 +00002272 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002273 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002274 }
Richard Smith745f5142012-01-27 01:14:48 +00002275
Richard Smith83587db2012-02-15 02:18:13 +00002276 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2277 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002278 ? CCEK_Constant : CCEK_MemberInit)) {
2279 // If we're checking for a potential constant expression, evaluate all
2280 // initializers even if some of them fail.
2281 if (!Info.keepEvaluatingAfterFailure())
2282 return false;
2283 Success = false;
2284 }
Richard Smith180f4792011-11-10 06:34:14 +00002285 }
2286
Richard Smith745f5142012-01-27 01:14:48 +00002287 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002288}
2289
Richard Smithd0dccea2011-10-28 22:34:42 +00002290namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002291class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002292 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002293 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002294public:
2295
Richard Smith1e12c592011-10-16 21:26:27 +00002296 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002297
2298 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002299 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002300 return true;
2301 }
2302
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002303 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2304 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002305 return Visit(E->getResultExpr());
2306 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002307 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002308 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002309 return true;
2310 return false;
2311 }
John McCallf85e1932011-06-15 23:02:42 +00002312 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002313 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002314 return true;
2315 return false;
2316 }
John McCallf85e1932011-06-15 23:02:42 +00002317
Mike Stumpc4c90452009-10-27 22:09:17 +00002318 // We don't want to evaluate BlockExprs multiple times, as they generate
2319 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002320 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2321 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2322 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002323 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002324 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2325 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2326 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2327 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2328 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2329 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002330 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002331 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002332 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002333 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002334 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002335 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2336 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2337 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2338 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002339 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002340 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2341 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2342 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2343 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2344 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002345 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002346 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002347 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002348 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002349 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002350
2351 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002352 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002353 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2354 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002355 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002356 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002357 return false;
2358 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002359
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002360 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002361};
2362
John McCall56ca35d2011-02-17 10:25:35 +00002363class OpaqueValueEvaluation {
2364 EvalInfo &info;
2365 OpaqueValueExpr *opaqueValue;
2366
2367public:
2368 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2369 Expr *value)
2370 : info(info), opaqueValue(opaqueValue) {
2371
2372 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002373 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002374 this->opaqueValue = 0;
2375 return;
2376 }
John McCall56ca35d2011-02-17 10:25:35 +00002377 }
2378
2379 bool hasError() const { return opaqueValue == 0; }
2380
2381 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002382 // FIXME: For a recursive constexpr call, an outer stack frame might have
2383 // been using this opaque value too, and will now have to re-evaluate the
2384 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002385 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2386 }
2387};
2388
Mike Stumpc4c90452009-10-27 22:09:17 +00002389} // end anonymous namespace
2390
Eli Friedman4efaa272008-11-12 09:44:48 +00002391//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002392// Generic Evaluation
2393//===----------------------------------------------------------------------===//
2394namespace {
2395
Richard Smithf48fdb02011-12-09 22:58:01 +00002396// FIXME: RetTy is always bool. Remove it.
2397template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002398class ExprEvaluatorBase
2399 : public ConstStmtVisitor<Derived, RetTy> {
2400private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002401 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002402 return static_cast<Derived*>(this)->Success(V, E);
2403 }
Richard Smith51201882011-12-30 21:15:51 +00002404 RetTy DerivedZeroInitialization(const Expr *E) {
2405 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002406 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002407
Richard Smith74e1ad92012-02-16 02:46:34 +00002408 // Check whether a conditional operator with a non-constant condition is a
2409 // potential constant expression. If neither arm is a potential constant
2410 // expression, then the conditional operator is not either.
2411 template<typename ConditionalOperator>
2412 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2413 assert(Info.CheckingPotentialConstantExpression);
2414
2415 // Speculatively evaluate both arms.
2416 {
2417 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2418 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2419
2420 StmtVisitorTy::Visit(E->getFalseExpr());
2421 if (Diag.empty())
2422 return;
2423
2424 Diag.clear();
2425 StmtVisitorTy::Visit(E->getTrueExpr());
2426 if (Diag.empty())
2427 return;
2428 }
2429
2430 Error(E, diag::note_constexpr_conditional_never_const);
2431 }
2432
2433
2434 template<typename ConditionalOperator>
2435 bool HandleConditionalOperator(const ConditionalOperator *E) {
2436 bool BoolResult;
2437 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2438 if (Info.CheckingPotentialConstantExpression)
2439 CheckPotentialConstantConditional(E);
2440 return false;
2441 }
2442
2443 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2444 return StmtVisitorTy::Visit(EvalExpr);
2445 }
2446
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002447protected:
2448 EvalInfo &Info;
2449 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2450 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2451
Richard Smithdd1f29b2011-12-12 09:28:41 +00002452 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002453 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002454 }
2455
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00002456 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2457
2458public:
2459 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2460
2461 EvalInfo &getEvalInfo() { return Info; }
2462
Richard Smithf48fdb02011-12-09 22:58:01 +00002463 /// Report an evaluation error. This should only be called when an error is
2464 /// first discovered. When propagating an error, just return false.
2465 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002466 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002467 return false;
2468 }
2469 bool Error(const Expr *E) {
2470 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2471 }
2472
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002473 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002474 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002475 }
2476 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002477 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002478 }
2479
2480 RetTy VisitParenExpr(const ParenExpr *E)
2481 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2482 RetTy VisitUnaryExtension(const UnaryOperator *E)
2483 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2484 RetTy VisitUnaryPlus(const UnaryOperator *E)
2485 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2486 RetTy VisitChooseExpr(const ChooseExpr *E)
2487 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2488 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2489 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002490 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2491 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002492 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2493 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002494 // We cannot create any objects for which cleanups are required, so there is
2495 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2496 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2497 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002498
Richard Smithc216a012011-12-12 12:46:16 +00002499 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2500 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2501 return static_cast<Derived*>(this)->VisitCastExpr(E);
2502 }
2503 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2504 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2505 return static_cast<Derived*>(this)->VisitCastExpr(E);
2506 }
2507
Richard Smithe24f5fc2011-11-17 22:56:20 +00002508 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2509 switch (E->getOpcode()) {
2510 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002511 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002512
2513 case BO_Comma:
2514 VisitIgnoredValue(E->getLHS());
2515 return StmtVisitorTy::Visit(E->getRHS());
2516
2517 case BO_PtrMemD:
2518 case BO_PtrMemI: {
2519 LValue Obj;
2520 if (!HandleMemberPointerAccess(Info, E, Obj))
2521 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002522 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002523 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002524 return false;
2525 return DerivedSuccess(Result, E);
2526 }
2527 }
2528 }
2529
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002530 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002531 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002532 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2533 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002534 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002535
Richard Smith74e1ad92012-02-16 02:46:34 +00002536 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002537 }
2538
2539 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002540 bool IsBcpCall = false;
2541 // If the condition (ignoring parens) is a __builtin_constant_p call,
2542 // the result is a constant expression if it can be folded without
2543 // side-effects. This is an important GNU extension. See GCC PR38377
2544 // for discussion.
2545 if (const CallExpr *CallCE =
2546 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2547 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2548 IsBcpCall = true;
2549
2550 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2551 // constant expression; we can't check whether it's potentially foldable.
2552 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2553 return false;
2554
2555 FoldConstant Fold(Info);
2556
Richard Smith74e1ad92012-02-16 02:46:34 +00002557 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002558 return false;
2559
2560 if (IsBcpCall)
2561 Fold.Fold(Info);
2562
2563 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002564 }
2565
2566 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002567 const APValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002568 if (!Value) {
2569 const Expr *Source = E->getSourceExpr();
2570 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002571 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002572 if (Source == E) { // sanity checking.
2573 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002574 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002575 }
2576 return StmtVisitorTy::Visit(Source);
2577 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002578 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002579 }
Richard Smithf10d9172011-10-11 21:43:33 +00002580
Richard Smithd0dccea2011-10-28 22:34:42 +00002581 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002582 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002583 QualType CalleeType = Callee->getType();
2584
Richard Smithd0dccea2011-10-28 22:34:42 +00002585 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002586 LValue *This = 0, ThisVal;
2587 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002588 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002589
Richard Smith59efe262011-11-11 04:05:33 +00002590 // Extract function decl and 'this' pointer from the callee.
2591 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002592 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002593 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2594 // Explicit bound member calls, such as x.f() or p->g();
2595 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002596 return false;
2597 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002598 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002599 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002600 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2601 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002602 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2603 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002604 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002605 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002606 return Error(Callee);
2607
2608 FD = dyn_cast<FunctionDecl>(Member);
2609 if (!FD)
2610 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002611 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002612 LValue Call;
2613 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002614 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002615
Richard Smithb4e85ed2012-01-06 16:39:00 +00002616 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002617 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002618 FD = dyn_cast_or_null<FunctionDecl>(
2619 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002620 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002621 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002622
2623 // Overloaded operator calls to member functions are represented as normal
2624 // calls with '*this' as the first argument.
2625 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2626 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002627 // FIXME: When selecting an implicit conversion for an overloaded
2628 // operator delete, we sometimes try to evaluate calls to conversion
2629 // operators without a 'this' parameter!
2630 if (Args.empty())
2631 return Error(E);
2632
Richard Smith59efe262011-11-11 04:05:33 +00002633 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2634 return false;
2635 This = &ThisVal;
2636 Args = Args.slice(1);
2637 }
2638
2639 // Don't call function pointers which have been cast to some other type.
2640 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002641 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002642 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002643 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002644
Richard Smithb04035a2012-02-01 02:39:43 +00002645 if (This && !This->checkSubobject(Info, E, CSK_This))
2646 return false;
2647
Richard Smith86c3ae42012-02-13 03:54:03 +00002648 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2649 // calls to such functions in constant expressions.
2650 if (This && !HasQualifier &&
2651 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2652 return Error(E, diag::note_constexpr_virtual_call);
2653
Richard Smithc1c5f272011-12-13 06:39:58 +00002654 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002655 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002656 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002657
Richard Smithc1c5f272011-12-13 06:39:58 +00002658 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002659 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2660 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002661 return false;
2662
Richard Smith83587db2012-02-15 02:18:13 +00002663 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002664 }
2665
Richard Smithc49bd112011-10-28 17:51:58 +00002666 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2667 return StmtVisitorTy::Visit(E->getInitializer());
2668 }
Richard Smithf10d9172011-10-11 21:43:33 +00002669 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002670 if (E->getNumInits() == 0)
2671 return DerivedZeroInitialization(E);
2672 if (E->getNumInits() == 1)
2673 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002674 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002675 }
2676 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002677 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002678 }
2679 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002680 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002681 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002682 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002683 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002684 }
Richard Smithf10d9172011-10-11 21:43:33 +00002685
Richard Smith180f4792011-11-10 06:34:14 +00002686 /// A member expression where the object is a prvalue is itself a prvalue.
2687 RetTy VisitMemberExpr(const MemberExpr *E) {
2688 assert(!E->isArrow() && "missing call to bound member function?");
2689
Richard Smith1aa0be82012-03-03 22:46:17 +00002690 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002691 if (!Evaluate(Val, Info, E->getBase()))
2692 return false;
2693
2694 QualType BaseTy = E->getBase()->getType();
2695
2696 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002697 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002698 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2699 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2700 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2701
Richard Smithb4e85ed2012-01-06 16:39:00 +00002702 SubobjectDesignator Designator(BaseTy);
2703 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002704
Richard Smithf48fdb02011-12-09 22:58:01 +00002705 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002706 DerivedSuccess(Val, E);
2707 }
2708
Richard Smithc49bd112011-10-28 17:51:58 +00002709 RetTy VisitCastExpr(const CastExpr *E) {
2710 switch (E->getCastKind()) {
2711 default:
2712 break;
2713
David Chisnall7a7ee302012-01-16 17:27:18 +00002714 case CK_AtomicToNonAtomic:
2715 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002716 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002717 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002718 return StmtVisitorTy::Visit(E->getSubExpr());
2719
2720 case CK_LValueToRValue: {
2721 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002722 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2723 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002724 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002725 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2726 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2727 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002728 return false;
2729 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002730 }
2731 }
2732
Richard Smithf48fdb02011-12-09 22:58:01 +00002733 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002734 }
2735
Richard Smith8327fad2011-10-24 18:44:57 +00002736 /// Visit a value which is evaluated, but whose value is ignored.
2737 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002738 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002739 if (!Evaluate(Scratch, Info, E))
2740 Info.EvalStatus.HasSideEffects = true;
2741 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002742};
2743
2744}
2745
2746//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002747// Common base class for lvalue and temporary evaluation.
2748//===----------------------------------------------------------------------===//
2749namespace {
2750template<class Derived>
2751class LValueExprEvaluatorBase
2752 : public ExprEvaluatorBase<Derived, bool> {
2753protected:
2754 LValue &Result;
2755 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2756 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2757
2758 bool Success(APValue::LValueBase B) {
2759 Result.set(B);
2760 return true;
2761 }
2762
2763public:
2764 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2765 ExprEvaluatorBaseTy(Info), Result(Result) {}
2766
Richard Smith1aa0be82012-03-03 22:46:17 +00002767 bool Success(const APValue &V, const Expr *E) {
2768 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002769 return true;
2770 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002771
Richard Smithe24f5fc2011-11-17 22:56:20 +00002772 bool VisitMemberExpr(const MemberExpr *E) {
2773 // Handle non-static data members.
2774 QualType BaseTy;
2775 if (E->isArrow()) {
2776 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2777 return false;
2778 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002779 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002780 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002781 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2782 return false;
2783 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002784 } else {
2785 if (!this->Visit(E->getBase()))
2786 return false;
2787 BaseTy = E->getBase()->getType();
2788 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002789
Richard Smithd9b02e72012-01-25 22:15:11 +00002790 const ValueDecl *MD = E->getMemberDecl();
2791 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2792 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2793 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2794 (void)BaseTy;
John McCall8d59dee2012-05-01 00:38:49 +00002795 if (!HandleLValueMember(this->Info, E, Result, FD))
2796 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002797 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCall8d59dee2012-05-01 00:38:49 +00002798 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2799 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002800 } else
2801 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002802
Richard Smithd9b02e72012-01-25 22:15:11 +00002803 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002804 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002805 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002806 RefValue))
2807 return false;
2808 return Success(RefValue, E);
2809 }
2810 return true;
2811 }
2812
2813 bool VisitBinaryOperator(const BinaryOperator *E) {
2814 switch (E->getOpcode()) {
2815 default:
2816 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2817
2818 case BO_PtrMemD:
2819 case BO_PtrMemI:
2820 return HandleMemberPointerAccess(this->Info, E, Result);
2821 }
2822 }
2823
2824 bool VisitCastExpr(const CastExpr *E) {
2825 switch (E->getCastKind()) {
2826 default:
2827 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2828
2829 case CK_DerivedToBase:
2830 case CK_UncheckedDerivedToBase: {
2831 if (!this->Visit(E->getSubExpr()))
2832 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002833
2834 // Now figure out the necessary offset to add to the base LV to get from
2835 // the derived class to the base class.
2836 QualType Type = E->getSubExpr()->getType();
2837
2838 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2839 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002840 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002841 *PathI))
2842 return false;
2843 Type = (*PathI)->getType();
2844 }
2845
2846 return true;
2847 }
2848 }
2849 }
2850};
2851}
2852
2853//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002854// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002855//
2856// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2857// function designators (in C), decl references to void objects (in C), and
2858// temporaries (if building with -Wno-address-of-temporary).
2859//
2860// LValue evaluation produces values comprising a base expression of one of the
2861// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002862// - Declarations
2863// * VarDecl
2864// * FunctionDecl
2865// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002866// * CompoundLiteralExpr in C
2867// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002868// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002869// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002870// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002871// * ObjCEncodeExpr
2872// * AddrLabelExpr
2873// * BlockExpr
2874// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002875// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002876// * Any Expr, with a CallIndex indicating the function in which the temporary
2877// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002878// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002879//===----------------------------------------------------------------------===//
2880namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002881class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002882 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002883public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002884 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2885 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002886
Richard Smithc49bd112011-10-28 17:51:58 +00002887 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2888
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002889 bool VisitDeclRefExpr(const DeclRefExpr *E);
2890 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002891 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002892 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2893 bool VisitMemberExpr(const MemberExpr *E);
2894 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2895 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002896 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichete275a182012-04-16 04:08:35 +00002897 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002898 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2899 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002900 bool VisitUnaryReal(const UnaryOperator *E);
2901 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002902
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002903 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002904 switch (E->getCastKind()) {
2905 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002906 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002907
Eli Friedmandb924222011-10-11 00:13:24 +00002908 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002909 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002910 if (!Visit(E->getSubExpr()))
2911 return false;
2912 Result.Designator.setInvalid();
2913 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002914
Richard Smithe24f5fc2011-11-17 22:56:20 +00002915 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002916 if (!Visit(E->getSubExpr()))
2917 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002918 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002919 }
2920 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002921};
2922} // end anonymous namespace
2923
Richard Smithc49bd112011-10-28 17:51:58 +00002924/// Evaluate an expression as an lvalue. This can be legitimately called on
2925/// expressions which are not glvalues, in a few cases:
2926/// * function designators in C,
2927/// * "extern void" objects,
2928/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002929static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002930 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2931 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2932 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002933 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002934}
2935
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002936bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002937 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2938 return Success(FD);
2939 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002940 return VisitVarDecl(E, VD);
2941 return Error(E);
2942}
Richard Smith436c8892011-10-24 23:14:33 +00002943
Richard Smithc49bd112011-10-28 17:51:58 +00002944bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002945 if (!VD->getType()->isReferenceType()) {
2946 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002947 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002948 return true;
2949 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002950 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002951 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002952
Richard Smith1aa0be82012-03-03 22:46:17 +00002953 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002954 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2955 return false;
2956 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002957}
2958
Richard Smithbd552ef2011-10-31 05:52:43 +00002959bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2960 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002961 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002962 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002963 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2964
Richard Smith83587db2012-02-15 02:18:13 +00002965 Result.set(E, Info.CurrentCall->Index);
2966 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2967 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002968 }
2969
2970 // Materialization of an lvalue temporary occurs when we need to force a copy
2971 // (for instance, if it's a bitfield).
2972 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2973 if (!Visit(E->GetTemporaryExpr()))
2974 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002975 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002976 Info.CurrentCall->Temporaries[E]))
2977 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002978 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002979 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002980}
2981
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002982bool
2983LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002984 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2985 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2986 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002987 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002988}
2989
Richard Smith47d21452011-12-27 12:18:28 +00002990bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2991 if (E->isTypeOperand())
2992 return Success(E);
2993 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2994 if (RD && RD->isPolymorphic()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002995 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith47d21452011-12-27 12:18:28 +00002996 << E->getExprOperand()->getType()
2997 << E->getExprOperand()->getSourceRange();
2998 return false;
2999 }
3000 return Success(E);
3001}
3002
Francois Pichete275a182012-04-16 04:08:35 +00003003bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
3004 return Success(E);
3005}
3006
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003007bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003008 // Handle static data members.
3009 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3010 VisitIgnoredValue(E->getBase());
3011 return VisitVarDecl(E, VD);
3012 }
3013
Richard Smithd0dccea2011-10-28 22:34:42 +00003014 // Handle static member functions.
3015 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3016 if (MD->isStatic()) {
3017 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003018 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00003019 }
3020 }
3021
Richard Smith180f4792011-11-10 06:34:14 +00003022 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00003023 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003024}
3025
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003026bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003027 // FIXME: Deal with vectors as array subscript bases.
3028 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003029 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003030
Anders Carlsson3068d112008-11-16 19:01:22 +00003031 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003032 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003033
Anders Carlsson3068d112008-11-16 19:01:22 +00003034 APSInt Index;
3035 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003036 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003037 int64_t IndexValue
3038 = Index.isSigned() ? Index.getSExtValue()
3039 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003040
Richard Smithb4e85ed2012-01-06 16:39:00 +00003041 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003042}
Eli Friedman4efaa272008-11-12 09:44:48 +00003043
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003044bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003045 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003046}
3047
Richard Smith86024012012-02-18 22:04:06 +00003048bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3049 if (!Visit(E->getSubExpr()))
3050 return false;
3051 // __real is a no-op on scalar lvalues.
3052 if (E->getSubExpr()->getType()->isAnyComplexType())
3053 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3054 return true;
3055}
3056
3057bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3058 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3059 "lvalue __imag__ on scalar?");
3060 if (!Visit(E->getSubExpr()))
3061 return false;
3062 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3063 return true;
3064}
3065
Eli Friedman4efaa272008-11-12 09:44:48 +00003066//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003067// Pointer Evaluation
3068//===----------------------------------------------------------------------===//
3069
Anders Carlssonc754aa62008-07-08 05:13:58 +00003070namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003071class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003072 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003073 LValue &Result;
3074
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003075 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003076 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003077 return true;
3078 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003079public:
Mike Stump1eb44332009-09-09 15:08:12 +00003080
John McCallefdb83e2010-05-07 21:00:08 +00003081 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003082 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003083
Richard Smith1aa0be82012-03-03 22:46:17 +00003084 bool Success(const APValue &V, const Expr *E) {
3085 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003086 return true;
3087 }
Richard Smith51201882011-12-30 21:15:51 +00003088 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003089 return Success((Expr*)0);
3090 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003091
John McCallefdb83e2010-05-07 21:00:08 +00003092 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003093 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003094 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003095 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003096 { return Success(E); }
Patrick Beardeb382ec2012-04-19 00:25:12 +00003097 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003098 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003099 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003100 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003101 bool VisitCallExpr(const CallExpr *E);
3102 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003103 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003104 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003105 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003106 }
Richard Smith180f4792011-11-10 06:34:14 +00003107 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3108 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003109 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003110 Result = *Info.CurrentCall->This;
3111 return true;
3112 }
John McCall56ca35d2011-02-17 10:25:35 +00003113
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003114 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003115};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003116} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003117
John McCallefdb83e2010-05-07 21:00:08 +00003118static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003119 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003120 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003121}
3122
John McCallefdb83e2010-05-07 21:00:08 +00003123bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003124 if (E->getOpcode() != BO_Add &&
3125 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003126 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003127
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003128 const Expr *PExp = E->getLHS();
3129 const Expr *IExp = E->getRHS();
3130 if (IExp->getType()->isPointerType())
3131 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003132
Richard Smith745f5142012-01-27 01:14:48 +00003133 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3134 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003135 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003136
John McCallefdb83e2010-05-07 21:00:08 +00003137 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003138 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003139 return false;
3140 int64_t AdditionalOffset
3141 = Offset.isSigned() ? Offset.getSExtValue()
3142 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003143 if (E->getOpcode() == BO_Sub)
3144 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003145
Richard Smith180f4792011-11-10 06:34:14 +00003146 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003147 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3148 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003149}
Eli Friedman4efaa272008-11-12 09:44:48 +00003150
John McCallefdb83e2010-05-07 21:00:08 +00003151bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3152 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003153}
Mike Stump1eb44332009-09-09 15:08:12 +00003154
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003155bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3156 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003157
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003158 switch (E->getCastKind()) {
3159 default:
3160 break;
3161
John McCall2de56d12010-08-25 11:45:40 +00003162 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003163 case CK_CPointerToObjCPointerCast:
3164 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003165 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003166 if (!Visit(SubExpr))
3167 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003168 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3169 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3170 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003171 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003172 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003173 if (SubExpr->getType()->isVoidPointerType())
3174 CCEDiag(E, diag::note_constexpr_invalid_cast)
3175 << 3 << SubExpr->getType();
3176 else
3177 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3178 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003179 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003180
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003181 case CK_DerivedToBase:
3182 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003183 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003184 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003185 if (!Result.Base && Result.Offset.isZero())
3186 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003187
Richard Smith180f4792011-11-10 06:34:14 +00003188 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003189 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003190 QualType Type =
3191 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003192
Richard Smith180f4792011-11-10 06:34:14 +00003193 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003194 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003195 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3196 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003197 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003198 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003199 }
3200
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003201 return true;
3202 }
3203
Richard Smithe24f5fc2011-11-17 22:56:20 +00003204 case CK_BaseToDerived:
3205 if (!Visit(E->getSubExpr()))
3206 return false;
3207 if (!Result.Base && Result.Offset.isZero())
3208 return true;
3209 return HandleBaseToDerivedCast(Info, E, Result);
3210
Richard Smith47a1eed2011-10-29 20:57:55 +00003211 case CK_NullToPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003212 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003213 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003214
John McCall2de56d12010-08-25 11:45:40 +00003215 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003216 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3217
Richard Smith1aa0be82012-03-03 22:46:17 +00003218 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003219 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003220 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003221
John McCallefdb83e2010-05-07 21:00:08 +00003222 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003223 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3224 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003225 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003226 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003227 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003228 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003229 return true;
3230 } else {
3231 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003232 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003233 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003234 }
3235 }
John McCall2de56d12010-08-25 11:45:40 +00003236 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003237 if (SubExpr->isGLValue()) {
3238 if (!EvaluateLValue(SubExpr, Result, Info))
3239 return false;
3240 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003241 Result.set(SubExpr, Info.CurrentCall->Index);
3242 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3243 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003244 return false;
3245 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003246 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003247 if (const ConstantArrayType *CAT
3248 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3249 Result.addArray(Info, E, CAT);
3250 else
3251 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003252 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003253
John McCall2de56d12010-08-25 11:45:40 +00003254 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003255 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003256 }
3257
Richard Smithc49bd112011-10-28 17:51:58 +00003258 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003259}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003260
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003261bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003262 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003263 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003264
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003265 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003266}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003267
3268//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003269// Member Pointer Evaluation
3270//===----------------------------------------------------------------------===//
3271
3272namespace {
3273class MemberPointerExprEvaluator
3274 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3275 MemberPtr &Result;
3276
3277 bool Success(const ValueDecl *D) {
3278 Result = MemberPtr(D);
3279 return true;
3280 }
3281public:
3282
3283 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3284 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3285
Richard Smith1aa0be82012-03-03 22:46:17 +00003286 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003287 Result.setFrom(V);
3288 return true;
3289 }
Richard Smith51201882011-12-30 21:15:51 +00003290 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003291 return Success((const ValueDecl*)0);
3292 }
3293
3294 bool VisitCastExpr(const CastExpr *E);
3295 bool VisitUnaryAddrOf(const UnaryOperator *E);
3296};
3297} // end anonymous namespace
3298
3299static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3300 EvalInfo &Info) {
3301 assert(E->isRValue() && E->getType()->isMemberPointerType());
3302 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3303}
3304
3305bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3306 switch (E->getCastKind()) {
3307 default:
3308 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3309
3310 case CK_NullToMemberPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003311 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003312 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003313
3314 case CK_BaseToDerivedMemberPointer: {
3315 if (!Visit(E->getSubExpr()))
3316 return false;
3317 if (E->path_empty())
3318 return true;
3319 // Base-to-derived member pointer casts store the path in derived-to-base
3320 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3321 // the wrong end of the derived->base arc, so stagger the path by one class.
3322 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3323 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3324 PathI != PathE; ++PathI) {
3325 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3326 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3327 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003328 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003329 }
3330 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3331 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003332 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003333 return true;
3334 }
3335
3336 case CK_DerivedToBaseMemberPointer:
3337 if (!Visit(E->getSubExpr()))
3338 return false;
3339 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3340 PathE = E->path_end(); PathI != PathE; ++PathI) {
3341 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3342 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3343 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003344 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003345 }
3346 return true;
3347 }
3348}
3349
3350bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3351 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3352 // member can be formed.
3353 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3354}
3355
3356//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003357// Record Evaluation
3358//===----------------------------------------------------------------------===//
3359
3360namespace {
3361 class RecordExprEvaluator
3362 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3363 const LValue &This;
3364 APValue &Result;
3365 public:
3366
3367 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3368 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3369
Richard Smith1aa0be82012-03-03 22:46:17 +00003370 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003371 Result = V;
3372 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003373 }
Richard Smith51201882011-12-30 21:15:51 +00003374 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003375
Richard Smith59efe262011-11-11 04:05:33 +00003376 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003377 bool VisitInitListExpr(const InitListExpr *E);
3378 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3379 };
3380}
3381
Richard Smith51201882011-12-30 21:15:51 +00003382/// Perform zero-initialization on an object of non-union class type.
3383/// C++11 [dcl.init]p5:
3384/// To zero-initialize an object or reference of type T means:
3385/// [...]
3386/// -- if T is a (possibly cv-qualified) non-union class type,
3387/// each non-static data member and each base-class subobject is
3388/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003389static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3390 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003391 const LValue &This, APValue &Result) {
3392 assert(!RD->isUnion() && "Expected non-union class type");
3393 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3394 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3395 std::distance(RD->field_begin(), RD->field_end()));
3396
John McCall8d59dee2012-05-01 00:38:49 +00003397 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003398 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3399
3400 if (CD) {
3401 unsigned Index = 0;
3402 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003403 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003404 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3405 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003406 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3407 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003408 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003409 Result.getStructBase(Index)))
3410 return false;
3411 }
3412 }
3413
Richard Smithb4e85ed2012-01-06 16:39:00 +00003414 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3415 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003416 // -- if T is a reference type, no initialization is performed.
David Blaikie262bc182012-04-30 02:36:29 +00003417 if (I->getType()->isReferenceType())
Richard Smith51201882011-12-30 21:15:51 +00003418 continue;
3419
3420 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003421 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003422 return false;
Richard Smith51201882011-12-30 21:15:51 +00003423
David Blaikie262bc182012-04-30 02:36:29 +00003424 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003425 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003426 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003427 return false;
3428 }
3429
3430 return true;
3431}
3432
3433bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3434 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003435 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003436 if (RD->isUnion()) {
3437 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3438 // object's first non-static named data member is zero-initialized
3439 RecordDecl::field_iterator I = RD->field_begin();
3440 if (I == RD->field_end()) {
3441 Result = APValue((const FieldDecl*)0);
3442 return true;
3443 }
3444
3445 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003446 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCall8d59dee2012-05-01 00:38:49 +00003447 return false;
David Blaikie581deb32012-06-06 20:45:41 +00003448 Result = APValue(*I);
David Blaikie262bc182012-04-30 02:36:29 +00003449 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003450 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003451 }
3452
Richard Smithce582fe2012-02-17 00:44:16 +00003453 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003454 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003455 return false;
3456 }
3457
Richard Smithb4e85ed2012-01-06 16:39:00 +00003458 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003459}
3460
Richard Smith59efe262011-11-11 04:05:33 +00003461bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3462 switch (E->getCastKind()) {
3463 default:
3464 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3465
3466 case CK_ConstructorConversion:
3467 return Visit(E->getSubExpr());
3468
3469 case CK_DerivedToBase:
3470 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003471 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003472 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003473 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003474 if (!DerivedObject.isStruct())
3475 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003476
3477 // Derived-to-base rvalue conversion: just slice off the derived part.
3478 APValue *Value = &DerivedObject;
3479 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3480 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3481 PathE = E->path_end(); PathI != PathE; ++PathI) {
3482 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3483 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3484 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3485 RD = Base;
3486 }
3487 Result = *Value;
3488 return true;
3489 }
3490 }
3491}
3492
Richard Smith180f4792011-11-10 06:34:14 +00003493bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003494 // Cannot constant-evaluate std::initializer_list inits.
3495 if (E->initializesStdInitializerList())
3496 return false;
3497
Richard Smith180f4792011-11-10 06:34:14 +00003498 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003499 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00003500 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3501
3502 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003503 const FieldDecl *Field = E->getInitializedFieldInUnion();
3504 Result = APValue(Field);
3505 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003506 return true;
Richard Smithec789162012-01-12 18:54:33 +00003507
3508 // If the initializer list for a union does not contain any elements, the
3509 // first element of the union is value-initialized.
3510 ImplicitValueInitExpr VIE(Field->getType());
3511 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3512
Richard Smith180f4792011-11-10 06:34:14 +00003513 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003514 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3515 return false;
Richard Smith83587db2012-02-15 02:18:13 +00003516 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003517 }
3518
3519 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3520 "initializer list for class with base classes");
3521 Result = APValue(APValue::UninitStruct(), 0,
3522 std::distance(RD->field_begin(), RD->field_end()));
3523 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003524 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003525 for (RecordDecl::field_iterator Field = RD->field_begin(),
3526 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3527 // Anonymous bit-fields are not considered members of the class for
3528 // purposes of aggregate initialization.
3529 if (Field->isUnnamedBitfield())
3530 continue;
3531
3532 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003533
Richard Smith745f5142012-01-27 01:14:48 +00003534 bool HaveInit = ElementNo < E->getNumInits();
3535
3536 // FIXME: Diagnostics here should point to the end of the initializer
3537 // list, not the start.
John McCall8d59dee2012-05-01 00:38:49 +00003538 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie581deb32012-06-06 20:45:41 +00003539 Subobject, *Field, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003540 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003541
3542 // Perform an implicit value-initialization for members beyond the end of
3543 // the initializer list.
3544 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3545
Richard Smith83587db2012-02-15 02:18:13 +00003546 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003547 Result.getStructField(Field->getFieldIndex()),
Richard Smith745f5142012-01-27 01:14:48 +00003548 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3549 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003550 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003551 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003552 }
3553 }
3554
Richard Smith745f5142012-01-27 01:14:48 +00003555 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003556}
3557
3558bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3559 const CXXConstructorDecl *FD = E->getConstructor();
John McCall1de9d7d2012-04-26 18:10:01 +00003560 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3561
Richard Smith51201882011-12-30 21:15:51 +00003562 bool ZeroInit = E->requiresZeroInitialization();
3563 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003564 // If we've already performed zero-initialization, we're already done.
3565 if (!Result.isUninit())
3566 return true;
3567
Richard Smith51201882011-12-30 21:15:51 +00003568 if (ZeroInit)
3569 return ZeroInitialization(E);
3570
Richard Smith61802452011-12-22 02:22:31 +00003571 const CXXRecordDecl *RD = FD->getParent();
3572 if (RD->isUnion())
3573 Result = APValue((FieldDecl*)0);
3574 else
3575 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3576 std::distance(RD->field_begin(), RD->field_end()));
3577 return true;
3578 }
3579
Richard Smith180f4792011-11-10 06:34:14 +00003580 const FunctionDecl *Definition = 0;
3581 FD->getBody(Definition);
3582
Richard Smithc1c5f272011-12-13 06:39:58 +00003583 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3584 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003585
Richard Smith610a60c2012-01-10 04:32:03 +00003586 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003587 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003588 if (const MaterializeTemporaryExpr *ME
3589 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3590 return Visit(ME->GetTemporaryExpr());
3591
Richard Smith51201882011-12-30 21:15:51 +00003592 if (ZeroInit && !ZeroInitialization(E))
3593 return false;
3594
Richard Smith180f4792011-11-10 06:34:14 +00003595 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003596 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003597 cast<CXXConstructorDecl>(Definition), Info,
3598 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003599}
3600
3601static bool EvaluateRecord(const Expr *E, const LValue &This,
3602 APValue &Result, EvalInfo &Info) {
3603 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003604 "can't evaluate expression as a record rvalue");
3605 return RecordExprEvaluator(Info, This, Result).Visit(E);
3606}
3607
3608//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003609// Temporary Evaluation
3610//
3611// Temporaries are represented in the AST as rvalues, but generally behave like
3612// lvalues. The full-object of which the temporary is a subobject is implicitly
3613// materialized so that a reference can bind to it.
3614//===----------------------------------------------------------------------===//
3615namespace {
3616class TemporaryExprEvaluator
3617 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3618public:
3619 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3620 LValueExprEvaluatorBaseTy(Info, Result) {}
3621
3622 /// Visit an expression which constructs the value of this temporary.
3623 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003624 Result.set(E, Info.CurrentCall->Index);
3625 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003626 }
3627
3628 bool VisitCastExpr(const CastExpr *E) {
3629 switch (E->getCastKind()) {
3630 default:
3631 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3632
3633 case CK_ConstructorConversion:
3634 return VisitConstructExpr(E->getSubExpr());
3635 }
3636 }
3637 bool VisitInitListExpr(const InitListExpr *E) {
3638 return VisitConstructExpr(E);
3639 }
3640 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3641 return VisitConstructExpr(E);
3642 }
3643 bool VisitCallExpr(const CallExpr *E) {
3644 return VisitConstructExpr(E);
3645 }
3646};
3647} // end anonymous namespace
3648
3649/// Evaluate an expression of record type as a temporary.
3650static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003651 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003652 return TemporaryExprEvaluator(Info, Result).Visit(E);
3653}
3654
3655//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003656// Vector Evaluation
3657//===----------------------------------------------------------------------===//
3658
3659namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003660 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003661 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3662 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003663 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003664
Richard Smith07fc6572011-10-22 21:10:00 +00003665 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3666 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003667
Richard Smith07fc6572011-10-22 21:10:00 +00003668 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3669 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3670 // FIXME: remove this APValue copy.
3671 Result = APValue(V.data(), V.size());
3672 return true;
3673 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003674 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003675 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003676 Result = V;
3677 return true;
3678 }
Richard Smith51201882011-12-30 21:15:51 +00003679 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003680
Richard Smith07fc6572011-10-22 21:10:00 +00003681 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003682 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003683 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003684 bool VisitInitListExpr(const InitListExpr *E);
3685 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003686 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003687 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003688 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003689 };
3690} // end anonymous namespace
3691
3692static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003693 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003694 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003695}
3696
Richard Smith07fc6572011-10-22 21:10:00 +00003697bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3698 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003699 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003700
Richard Smithd62ca372011-12-06 22:44:34 +00003701 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003702 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003703
Eli Friedman46a52322011-03-25 00:43:55 +00003704 switch (E->getCastKind()) {
3705 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003706 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003707 if (SETy->isIntegerType()) {
3708 APSInt IntResult;
3709 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003710 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003711 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003712 } else if (SETy->isRealFloatingType()) {
3713 APFloat F(0.0);
3714 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003715 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003716 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003717 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003718 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003719 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003720
3721 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003722 SmallVector<APValue, 4> Elts(NElts, Val);
3723 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003724 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003725 case CK_BitCast: {
3726 // Evaluate the operand into an APInt we can extract from.
3727 llvm::APInt SValInt;
3728 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3729 return false;
3730 // Extract the elements
3731 QualType EltTy = VTy->getElementType();
3732 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3733 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3734 SmallVector<APValue, 4> Elts;
3735 if (EltTy->isRealFloatingType()) {
3736 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3737 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3738 unsigned FloatEltSize = EltSize;
3739 if (&Sem == &APFloat::x87DoubleExtended)
3740 FloatEltSize = 80;
3741 for (unsigned i = 0; i < NElts; i++) {
3742 llvm::APInt Elt;
3743 if (BigEndian)
3744 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3745 else
3746 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3747 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3748 }
3749 } else if (EltTy->isIntegerType()) {
3750 for (unsigned i = 0; i < NElts; i++) {
3751 llvm::APInt Elt;
3752 if (BigEndian)
3753 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3754 else
3755 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3756 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3757 }
3758 } else {
3759 return Error(E);
3760 }
3761 return Success(Elts, E);
3762 }
Eli Friedman46a52322011-03-25 00:43:55 +00003763 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003764 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003765 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003766}
3767
Richard Smith07fc6572011-10-22 21:10:00 +00003768bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003769VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003770 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003771 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003772 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003773
Nate Begeman59b5da62009-01-18 03:20:47 +00003774 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003775 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003776
Eli Friedman3edd5a92012-01-03 23:24:20 +00003777 // The number of initializers can be less than the number of
3778 // vector elements. For OpenCL, this can be due to nested vector
3779 // initialization. For GCC compatibility, missing trailing elements
3780 // should be initialized with zeroes.
3781 unsigned CountInits = 0, CountElts = 0;
3782 while (CountElts < NumElements) {
3783 // Handle nested vector initialization.
3784 if (CountInits < NumInits
3785 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3786 APValue v;
3787 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3788 return Error(E);
3789 unsigned vlen = v.getVectorLength();
3790 for (unsigned j = 0; j < vlen; j++)
3791 Elements.push_back(v.getVectorElt(j));
3792 CountElts += vlen;
3793 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003794 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003795 if (CountInits < NumInits) {
3796 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003797 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003798 } else // trailing integer zero.
3799 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3800 Elements.push_back(APValue(sInt));
3801 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003802 } else {
3803 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003804 if (CountInits < NumInits) {
3805 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003806 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003807 } else // trailing float zero.
3808 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3809 Elements.push_back(APValue(f));
3810 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003811 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003812 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003813 }
Richard Smith07fc6572011-10-22 21:10:00 +00003814 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003815}
3816
Richard Smith07fc6572011-10-22 21:10:00 +00003817bool
Richard Smith51201882011-12-30 21:15:51 +00003818VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003819 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003820 QualType EltTy = VT->getElementType();
3821 APValue ZeroElement;
3822 if (EltTy->isIntegerType())
3823 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3824 else
3825 ZeroElement =
3826 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3827
Chris Lattner5f9e2722011-07-23 10:55:15 +00003828 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003829 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003830}
3831
Richard Smith07fc6572011-10-22 21:10:00 +00003832bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003833 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003834 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003835}
3836
Nate Begeman59b5da62009-01-18 03:20:47 +00003837//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003838// Array Evaluation
3839//===----------------------------------------------------------------------===//
3840
3841namespace {
3842 class ArrayExprEvaluator
3843 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003844 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003845 APValue &Result;
3846 public:
3847
Richard Smith180f4792011-11-10 06:34:14 +00003848 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3849 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003850
3851 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003852 assert((V.isArray() || V.isLValue()) &&
3853 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003854 Result = V;
3855 return true;
3856 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003857
Richard Smith51201882011-12-30 21:15:51 +00003858 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003859 const ConstantArrayType *CAT =
3860 Info.Ctx.getAsConstantArrayType(E->getType());
3861 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003862 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003863
3864 Result = APValue(APValue::UninitArray(), 0,
3865 CAT->getSize().getZExtValue());
3866 if (!Result.hasArrayFiller()) return true;
3867
Richard Smith51201882011-12-30 21:15:51 +00003868 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003869 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003870 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003871 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003872 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003873 }
3874
Richard Smithcc5d4f62011-11-07 09:22:26 +00003875 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003876 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003877 };
3878} // end anonymous namespace
3879
Richard Smith180f4792011-11-10 06:34:14 +00003880static bool EvaluateArray(const Expr *E, const LValue &This,
3881 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003882 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003883 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003884}
3885
3886bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3887 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3888 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003889 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003890
Richard Smith974c5f92011-12-22 01:07:19 +00003891 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3892 // an appropriately-typed string literal enclosed in braces.
Richard Smithfe587202012-04-15 02:50:59 +00003893 if (E->isStringLiteralInit()) {
Richard Smith974c5f92011-12-22 01:07:19 +00003894 LValue LV;
3895 if (!EvaluateLValue(E->getInit(0), LV, Info))
3896 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003897 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003898 LV.moveInto(Val);
3899 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003900 }
3901
Richard Smith745f5142012-01-27 01:14:48 +00003902 bool Success = true;
3903
Richard Smithcc5d4f62011-11-07 09:22:26 +00003904 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3905 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003906 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003907 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003908 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003909 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003910 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003911 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3912 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003913 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3914 CAT->getElementType(), 1)) {
3915 if (!Info.keepEvaluatingAfterFailure())
3916 return false;
3917 Success = false;
3918 }
Richard Smith180f4792011-11-10 06:34:14 +00003919 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003920
Richard Smith745f5142012-01-27 01:14:48 +00003921 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003922 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003923 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3924 // but sometimes does:
3925 // struct S { constexpr S() : p(&p) {} void *p; };
3926 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003927 return EvaluateInPlace(Result.getArrayFiller(), Info,
3928 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003929}
3930
Richard Smithe24f5fc2011-11-17 22:56:20 +00003931bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3932 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3933 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003934 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003935
Richard Smithec789162012-01-12 18:54:33 +00003936 bool HadZeroInit = !Result.isUninit();
3937 if (!HadZeroInit)
3938 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003939 if (!Result.hasArrayFiller())
3940 return true;
3941
3942 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003943
Richard Smith51201882011-12-30 21:15:51 +00003944 bool ZeroInit = E->requiresZeroInitialization();
3945 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003946 if (HadZeroInit)
3947 return true;
3948
Richard Smith51201882011-12-30 21:15:51 +00003949 if (ZeroInit) {
3950 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003951 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003952 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003953 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003954 }
3955
Richard Smith61802452011-12-22 02:22:31 +00003956 const CXXRecordDecl *RD = FD->getParent();
3957 if (RD->isUnion())
3958 Result.getArrayFiller() = APValue((FieldDecl*)0);
3959 else
3960 Result.getArrayFiller() =
3961 APValue(APValue::UninitStruct(), RD->getNumBases(),
3962 std::distance(RD->field_begin(), RD->field_end()));
3963 return true;
3964 }
3965
Richard Smithe24f5fc2011-11-17 22:56:20 +00003966 const FunctionDecl *Definition = 0;
3967 FD->getBody(Definition);
3968
Richard Smithc1c5f272011-12-13 06:39:58 +00003969 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3970 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003971
3972 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3973 // but sometimes does:
3974 // struct S { constexpr S() : p(&p) {} void *p; };
3975 // S s[10];
3976 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003977 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003978
Richard Smithec789162012-01-12 18:54:33 +00003979 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003980 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003981 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003982 return false;
3983 }
3984
Richard Smithe24f5fc2011-11-17 22:56:20 +00003985 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003986 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003987 cast<CXXConstructorDecl>(Definition),
3988 Info, Result.getArrayFiller());
3989}
3990
Richard Smithcc5d4f62011-11-07 09:22:26 +00003991//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003992// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003993//
3994// As a GNU extension, we support casting pointers to sufficiently-wide integer
3995// types and back in constant folding. Integer values are thus represented
3996// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003997//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003998
3999namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004000class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004001 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00004002 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00004003public:
Richard Smith1aa0be82012-03-03 22:46:17 +00004004 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004005 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004006
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004007 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004008 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004009 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004010 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004011 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004012 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004013 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004014 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004015 return true;
4016 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004017 bool Success(const llvm::APSInt &SI, const Expr *E) {
4018 return Success(SI, E, Result);
4019 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004020
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004021 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004022 assert(E->getType()->isIntegralOrEnumerationType() &&
4023 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004024 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004025 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004026 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00004027 Result.getInt().setIsUnsigned(
4028 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00004029 return true;
4030 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004031 bool Success(const llvm::APInt &I, const Expr *E) {
4032 return Success(I, E, Result);
4033 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00004034
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004035 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004036 assert(E->getType()->isIntegralOrEnumerationType() &&
4037 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004038 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00004039 return true;
4040 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004041 bool Success(uint64_t Value, const Expr *E) {
4042 return Success(Value, E, Result);
4043 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00004044
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004045 bool Success(CharUnits Size, const Expr *E) {
4046 return Success(Size.getQuantity(), E);
4047 }
4048
Richard Smith1aa0be82012-03-03 22:46:17 +00004049 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00004050 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00004051 Result = V;
4052 return true;
4053 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004054 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00004055 }
Mike Stump1eb44332009-09-09 15:08:12 +00004056
Richard Smith51201882011-12-30 21:15:51 +00004057 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00004058
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004059 //===--------------------------------------------------------------------===//
4060 // Visitor Methods
4061 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004062
Chris Lattner4c4867e2008-07-12 00:38:25 +00004063 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004064 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004065 }
4066 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004067 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004068 }
Eli Friedman04309752009-11-24 05:28:59 +00004069
4070 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4071 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004072 if (CheckReferencedDecl(E, E->getDecl()))
4073 return true;
4074
4075 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004076 }
4077 bool VisitMemberExpr(const MemberExpr *E) {
4078 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004079 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004080 return true;
4081 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004082
4083 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004084 }
4085
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004086 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004087 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004088 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004089 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004090
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004091 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004092 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004093
Anders Carlsson3068d112008-11-16 19:01:22 +00004094 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004095 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004096 }
Mike Stump1eb44332009-09-09 15:08:12 +00004097
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004098 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4099 return Success(E->getValue(), E);
4100 }
4101
Richard Smithf10d9172011-10-11 21:43:33 +00004102 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004103 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004104 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004105 }
4106
Sebastian Redl64b45f72009-01-05 20:52:13 +00004107 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004108 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004109 }
4110
Francois Pichet6ad6f282010-12-07 00:08:36 +00004111 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4112 return Success(E->getValue(), E);
4113 }
4114
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004115 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4116 return Success(E->getValue(), E);
4117 }
4118
John Wiegley21ff2e52011-04-28 00:16:57 +00004119 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4120 return Success(E->getValue(), E);
4121 }
4122
John Wiegley55262202011-04-25 06:54:41 +00004123 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4124 return Success(E->getValue(), E);
4125 }
4126
Eli Friedman722c7172009-02-28 03:59:05 +00004127 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004128 bool VisitUnaryImag(const UnaryOperator *E);
4129
Sebastian Redl295995c2010-09-10 20:55:47 +00004130 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004131 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004132
Chris Lattnerfcee0012008-07-11 21:24:13 +00004133private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004134 CharUnits GetAlignOfExpr(const Expr *E);
4135 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004136 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004137 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004138 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004139};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004140} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004141
Richard Smithc49bd112011-10-28 17:51:58 +00004142/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4143/// produce either the integer value or a pointer.
4144///
4145/// GCC has a heinous extension which folds casts between pointer types and
4146/// pointer-sized integral types. We support this by allowing the evaluation of
4147/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4148/// Some simple arithmetic on such values is supported (they are treated much
4149/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004150static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004151 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004152 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004153 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004154}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004155
Richard Smithf48fdb02011-12-09 22:58:01 +00004156static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004157 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004158 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004159 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004160 if (!Val.isInt()) {
4161 // FIXME: It would be better to produce the diagnostic for casting
4162 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004163 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004164 return false;
4165 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004166 Result = Val.getInt();
4167 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004168}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004169
Richard Smithf48fdb02011-12-09 22:58:01 +00004170/// Check whether the given declaration can be directly converted to an integral
4171/// rvalue. If not, no diagnostic is produced; there are other things we can
4172/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004173bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004174 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004175 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004176 // Check for signedness/width mismatches between E type and ECD value.
4177 bool SameSign = (ECD->getInitVal().isSigned()
4178 == E->getType()->isSignedIntegerOrEnumerationType());
4179 bool SameWidth = (ECD->getInitVal().getBitWidth()
4180 == Info.Ctx.getIntWidth(E->getType()));
4181 if (SameSign && SameWidth)
4182 return Success(ECD->getInitVal(), E);
4183 else {
4184 // Get rid of mismatch (otherwise Success assertions will fail)
4185 // by computing a new value matching the type of E.
4186 llvm::APSInt Val = ECD->getInitVal();
4187 if (!SameSign)
4188 Val.setIsSigned(!ECD->getInitVal().isSigned());
4189 if (!SameWidth)
4190 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4191 return Success(Val, E);
4192 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004193 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004194 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004195}
4196
Chris Lattnera4d55d82008-10-06 06:40:35 +00004197/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4198/// as GCC.
4199static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4200 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004201 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004202 enum gcc_type_class {
4203 no_type_class = -1,
4204 void_type_class, integer_type_class, char_type_class,
4205 enumeral_type_class, boolean_type_class,
4206 pointer_type_class, reference_type_class, offset_type_class,
4207 real_type_class, complex_type_class,
4208 function_type_class, method_type_class,
4209 record_type_class, union_type_class,
4210 array_type_class, string_type_class,
4211 lang_type_class
4212 };
Mike Stump1eb44332009-09-09 15:08:12 +00004213
4214 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004215 // ideal, however it is what gcc does.
4216 if (E->getNumArgs() == 0)
4217 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004218
Chris Lattnera4d55d82008-10-06 06:40:35 +00004219 QualType ArgTy = E->getArg(0)->getType();
4220 if (ArgTy->isVoidType())
4221 return void_type_class;
4222 else if (ArgTy->isEnumeralType())
4223 return enumeral_type_class;
4224 else if (ArgTy->isBooleanType())
4225 return boolean_type_class;
4226 else if (ArgTy->isCharType())
4227 return string_type_class; // gcc doesn't appear to use char_type_class
4228 else if (ArgTy->isIntegerType())
4229 return integer_type_class;
4230 else if (ArgTy->isPointerType())
4231 return pointer_type_class;
4232 else if (ArgTy->isReferenceType())
4233 return reference_type_class;
4234 else if (ArgTy->isRealType())
4235 return real_type_class;
4236 else if (ArgTy->isComplexType())
4237 return complex_type_class;
4238 else if (ArgTy->isFunctionType())
4239 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004240 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004241 return record_type_class;
4242 else if (ArgTy->isUnionType())
4243 return union_type_class;
4244 else if (ArgTy->isArrayType())
4245 return array_type_class;
4246 else if (ArgTy->isUnionType())
4247 return union_type_class;
4248 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004249 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004250}
4251
Richard Smith80d4b552011-12-28 19:48:30 +00004252/// EvaluateBuiltinConstantPForLValue - Determine the result of
4253/// __builtin_constant_p when applied to the given lvalue.
4254///
4255/// An lvalue is only "constant" if it is a pointer or reference to the first
4256/// character of a string literal.
4257template<typename LValue>
4258static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004259 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004260 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4261}
4262
4263/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4264/// GCC as we can manage.
4265static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4266 QualType ArgType = Arg->getType();
4267
4268 // __builtin_constant_p always has one operand. The rules which gcc follows
4269 // are not precisely documented, but are as follows:
4270 //
4271 // - If the operand is of integral, floating, complex or enumeration type,
4272 // and can be folded to a known value of that type, it returns 1.
4273 // - If the operand and can be folded to a pointer to the first character
4274 // of a string literal (or such a pointer cast to an integral type), it
4275 // returns 1.
4276 //
4277 // Otherwise, it returns 0.
4278 //
4279 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4280 // its support for this does not currently work.
4281 if (ArgType->isIntegralOrEnumerationType()) {
4282 Expr::EvalResult Result;
4283 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4284 return false;
4285
4286 APValue &V = Result.Val;
4287 if (V.getKind() == APValue::Int)
4288 return true;
4289
4290 return EvaluateBuiltinConstantPForLValue(V);
4291 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4292 return Arg->isEvaluatable(Ctx);
4293 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4294 LValue LV;
4295 Expr::EvalStatus Status;
4296 EvalInfo Info(Ctx, Status);
4297 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4298 : EvaluatePointer(Arg, LV, Info)) &&
4299 !Status.HasSideEffects)
4300 return EvaluateBuiltinConstantPForLValue(LV);
4301 }
4302
4303 // Anything else isn't considered to be sufficiently constant.
4304 return false;
4305}
4306
John McCall42c8f872010-05-10 23:27:23 +00004307/// Retrieves the "underlying object type" of the given expression,
4308/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004309QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4310 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4311 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004312 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004313 } else if (const Expr *E = B.get<const Expr*>()) {
4314 if (isa<CompoundLiteralExpr>(E))
4315 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004316 }
4317
4318 return QualType();
4319}
4320
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004321bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004322 LValue Base;
Richard Smithc6794852012-05-23 04:13:20 +00004323
4324 {
4325 // The operand of __builtin_object_size is never evaluated for side-effects.
4326 // If there are any, but we can determine the pointed-to object anyway, then
4327 // ignore the side-effects.
4328 SpeculativeEvaluationRAII SpeculativeEval(Info);
4329 if (!EvaluatePointer(E->getArg(0), Base, Info))
4330 return false;
4331 }
John McCall42c8f872010-05-10 23:27:23 +00004332
4333 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004334 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004335
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004336 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004337 if (T.isNull() ||
4338 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004339 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004340 T->isVariablyModifiedType() ||
4341 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004342 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004343
4344 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4345 CharUnits Offset = Base.getLValueOffset();
4346
4347 if (!Offset.isNegative() && Offset <= Size)
4348 Size -= Offset;
4349 else
4350 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004351 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004352}
4353
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004354bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith2c39d712012-04-13 00:45:38 +00004355 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004356 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004357 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004358
4359 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004360 if (TryEvaluateBuiltinObjectSize(E))
4361 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004362
Eric Christopherb2aaf512010-01-19 22:58:35 +00004363 // If evaluating the argument has side-effects we can't determine
Richard Smithc6794852012-05-23 04:13:20 +00004364 // the size of the object and lower it to unknown now. CodeGen relies on
4365 // us to handle all cases where the expression has side-effects.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004366 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004367 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004368 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004369 return Success(0, E);
4370 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004371
Richard Smithc6794852012-05-23 04:13:20 +00004372 // Expression had no side effects, but we couldn't statically determine the
4373 // size of the referenced object.
Richard Smithf48fdb02011-12-09 22:58:01 +00004374 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004375 }
4376
Chris Lattner019f4e82008-10-06 05:28:25 +00004377 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004378 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004379
Richard Smith80d4b552011-12-28 19:48:30 +00004380 case Builtin::BI__builtin_constant_p:
4381 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004382
Chris Lattner21fb98e2009-09-23 06:06:36 +00004383 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004384 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004385 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004386 return Success(Operand, E);
4387 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004388
4389 case Builtin::BI__builtin_expect:
4390 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004391
Douglas Gregor5726d402010-09-10 06:27:15 +00004392 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004393 // A call to strlen is not a constant expression.
4394 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004395 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004396 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4397 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004398 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004399 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004400 case Builtin::BI__builtin_strlen:
4401 // As an extension, we support strlen() and __builtin_strlen() as constant
4402 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004403 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004404 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4405 // The string literal may have embedded null characters. Find the first
4406 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004407 StringRef Str = S->getString();
4408 StringRef::size_type Pos = Str.find(0);
4409 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004410 Str = Str.substr(0, Pos);
4411
4412 return Success(Str.size(), E);
4413 }
4414
Richard Smithf48fdb02011-12-09 22:58:01 +00004415 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004416
Richard Smith2c39d712012-04-13 00:45:38 +00004417 case Builtin::BI__atomic_always_lock_free:
Richard Smithfafbf062012-04-11 17:55:32 +00004418 case Builtin::BI__atomic_is_lock_free:
4419 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedman454b57a2011-10-17 21:44:23 +00004420 APSInt SizeVal;
4421 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4422 return false;
4423
4424 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4425 // of two less than the maximum inline atomic width, we know it is
4426 // lock-free. If the size isn't a power of two, or greater than the
4427 // maximum alignment where we promote atomics, we know it is not lock-free
4428 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4429 // the answer can only be determined at runtime; for example, 16-byte
4430 // atomics have lock-free implementations on some, but not all,
4431 // x86-64 processors.
4432
4433 // Check power-of-two.
4434 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith2c39d712012-04-13 00:45:38 +00004435 if (Size.isPowerOfTwo()) {
4436 // Check against inlining width.
4437 unsigned InlineWidthBits =
4438 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4439 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4440 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4441 Size == CharUnits::One() ||
4442 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4443 Expr::NPC_NeverValueDependent))
4444 // OK, we will inline appropriately-aligned operations of this size,
4445 // and _Atomic(T) is appropriately-aligned.
4446 return Success(1, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004447
Richard Smith2c39d712012-04-13 00:45:38 +00004448 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4449 castAs<PointerType>()->getPointeeType();
4450 if (!PointeeType->isIncompleteType() &&
4451 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4452 // OK, we will inline operations on this object.
4453 return Success(1, E);
4454 }
4455 }
4456 }
Eli Friedman454b57a2011-10-17 21:44:23 +00004457
Richard Smith2c39d712012-04-13 00:45:38 +00004458 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4459 Success(0, E) : Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004460 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004461 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004462}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004463
Richard Smith625b8072011-10-31 01:37:14 +00004464static bool HasSameBase(const LValue &A, const LValue &B) {
4465 if (!A.getLValueBase())
4466 return !B.getLValueBase();
4467 if (!B.getLValueBase())
4468 return false;
4469
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004470 if (A.getLValueBase().getOpaqueValue() !=
4471 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004472 const Decl *ADecl = GetLValueBaseDecl(A);
4473 if (!ADecl)
4474 return false;
4475 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004476 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004477 return false;
4478 }
4479
4480 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004481 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004482}
4483
Richard Smith7b48a292012-02-01 05:53:12 +00004484/// Perform the given integer operation, which is known to need at most BitWidth
4485/// bits, and check for overflow in the original type (if that type was not an
4486/// unsigned type).
4487template<typename Operation>
4488static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4489 const APSInt &LHS, const APSInt &RHS,
4490 unsigned BitWidth, Operation Op) {
4491 if (LHS.isUnsigned())
4492 return Op(LHS, RHS);
4493
4494 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4495 APSInt Result = Value.trunc(LHS.getBitWidth());
4496 if (Result.extend(BitWidth) != Value)
4497 HandleOverflow(Info, E, Value, E->getType());
4498 return Result;
4499}
4500
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004501namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00004502
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004503/// \brief Data recursive integer evaluator of certain binary operators.
4504///
4505/// We use a data recursive algorithm for binary operators so that we are able
4506/// to handle extreme cases of chained binary operators without causing stack
4507/// overflow.
4508class DataRecursiveIntBinOpEvaluator {
4509 struct EvalResult {
4510 APValue Val;
4511 bool Failed;
4512
4513 EvalResult() : Failed(false) { }
4514
4515 void swap(EvalResult &RHS) {
4516 Val.swap(RHS.Val);
4517 Failed = RHS.Failed;
4518 RHS.Failed = false;
4519 }
4520 };
4521
4522 struct Job {
4523 const Expr *E;
4524 EvalResult LHSResult; // meaningful only for binary operator expression.
4525 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4526
4527 Job() : StoredInfo(0) { }
4528 void startSpeculativeEval(EvalInfo &Info) {
4529 OldEvalStatus = Info.EvalStatus;
4530 Info.EvalStatus.Diag = 0;
4531 StoredInfo = &Info;
4532 }
4533 ~Job() {
4534 if (StoredInfo) {
4535 StoredInfo->EvalStatus = OldEvalStatus;
4536 }
4537 }
4538 private:
4539 EvalInfo *StoredInfo; // non-null if status changed.
4540 Expr::EvalStatus OldEvalStatus;
4541 };
4542
4543 SmallVector<Job, 16> Queue;
4544
4545 IntExprEvaluator &IntEval;
4546 EvalInfo &Info;
4547 APValue &FinalResult;
4548
4549public:
4550 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4551 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4552
4553 /// \brief True if \param E is a binary operator that we are going to handle
4554 /// data recursively.
4555 /// We handle binary operators that are comma, logical, or that have operands
4556 /// with integral or enumeration type.
4557 static bool shouldEnqueue(const BinaryOperator *E) {
4558 return E->getOpcode() == BO_Comma ||
4559 E->isLogicalOp() ||
4560 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4561 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00004562 }
4563
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004564 bool Traverse(const BinaryOperator *E) {
4565 enqueue(E);
4566 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00004567 while (!Queue.empty())
4568 process(PrevResult);
4569
4570 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004571
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004572 FinalResult.swap(PrevResult.Val);
4573 return true;
4574 }
4575
4576private:
4577 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4578 return IntEval.Success(Value, E, Result);
4579 }
4580 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4581 return IntEval.Success(Value, E, Result);
4582 }
4583 bool Error(const Expr *E) {
4584 return IntEval.Error(E);
4585 }
4586 bool Error(const Expr *E, diag::kind D) {
4587 return IntEval.Error(E, D);
4588 }
4589
4590 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4591 return Info.CCEDiag(E, D);
4592 }
4593
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004594 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4595 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004596 bool &SuppressRHSDiags);
4597
4598 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4599 const BinaryOperator *E, APValue &Result);
4600
4601 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4602 Result.Failed = !Evaluate(Result.Val, Info, E);
4603 if (Result.Failed)
4604 Result.Val = APValue();
4605 }
4606
Richard Trieub7783052012-03-21 23:30:30 +00004607 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004608
4609 void enqueue(const Expr *E) {
4610 E = E->IgnoreParens();
4611 Queue.resize(Queue.size()+1);
4612 Queue.back().E = E;
4613 Queue.back().Kind = Job::AnyExprKind;
4614 }
4615};
4616
4617}
4618
4619bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004620 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004621 bool &SuppressRHSDiags) {
4622 if (E->getOpcode() == BO_Comma) {
4623 // Ignore LHS but note if we could not evaluate it.
4624 if (LHSResult.Failed)
4625 Info.EvalStatus.HasSideEffects = true;
4626 return true;
4627 }
4628
4629 if (E->isLogicalOp()) {
4630 bool lhsResult;
4631 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004632 // We were able to evaluate the LHS, see if we can get away with not
4633 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004634 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004635 Success(lhsResult, E, LHSResult.Val);
4636 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004637 }
4638 } else {
4639 // Since we weren't able to evaluate the left hand side, it
4640 // must have had side effects.
4641 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004642
4643 // We can't evaluate the LHS; however, sometimes the result
4644 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4645 // Don't ignore RHS and suppress diagnostics from this arm.
4646 SuppressRHSDiags = true;
4647 }
4648
4649 return true;
4650 }
4651
4652 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4653 E->getRHS()->getType()->isIntegralOrEnumerationType());
4654
4655 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004656 return false; // Ignore RHS;
4657
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004658 return true;
4659}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004660
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004661bool DataRecursiveIntBinOpEvaluator::
4662 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4663 const BinaryOperator *E, APValue &Result) {
4664 if (E->getOpcode() == BO_Comma) {
4665 if (RHSResult.Failed)
4666 return false;
4667 Result = RHSResult.Val;
4668 return true;
4669 }
4670
4671 if (E->isLogicalOp()) {
4672 bool lhsResult, rhsResult;
4673 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4674 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4675
4676 if (LHSIsOK) {
4677 if (RHSIsOK) {
4678 if (E->getOpcode() == BO_LOr)
4679 return Success(lhsResult || rhsResult, E, Result);
4680 else
4681 return Success(lhsResult && rhsResult, E, Result);
4682 }
4683 } else {
4684 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004685 // We can't evaluate the LHS; however, sometimes the result
4686 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4687 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004688 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004689 }
4690 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004691
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004692 return false;
4693 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004694
4695 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4696 E->getRHS()->getType()->isIntegralOrEnumerationType());
4697
4698 if (LHSResult.Failed || RHSResult.Failed)
4699 return false;
4700
4701 const APValue &LHSVal = LHSResult.Val;
4702 const APValue &RHSVal = RHSResult.Val;
4703
4704 // Handle cases like (unsigned long)&a + 4.
4705 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4706 Result = LHSVal;
4707 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4708 RHSVal.getInt().getZExtValue());
4709 if (E->getOpcode() == BO_Add)
4710 Result.getLValueOffset() += AdditionalOffset;
4711 else
4712 Result.getLValueOffset() -= AdditionalOffset;
4713 return true;
4714 }
4715
4716 // Handle cases like 4 + (unsigned long)&a
4717 if (E->getOpcode() == BO_Add &&
4718 RHSVal.isLValue() && LHSVal.isInt()) {
4719 Result = RHSVal;
4720 Result.getLValueOffset() += CharUnits::fromQuantity(
4721 LHSVal.getInt().getZExtValue());
4722 return true;
4723 }
4724
4725 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4726 // Handle (intptr_t)&&A - (intptr_t)&&B.
4727 if (!LHSVal.getLValueOffset().isZero() ||
4728 !RHSVal.getLValueOffset().isZero())
4729 return false;
4730 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4731 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4732 if (!LHSExpr || !RHSExpr)
4733 return false;
4734 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4735 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4736 if (!LHSAddrExpr || !RHSAddrExpr)
4737 return false;
4738 // Make sure both labels come from the same function.
4739 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4740 RHSAddrExpr->getLabel()->getDeclContext())
4741 return false;
4742 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4743 return true;
4744 }
4745
4746 // All the following cases expect both operands to be an integer
4747 if (!LHSVal.isInt() || !RHSVal.isInt())
4748 return Error(E);
4749
4750 const APSInt &LHS = LHSVal.getInt();
4751 APSInt RHS = RHSVal.getInt();
4752
4753 switch (E->getOpcode()) {
4754 default:
4755 return Error(E);
4756 case BO_Mul:
4757 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4758 LHS.getBitWidth() * 2,
4759 std::multiplies<APSInt>()), E,
4760 Result);
4761 case BO_Add:
4762 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4763 LHS.getBitWidth() + 1,
4764 std::plus<APSInt>()), E, Result);
4765 case BO_Sub:
4766 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4767 LHS.getBitWidth() + 1,
4768 std::minus<APSInt>()), E, Result);
4769 case BO_And: return Success(LHS & RHS, E, Result);
4770 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4771 case BO_Or: return Success(LHS | RHS, E, Result);
4772 case BO_Div:
4773 case BO_Rem:
4774 if (RHS == 0)
4775 return Error(E, diag::note_expr_divide_by_zero);
4776 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4777 // not actually undefined behavior in C++11 due to a language defect.
4778 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4779 LHS.isSigned() && LHS.isMinSignedValue())
4780 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4781 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4782 Result);
4783 case BO_Shl: {
4784 // During constant-folding, a negative shift is an opposite shift. Such
4785 // a shift is not a constant expression.
4786 if (RHS.isSigned() && RHS.isNegative()) {
4787 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4788 RHS = -RHS;
4789 goto shift_right;
4790 }
4791
4792 shift_left:
4793 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4794 // the shifted type.
4795 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4796 if (SA != RHS) {
4797 CCEDiag(E, diag::note_constexpr_large_shift)
4798 << RHS << E->getType() << LHS.getBitWidth();
4799 } else if (LHS.isSigned()) {
4800 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4801 // operand, and must not overflow the corresponding unsigned type.
4802 if (LHS.isNegative())
4803 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4804 else if (LHS.countLeadingZeros() < SA)
4805 CCEDiag(E, diag::note_constexpr_lshift_discards);
4806 }
4807
4808 return Success(LHS << SA, E, Result);
4809 }
4810 case BO_Shr: {
4811 // During constant-folding, a negative shift is an opposite shift. Such a
4812 // shift is not a constant expression.
4813 if (RHS.isSigned() && RHS.isNegative()) {
4814 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4815 RHS = -RHS;
4816 goto shift_left;
4817 }
4818
4819 shift_right:
4820 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4821 // shifted type.
4822 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4823 if (SA != RHS)
4824 CCEDiag(E, diag::note_constexpr_large_shift)
4825 << RHS << E->getType() << LHS.getBitWidth();
4826
4827 return Success(LHS >> SA, E, Result);
4828 }
4829
4830 case BO_LT: return Success(LHS < RHS, E, Result);
4831 case BO_GT: return Success(LHS > RHS, E, Result);
4832 case BO_LE: return Success(LHS <= RHS, E, Result);
4833 case BO_GE: return Success(LHS >= RHS, E, Result);
4834 case BO_EQ: return Success(LHS == RHS, E, Result);
4835 case BO_NE: return Success(LHS != RHS, E, Result);
4836 }
4837}
4838
Richard Trieub7783052012-03-21 23:30:30 +00004839void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004840 Job &job = Queue.back();
4841
4842 switch (job.Kind) {
4843 case Job::AnyExprKind: {
4844 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4845 if (shouldEnqueue(Bop)) {
4846 job.Kind = Job::BinOpKind;
4847 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00004848 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004849 }
4850 }
4851
4852 EvaluateExpr(job.E, Result);
4853 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004854 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004855 }
4856
4857 case Job::BinOpKind: {
4858 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004859 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004860 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004861 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004862 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004863 }
4864 if (SuppressRHSDiags)
4865 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004866 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004867 job.Kind = Job::BinOpVisitedLHSKind;
4868 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00004869 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004870 }
4871
4872 case Job::BinOpVisitedLHSKind: {
4873 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4874 EvalResult RHS;
4875 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00004876 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004877 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004878 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004879 }
4880 }
4881
4882 llvm_unreachable("Invalid Job::Kind!");
4883}
4884
4885bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4886 if (E->isAssignmentOp())
4887 return Error(E);
4888
4889 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4890 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004891
Anders Carlsson286f85e2008-11-16 07:17:21 +00004892 QualType LHSTy = E->getLHS()->getType();
4893 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004894
4895 if (LHSTy->isAnyComplexType()) {
4896 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004897 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004898
Richard Smith745f5142012-01-27 01:14:48 +00004899 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4900 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004901 return false;
4902
Richard Smith745f5142012-01-27 01:14:48 +00004903 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004904 return false;
4905
4906 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004907 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004908 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004909 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004910 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4911
John McCall2de56d12010-08-25 11:45:40 +00004912 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004913 return Success((CR_r == APFloat::cmpEqual &&
4914 CR_i == APFloat::cmpEqual), E);
4915 else {
John McCall2de56d12010-08-25 11:45:40 +00004916 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004917 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004918 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004919 CR_r == APFloat::cmpLessThan ||
4920 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004921 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004922 CR_i == APFloat::cmpLessThan ||
4923 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004924 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004925 } else {
John McCall2de56d12010-08-25 11:45:40 +00004926 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004927 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4928 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4929 else {
John McCall2de56d12010-08-25 11:45:40 +00004930 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004931 "Invalid compex comparison.");
4932 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4933 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4934 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004935 }
4936 }
Mike Stump1eb44332009-09-09 15:08:12 +00004937
Anders Carlsson286f85e2008-11-16 07:17:21 +00004938 if (LHSTy->isRealFloatingType() &&
4939 RHSTy->isRealFloatingType()) {
4940 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004941
Richard Smith745f5142012-01-27 01:14:48 +00004942 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4943 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004944 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004945
Richard Smith745f5142012-01-27 01:14:48 +00004946 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004947 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004948
Anders Carlsson286f85e2008-11-16 07:17:21 +00004949 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004950
Anders Carlsson286f85e2008-11-16 07:17:21 +00004951 switch (E->getOpcode()) {
4952 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004953 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004954 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004955 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004956 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004957 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004958 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004959 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004960 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004961 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004962 E);
John McCall2de56d12010-08-25 11:45:40 +00004963 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004964 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004965 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004966 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004967 || CR == APFloat::cmpLessThan
4968 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004969 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004970 }
Mike Stump1eb44332009-09-09 15:08:12 +00004971
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004972 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004973 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004974 LValue LHSValue, RHSValue;
4975
4976 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4977 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004978 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004979
Richard Smith745f5142012-01-27 01:14:48 +00004980 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004981 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004982
Richard Smith625b8072011-10-31 01:37:14 +00004983 // Reject differing bases from the normal codepath; we special-case
4984 // comparisons to null.
4985 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004986 if (E->getOpcode() == BO_Sub) {
4987 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004988 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4989 return false;
4990 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4991 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4992 if (!LHSExpr || !RHSExpr)
4993 return false;
4994 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4995 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4996 if (!LHSAddrExpr || !RHSAddrExpr)
4997 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004998 // Make sure both labels come from the same function.
4999 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5000 RHSAddrExpr->getLabel()->getDeclContext())
5001 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00005002 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00005003 return true;
5004 }
Richard Smith9e36b532011-10-31 05:11:32 +00005005 // Inequalities and subtractions between unrelated pointers have
5006 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00005007 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00005008 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00005009 // A constant address may compare equal to the address of a symbol.
5010 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00005011 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00005012 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5013 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00005014 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00005015 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00005016 // distinct addresses. In clang, the result of such a comparison is
5017 // unspecified, so it is not a constant expression. However, we do know
5018 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00005019 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5020 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00005021 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00005022 // We can't tell whether weak symbols will end up pointing to the same
5023 // object.
5024 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00005025 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00005026 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00005027 // (Note that clang defaults to -fmerge-all-constants, which can
5028 // lead to inconsistent results for comparisons involving the address
5029 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00005030 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00005031 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005032
Richard Smith15efc4d2012-02-01 08:10:20 +00005033 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5034 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5035
Richard Smithf15fda02012-02-02 01:16:57 +00005036 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5037 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5038
John McCall2de56d12010-08-25 11:45:40 +00005039 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00005040 // C++11 [expr.add]p6:
5041 // Unless both pointers point to elements of the same array object, or
5042 // one past the last element of the array object, the behavior is
5043 // undefined.
5044 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5045 !AreElementsOfSameArray(getType(LHSValue.Base),
5046 LHSDesignator, RHSDesignator))
5047 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5048
Chris Lattner4992bdd2010-04-20 17:13:14 +00005049 QualType Type = E->getLHS()->getType();
5050 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00005051
Richard Smith180f4792011-11-10 06:34:14 +00005052 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00005053 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00005054 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00005055
Richard Smith15efc4d2012-02-01 08:10:20 +00005056 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5057 // and produce incorrect results when it overflows. Such behavior
5058 // appears to be non-conforming, but is common, so perhaps we should
5059 // assume the standard intended for such cases to be undefined behavior
5060 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00005061
Richard Smith15efc4d2012-02-01 08:10:20 +00005062 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5063 // overflow in the final conversion to ptrdiff_t.
5064 APSInt LHS(
5065 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5066 APSInt RHS(
5067 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5068 APSInt ElemSize(
5069 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5070 APSInt TrueResult = (LHS - RHS) / ElemSize;
5071 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5072
5073 if (Result.extend(65) != TrueResult)
5074 HandleOverflow(Info, E, TrueResult, E->getType());
5075 return Success(Result, E);
5076 }
Richard Smith82f28582012-01-31 06:41:30 +00005077
5078 // C++11 [expr.rel]p3:
5079 // Pointers to void (after pointer conversions) can be compared, with a
5080 // result defined as follows: If both pointers represent the same
5081 // address or are both the null pointer value, the result is true if the
5082 // operator is <= or >= and false otherwise; otherwise the result is
5083 // unspecified.
5084 // We interpret this as applying to pointers to *cv* void.
5085 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00005086 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00005087 CCEDiag(E, diag::note_constexpr_void_comparison);
5088
Richard Smithf15fda02012-02-02 01:16:57 +00005089 // C++11 [expr.rel]p2:
5090 // - If two pointers point to non-static data members of the same object,
5091 // or to subobjects or array elements fo such members, recursively, the
5092 // pointer to the later declared member compares greater provided the
5093 // two members have the same access control and provided their class is
5094 // not a union.
5095 // [...]
5096 // - Otherwise pointer comparisons are unspecified.
5097 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5098 E->isRelationalOp()) {
5099 bool WasArrayIndex;
5100 unsigned Mismatch =
5101 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5102 RHSDesignator, WasArrayIndex);
5103 // At the point where the designators diverge, the comparison has a
5104 // specified value if:
5105 // - we are comparing array indices
5106 // - we are comparing fields of a union, or fields with the same access
5107 // Otherwise, the result is unspecified and thus the comparison is not a
5108 // constant expression.
5109 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5110 Mismatch < RHSDesignator.Entries.size()) {
5111 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5112 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5113 if (!LF && !RF)
5114 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5115 else if (!LF)
5116 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5117 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5118 << RF->getParent() << RF;
5119 else if (!RF)
5120 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5121 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5122 << LF->getParent() << LF;
5123 else if (!LF->getParent()->isUnion() &&
5124 LF->getAccess() != RF->getAccess())
5125 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5126 << LF << LF->getAccess() << RF << RF->getAccess()
5127 << LF->getParent();
5128 }
5129 }
5130
Eli Friedmana3169882012-04-16 04:30:08 +00005131 // The comparison here must be unsigned, and performed with the same
5132 // width as the pointer.
Eli Friedmana3169882012-04-16 04:30:08 +00005133 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5134 uint64_t CompareLHS = LHSOffset.getQuantity();
5135 uint64_t CompareRHS = RHSOffset.getQuantity();
5136 assert(PtrSize <= 64 && "Unexpected pointer width");
5137 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5138 CompareLHS &= Mask;
5139 CompareRHS &= Mask;
5140
Eli Friedman28503762012-04-16 19:23:57 +00005141 // If there is a base and this is a relational operator, we can only
5142 // compare pointers within the object in question; otherwise, the result
5143 // depends on where the object is located in memory.
5144 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5145 QualType BaseTy = getType(LHSValue.Base);
5146 if (BaseTy->isIncompleteType())
5147 return Error(E);
5148 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5149 uint64_t OffsetLimit = Size.getQuantity();
5150 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5151 return Error(E);
5152 }
5153
Richard Smith625b8072011-10-31 01:37:14 +00005154 switch (E->getOpcode()) {
5155 default: llvm_unreachable("missing comparison operator");
Eli Friedmana3169882012-04-16 04:30:08 +00005156 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5157 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5158 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5159 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5160 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5161 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00005162 }
Anders Carlsson3068d112008-11-16 19:01:22 +00005163 }
5164 }
Richard Smithb02e4622012-02-01 01:42:44 +00005165
5166 if (LHSTy->isMemberPointerType()) {
5167 assert(E->isEqualityOp() && "unexpected member pointer operation");
5168 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5169
5170 MemberPtr LHSValue, RHSValue;
5171
5172 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5173 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5174 return false;
5175
5176 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5177 return false;
5178
5179 // C++11 [expr.eq]p2:
5180 // If both operands are null, they compare equal. Otherwise if only one is
5181 // null, they compare unequal.
5182 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5183 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5184 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5185 }
5186
5187 // Otherwise if either is a pointer to a virtual member function, the
5188 // result is unspecified.
5189 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5190 if (MD->isVirtual())
5191 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5192 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5193 if (MD->isVirtual())
5194 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5195
5196 // Otherwise they compare equal if and only if they would refer to the
5197 // same member of the same most derived object or the same subobject if
5198 // they were dereferenced with a hypothetical object of the associated
5199 // class type.
5200 bool Equal = LHSValue == RHSValue;
5201 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5202 }
5203
Richard Smith26f2cac2012-02-14 22:35:28 +00005204 if (LHSTy->isNullPtrType()) {
5205 assert(E->isComparisonOp() && "unexpected nullptr operation");
5206 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5207 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5208 // are compared, the result is true of the operator is <=, >= or ==, and
5209 // false otherwise.
5210 BinaryOperator::Opcode Opcode = E->getOpcode();
5211 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5212 }
5213
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005214 assert((!LHSTy->isIntegralOrEnumerationType() ||
5215 !RHSTy->isIntegralOrEnumerationType()) &&
5216 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5217 // We can't continue from here for non-integral types.
5218 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005219}
5220
Ken Dyck8b752f12010-01-27 17:10:57 +00005221CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005222 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5223 // result shall be the alignment of the referenced type."
5224 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5225 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005226
5227 // __alignof is defined to return the preferred alignment.
5228 return Info.Ctx.toCharUnitsFromBits(
5229 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005230}
5231
Ken Dyck8b752f12010-01-27 17:10:57 +00005232CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005233 E = E->IgnoreParens();
5234
5235 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005236 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005237 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005238 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5239 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005240
Chris Lattneraf707ab2009-01-24 21:53:27 +00005241 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005242 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5243 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005244
Chris Lattnere9feb472009-01-24 21:09:06 +00005245 return GetAlignOfType(E->getType());
5246}
5247
5248
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005249/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5250/// a result as the expression's type.
5251bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5252 const UnaryExprOrTypeTraitExpr *E) {
5253 switch(E->getKind()) {
5254 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005255 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005256 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005257 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005258 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005259 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005260
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005261 case UETT_VecStep: {
5262 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005263
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005264 if (Ty->isVectorType()) {
5265 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005266
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005267 // The vec_step built-in functions that take a 3-component
5268 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5269 if (n == 3)
5270 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005271
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005272 return Success(n, E);
5273 } else
5274 return Success(1, E);
5275 }
5276
5277 case UETT_SizeOf: {
5278 QualType SrcTy = E->getTypeOfArgument();
5279 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5280 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005281 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5282 SrcTy = Ref->getPointeeType();
5283
Richard Smith180f4792011-11-10 06:34:14 +00005284 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005285 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005286 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005287 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005288 }
5289 }
5290
5291 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005292}
5293
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005294bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005295 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005296 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005297 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005298 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005299 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005300 for (unsigned i = 0; i != n; ++i) {
5301 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5302 switch (ON.getKind()) {
5303 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005304 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005305 APSInt IdxResult;
5306 if (!EvaluateInteger(Idx, IdxResult, Info))
5307 return false;
5308 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5309 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005310 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005311 CurrentType = AT->getElementType();
5312 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5313 Result += IdxResult.getSExtValue() * ElementSize;
5314 break;
5315 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005316
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005317 case OffsetOfExpr::OffsetOfNode::Field: {
5318 FieldDecl *MemberDecl = ON.getField();
5319 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005320 if (!RT)
5321 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005322 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005323 if (RD->isInvalidDecl()) return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005324 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005325 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005326 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005327 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005328 CurrentType = MemberDecl->getType().getNonReferenceType();
5329 break;
5330 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005331
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005332 case OffsetOfExpr::OffsetOfNode::Identifier:
5333 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005334
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005335 case OffsetOfExpr::OffsetOfNode::Base: {
5336 CXXBaseSpecifier *BaseSpec = ON.getBase();
5337 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005338 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005339
5340 // Find the layout of the class whose base we are looking into.
5341 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005342 if (!RT)
5343 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005344 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005345 if (RD->isInvalidDecl()) return false;
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005346 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5347
5348 // Find the base class itself.
5349 CurrentType = BaseSpec->getType();
5350 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5351 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005352 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005353
5354 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005355 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005356 break;
5357 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005358 }
5359 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005360 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005361}
5362
Chris Lattnerb542afe2008-07-11 19:10:17 +00005363bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005364 switch (E->getOpcode()) {
5365 default:
5366 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5367 // See C99 6.6p3.
5368 return Error(E);
5369 case UO_Extension:
5370 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5371 // If so, we could clear the diagnostic ID.
5372 return Visit(E->getSubExpr());
5373 case UO_Plus:
5374 // The result is just the value.
5375 return Visit(E->getSubExpr());
5376 case UO_Minus: {
5377 if (!Visit(E->getSubExpr()))
5378 return false;
5379 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005380 const APSInt &Value = Result.getInt();
5381 if (Value.isSigned() && Value.isMinSignedValue())
5382 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5383 E->getType());
5384 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005385 }
5386 case UO_Not: {
5387 if (!Visit(E->getSubExpr()))
5388 return false;
5389 if (!Result.isInt()) return Error(E);
5390 return Success(~Result.getInt(), E);
5391 }
5392 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005393 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005394 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005395 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005396 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005397 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005398 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005399}
Mike Stump1eb44332009-09-09 15:08:12 +00005400
Chris Lattner732b2232008-07-12 01:15:53 +00005401/// HandleCast - This is used to evaluate implicit or explicit casts where the
5402/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005403bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5404 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005405 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005406 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005407
Eli Friedman46a52322011-03-25 00:43:55 +00005408 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005409 case CK_BaseToDerived:
5410 case CK_DerivedToBase:
5411 case CK_UncheckedDerivedToBase:
5412 case CK_Dynamic:
5413 case CK_ToUnion:
5414 case CK_ArrayToPointerDecay:
5415 case CK_FunctionToPointerDecay:
5416 case CK_NullToPointer:
5417 case CK_NullToMemberPointer:
5418 case CK_BaseToDerivedMemberPointer:
5419 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005420 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005421 case CK_ConstructorConversion:
5422 case CK_IntegralToPointer:
5423 case CK_ToVoid:
5424 case CK_VectorSplat:
5425 case CK_IntegralToFloating:
5426 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005427 case CK_CPointerToObjCPointerCast:
5428 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005429 case CK_AnyPointerToBlockPointerCast:
5430 case CK_ObjCObjectLValueCast:
5431 case CK_FloatingRealToComplex:
5432 case CK_FloatingComplexToReal:
5433 case CK_FloatingComplexCast:
5434 case CK_FloatingComplexToIntegralComplex:
5435 case CK_IntegralRealToComplex:
5436 case CK_IntegralComplexCast:
5437 case CK_IntegralComplexToFloatingComplex:
5438 llvm_unreachable("invalid cast kind for integral value");
5439
Eli Friedmane50c2972011-03-25 19:07:11 +00005440 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005441 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005442 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005443 case CK_ARCProduceObject:
5444 case CK_ARCConsumeObject:
5445 case CK_ARCReclaimReturnedObject:
5446 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005447 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005448 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005449
Richard Smith7d580a42012-01-17 21:17:26 +00005450 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005451 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005452 case CK_AtomicToNonAtomic:
5453 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005454 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005455 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005456
5457 case CK_MemberPointerToBoolean:
5458 case CK_PointerToBoolean:
5459 case CK_IntegralToBoolean:
5460 case CK_FloatingToBoolean:
5461 case CK_FloatingComplexToBoolean:
5462 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005463 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005464 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005465 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005466 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005467 }
5468
Eli Friedman46a52322011-03-25 00:43:55 +00005469 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005470 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005471 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005472
Eli Friedmanbe265702009-02-20 01:15:07 +00005473 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005474 // Allow casts of address-of-label differences if they are no-ops
5475 // or narrowing. (The narrowing case isn't actually guaranteed to
5476 // be constant-evaluatable except in some narrow cases which are hard
5477 // to detect here. We let it through on the assumption the user knows
5478 // what they are doing.)
5479 if (Result.isAddrLabelDiff())
5480 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005481 // Only allow casts of lvalues if they are lossless.
5482 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5483 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005484
Richard Smithf72fccf2012-01-30 22:27:01 +00005485 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5486 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005487 }
Mike Stump1eb44332009-09-09 15:08:12 +00005488
Eli Friedman46a52322011-03-25 00:43:55 +00005489 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005490 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5491
John McCallefdb83e2010-05-07 21:00:08 +00005492 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005493 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005494 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005495
Daniel Dunbardd211642009-02-19 22:24:01 +00005496 if (LV.getLValueBase()) {
5497 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005498 // FIXME: Allow a larger integer size than the pointer size, and allow
5499 // narrowing back down to pointer width in subsequent integral casts.
5500 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005501 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005502 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005503
Richard Smithb755a9d2011-11-16 07:18:12 +00005504 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005505 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005506 return true;
5507 }
5508
Ken Dycka7305832010-01-15 12:37:54 +00005509 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5510 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005511 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005512 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005513
Eli Friedman46a52322011-03-25 00:43:55 +00005514 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005515 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005516 if (!EvaluateComplex(SubExpr, C, Info))
5517 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005518 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005519 }
Eli Friedman2217c872009-02-22 11:46:18 +00005520
Eli Friedman46a52322011-03-25 00:43:55 +00005521 case CK_FloatingToIntegral: {
5522 APFloat F(0.0);
5523 if (!EvaluateFloat(SubExpr, F, Info))
5524 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005525
Richard Smithc1c5f272011-12-13 06:39:58 +00005526 APSInt Value;
5527 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5528 return false;
5529 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005530 }
5531 }
Mike Stump1eb44332009-09-09 15:08:12 +00005532
Eli Friedman46a52322011-03-25 00:43:55 +00005533 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005534}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005535
Eli Friedman722c7172009-02-28 03:59:05 +00005536bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5537 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005538 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005539 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5540 return false;
5541 if (!LV.isComplexInt())
5542 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005543 return Success(LV.getComplexIntReal(), E);
5544 }
5545
5546 return Visit(E->getSubExpr());
5547}
5548
Eli Friedman664a1042009-02-27 04:45:43 +00005549bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005550 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005551 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005552 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5553 return false;
5554 if (!LV.isComplexInt())
5555 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005556 return Success(LV.getComplexIntImag(), E);
5557 }
5558
Richard Smith8327fad2011-10-24 18:44:57 +00005559 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005560 return Success(0, E);
5561}
5562
Douglas Gregoree8aff02011-01-04 17:33:58 +00005563bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5564 return Success(E->getPackLength(), E);
5565}
5566
Sebastian Redl295995c2010-09-10 20:55:47 +00005567bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5568 return Success(E->getValue(), E);
5569}
5570
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005571//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005572// Float Evaluation
5573//===----------------------------------------------------------------------===//
5574
5575namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005576class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005577 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005578 APFloat &Result;
5579public:
5580 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005581 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005582
Richard Smith1aa0be82012-03-03 22:46:17 +00005583 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005584 Result = V.getFloat();
5585 return true;
5586 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005587
Richard Smith51201882011-12-30 21:15:51 +00005588 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005589 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5590 return true;
5591 }
5592
Chris Lattner019f4e82008-10-06 05:28:25 +00005593 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005594
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005595 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005596 bool VisitBinaryOperator(const BinaryOperator *E);
5597 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005598 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005599
John McCallabd3a852010-05-07 22:08:54 +00005600 bool VisitUnaryReal(const UnaryOperator *E);
5601 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005602
Richard Smith51201882011-12-30 21:15:51 +00005603 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005604};
5605} // end anonymous namespace
5606
5607static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005608 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005609 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005610}
5611
Jay Foad4ba2a172011-01-12 09:06:06 +00005612static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005613 QualType ResultTy,
5614 const Expr *Arg,
5615 bool SNaN,
5616 llvm::APFloat &Result) {
5617 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5618 if (!S) return false;
5619
5620 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5621
5622 llvm::APInt fill;
5623
5624 // Treat empty strings as if they were zero.
5625 if (S->getString().empty())
5626 fill = llvm::APInt(32, 0);
5627 else if (S->getString().getAsInteger(0, fill))
5628 return false;
5629
5630 if (SNaN)
5631 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5632 else
5633 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5634 return true;
5635}
5636
Chris Lattner019f4e82008-10-06 05:28:25 +00005637bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005638 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005639 default:
5640 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5641
Chris Lattner019f4e82008-10-06 05:28:25 +00005642 case Builtin::BI__builtin_huge_val:
5643 case Builtin::BI__builtin_huge_valf:
5644 case Builtin::BI__builtin_huge_vall:
5645 case Builtin::BI__builtin_inf:
5646 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005647 case Builtin::BI__builtin_infl: {
5648 const llvm::fltSemantics &Sem =
5649 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005650 Result = llvm::APFloat::getInf(Sem);
5651 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005652 }
Mike Stump1eb44332009-09-09 15:08:12 +00005653
John McCalldb7b72a2010-02-28 13:00:19 +00005654 case Builtin::BI__builtin_nans:
5655 case Builtin::BI__builtin_nansf:
5656 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005657 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5658 true, Result))
5659 return Error(E);
5660 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005661
Chris Lattner9e621712008-10-06 06:31:58 +00005662 case Builtin::BI__builtin_nan:
5663 case Builtin::BI__builtin_nanf:
5664 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005665 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005666 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005667 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5668 false, Result))
5669 return Error(E);
5670 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005671
5672 case Builtin::BI__builtin_fabs:
5673 case Builtin::BI__builtin_fabsf:
5674 case Builtin::BI__builtin_fabsl:
5675 if (!EvaluateFloat(E->getArg(0), Result, Info))
5676 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005677
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005678 if (Result.isNegative())
5679 Result.changeSign();
5680 return true;
5681
Mike Stump1eb44332009-09-09 15:08:12 +00005682 case Builtin::BI__builtin_copysign:
5683 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005684 case Builtin::BI__builtin_copysignl: {
5685 APFloat RHS(0.);
5686 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5687 !EvaluateFloat(E->getArg(1), RHS, Info))
5688 return false;
5689 Result.copySign(RHS);
5690 return true;
5691 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005692 }
5693}
5694
John McCallabd3a852010-05-07 22:08:54 +00005695bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005696 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5697 ComplexValue CV;
5698 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5699 return false;
5700 Result = CV.FloatReal;
5701 return true;
5702 }
5703
5704 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005705}
5706
5707bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005708 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5709 ComplexValue CV;
5710 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5711 return false;
5712 Result = CV.FloatImag;
5713 return true;
5714 }
5715
Richard Smith8327fad2011-10-24 18:44:57 +00005716 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005717 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5718 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005719 return true;
5720}
5721
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005722bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005723 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005724 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005725 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005726 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005727 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005728 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5729 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005730 Result.changeSign();
5731 return true;
5732 }
5733}
Chris Lattner019f4e82008-10-06 05:28:25 +00005734
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005735bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005736 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5737 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005738
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005739 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005740 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5741 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005742 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005743 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005744 return false;
5745
5746 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005747 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005748 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005749 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005750 break;
John McCall2de56d12010-08-25 11:45:40 +00005751 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005752 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005753 break;
John McCall2de56d12010-08-25 11:45:40 +00005754 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005755 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005756 break;
John McCall2de56d12010-08-25 11:45:40 +00005757 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005758 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005759 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005760 }
Richard Smith7b48a292012-02-01 05:53:12 +00005761
5762 if (Result.isInfinity() || Result.isNaN())
5763 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5764 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005765}
5766
5767bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5768 Result = E->getValue();
5769 return true;
5770}
5771
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005772bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5773 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005774
Eli Friedman2a523ee2011-03-25 00:54:52 +00005775 switch (E->getCastKind()) {
5776 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005777 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005778
5779 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005780 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005781 return EvaluateInteger(SubExpr, IntResult, Info) &&
5782 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5783 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005784 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005785
5786 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005787 if (!Visit(SubExpr))
5788 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005789 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5790 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005791 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005792
Eli Friedman2a523ee2011-03-25 00:54:52 +00005793 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005794 ComplexValue V;
5795 if (!EvaluateComplex(SubExpr, V, Info))
5796 return false;
5797 Result = V.getComplexFloatReal();
5798 return true;
5799 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005800 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005801}
5802
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005803//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005804// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005805//===----------------------------------------------------------------------===//
5806
5807namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005808class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005809 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005810 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005811
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005812public:
John McCallf4cf1a12010-05-07 17:22:02 +00005813 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005814 : ExprEvaluatorBaseTy(info), Result(Result) {}
5815
Richard Smith1aa0be82012-03-03 22:46:17 +00005816 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005817 Result.setFrom(V);
5818 return true;
5819 }
Mike Stump1eb44332009-09-09 15:08:12 +00005820
Eli Friedman7ead5c72012-01-10 04:58:17 +00005821 bool ZeroInitialization(const Expr *E);
5822
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005823 //===--------------------------------------------------------------------===//
5824 // Visitor Methods
5825 //===--------------------------------------------------------------------===//
5826
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005827 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005828 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005829 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005830 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005831 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005832};
5833} // end anonymous namespace
5834
John McCallf4cf1a12010-05-07 17:22:02 +00005835static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5836 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005837 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005838 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005839}
5840
Eli Friedman7ead5c72012-01-10 04:58:17 +00005841bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005842 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005843 if (ElemTy->isRealFloatingType()) {
5844 Result.makeComplexFloat();
5845 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5846 Result.FloatReal = Zero;
5847 Result.FloatImag = Zero;
5848 } else {
5849 Result.makeComplexInt();
5850 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5851 Result.IntReal = Zero;
5852 Result.IntImag = Zero;
5853 }
5854 return true;
5855}
5856
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005857bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5858 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005859
5860 if (SubExpr->getType()->isRealFloatingType()) {
5861 Result.makeComplexFloat();
5862 APFloat &Imag = Result.FloatImag;
5863 if (!EvaluateFloat(SubExpr, Imag, Info))
5864 return false;
5865
5866 Result.FloatReal = APFloat(Imag.getSemantics());
5867 return true;
5868 } else {
5869 assert(SubExpr->getType()->isIntegerType() &&
5870 "Unexpected imaginary literal.");
5871
5872 Result.makeComplexInt();
5873 APSInt &Imag = Result.IntImag;
5874 if (!EvaluateInteger(SubExpr, Imag, Info))
5875 return false;
5876
5877 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5878 return true;
5879 }
5880}
5881
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005882bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005883
John McCall8786da72010-12-14 17:51:41 +00005884 switch (E->getCastKind()) {
5885 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005886 case CK_BaseToDerived:
5887 case CK_DerivedToBase:
5888 case CK_UncheckedDerivedToBase:
5889 case CK_Dynamic:
5890 case CK_ToUnion:
5891 case CK_ArrayToPointerDecay:
5892 case CK_FunctionToPointerDecay:
5893 case CK_NullToPointer:
5894 case CK_NullToMemberPointer:
5895 case CK_BaseToDerivedMemberPointer:
5896 case CK_DerivedToBaseMemberPointer:
5897 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005898 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005899 case CK_ConstructorConversion:
5900 case CK_IntegralToPointer:
5901 case CK_PointerToIntegral:
5902 case CK_PointerToBoolean:
5903 case CK_ToVoid:
5904 case CK_VectorSplat:
5905 case CK_IntegralCast:
5906 case CK_IntegralToBoolean:
5907 case CK_IntegralToFloating:
5908 case CK_FloatingToIntegral:
5909 case CK_FloatingToBoolean:
5910 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005911 case CK_CPointerToObjCPointerCast:
5912 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005913 case CK_AnyPointerToBlockPointerCast:
5914 case CK_ObjCObjectLValueCast:
5915 case CK_FloatingComplexToReal:
5916 case CK_FloatingComplexToBoolean:
5917 case CK_IntegralComplexToReal:
5918 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005919 case CK_ARCProduceObject:
5920 case CK_ARCConsumeObject:
5921 case CK_ARCReclaimReturnedObject:
5922 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005923 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005924 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005925
John McCall8786da72010-12-14 17:51:41 +00005926 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005927 case CK_AtomicToNonAtomic:
5928 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005929 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005930 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005931
5932 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005933 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005934 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005935 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005936
5937 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005938 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005939 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005940 return false;
5941
John McCall8786da72010-12-14 17:51:41 +00005942 Result.makeComplexFloat();
5943 Result.FloatImag = APFloat(Real.getSemantics());
5944 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005945 }
5946
John McCall8786da72010-12-14 17:51:41 +00005947 case CK_FloatingComplexCast: {
5948 if (!Visit(E->getSubExpr()))
5949 return false;
5950
5951 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5952 QualType From
5953 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5954
Richard Smithc1c5f272011-12-13 06:39:58 +00005955 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5956 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005957 }
5958
5959 case CK_FloatingComplexToIntegralComplex: {
5960 if (!Visit(E->getSubExpr()))
5961 return false;
5962
5963 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5964 QualType From
5965 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5966 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005967 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5968 To, Result.IntReal) &&
5969 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5970 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005971 }
5972
5973 case CK_IntegralRealToComplex: {
5974 APSInt &Real = Result.IntReal;
5975 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5976 return false;
5977
5978 Result.makeComplexInt();
5979 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5980 return true;
5981 }
5982
5983 case CK_IntegralComplexCast: {
5984 if (!Visit(E->getSubExpr()))
5985 return false;
5986
5987 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5988 QualType From
5989 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5990
Richard Smithf72fccf2012-01-30 22:27:01 +00005991 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5992 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005993 return true;
5994 }
5995
5996 case CK_IntegralComplexToFloatingComplex: {
5997 if (!Visit(E->getSubExpr()))
5998 return false;
5999
6000 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6001 QualType From
6002 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6003 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00006004 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
6005 To, Result.FloatReal) &&
6006 HandleIntToFloatCast(Info, E, From, Result.IntImag,
6007 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00006008 }
6009 }
6010
6011 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00006012}
6013
John McCallf4cf1a12010-05-07 17:22:02 +00006014bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006015 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00006016 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6017
Richard Smith745f5142012-01-27 01:14:48 +00006018 bool LHSOK = Visit(E->getLHS());
6019 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00006020 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006021
John McCallf4cf1a12010-05-07 17:22:02 +00006022 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00006023 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00006024 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006025
Daniel Dunbar3f279872009-01-29 01:32:56 +00006026 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6027 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006028 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00006029 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00006030 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006031 if (Result.isComplexFloat()) {
6032 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6033 APFloat::rmNearestTiesToEven);
6034 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6035 APFloat::rmNearestTiesToEven);
6036 } else {
6037 Result.getComplexIntReal() += RHS.getComplexIntReal();
6038 Result.getComplexIntImag() += RHS.getComplexIntImag();
6039 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00006040 break;
John McCall2de56d12010-08-25 11:45:40 +00006041 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006042 if (Result.isComplexFloat()) {
6043 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6044 APFloat::rmNearestTiesToEven);
6045 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6046 APFloat::rmNearestTiesToEven);
6047 } else {
6048 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6049 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6050 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00006051 break;
John McCall2de56d12010-08-25 11:45:40 +00006052 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00006053 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00006054 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00006055 APFloat &LHS_r = LHS.getComplexFloatReal();
6056 APFloat &LHS_i = LHS.getComplexFloatImag();
6057 APFloat &RHS_r = RHS.getComplexFloatReal();
6058 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00006059
Daniel Dunbar3f279872009-01-29 01:32:56 +00006060 APFloat Tmp = LHS_r;
6061 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6062 Result.getComplexFloatReal() = Tmp;
6063 Tmp = LHS_i;
6064 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6065 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6066
6067 Tmp = LHS_r;
6068 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6069 Result.getComplexFloatImag() = Tmp;
6070 Tmp = LHS_i;
6071 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6072 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6073 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00006074 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00006075 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006076 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6077 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00006078 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006079 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6080 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6081 }
6082 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006083 case BO_Div:
6084 if (Result.isComplexFloat()) {
6085 ComplexValue LHS = Result;
6086 APFloat &LHS_r = LHS.getComplexFloatReal();
6087 APFloat &LHS_i = LHS.getComplexFloatImag();
6088 APFloat &RHS_r = RHS.getComplexFloatReal();
6089 APFloat &RHS_i = RHS.getComplexFloatImag();
6090 APFloat &Res_r = Result.getComplexFloatReal();
6091 APFloat &Res_i = Result.getComplexFloatImag();
6092
6093 APFloat Den = RHS_r;
6094 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6095 APFloat Tmp = RHS_i;
6096 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6097 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6098
6099 Res_r = LHS_r;
6100 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6101 Tmp = LHS_i;
6102 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6103 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6104 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6105
6106 Res_i = LHS_i;
6107 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6108 Tmp = LHS_r;
6109 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6110 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6111 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6112 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00006113 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6114 return Error(E, diag::note_expr_divide_by_zero);
6115
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006116 ComplexValue LHS = Result;
6117 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6118 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6119 Result.getComplexIntReal() =
6120 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6121 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6122 Result.getComplexIntImag() =
6123 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6124 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6125 }
6126 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006127 }
6128
John McCallf4cf1a12010-05-07 17:22:02 +00006129 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006130}
6131
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006132bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6133 // Get the operand value into 'Result'.
6134 if (!Visit(E->getSubExpr()))
6135 return false;
6136
6137 switch (E->getOpcode()) {
6138 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00006139 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006140 case UO_Extension:
6141 return true;
6142 case UO_Plus:
6143 // The result is always just the subexpr.
6144 return true;
6145 case UO_Minus:
6146 if (Result.isComplexFloat()) {
6147 Result.getComplexFloatReal().changeSign();
6148 Result.getComplexFloatImag().changeSign();
6149 }
6150 else {
6151 Result.getComplexIntReal() = -Result.getComplexIntReal();
6152 Result.getComplexIntImag() = -Result.getComplexIntImag();
6153 }
6154 return true;
6155 case UO_Not:
6156 if (Result.isComplexFloat())
6157 Result.getComplexFloatImag().changeSign();
6158 else
6159 Result.getComplexIntImag() = -Result.getComplexIntImag();
6160 return true;
6161 }
6162}
6163
Eli Friedman7ead5c72012-01-10 04:58:17 +00006164bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6165 if (E->getNumInits() == 2) {
6166 if (E->getType()->isComplexType()) {
6167 Result.makeComplexFloat();
6168 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6169 return false;
6170 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6171 return false;
6172 } else {
6173 Result.makeComplexInt();
6174 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6175 return false;
6176 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6177 return false;
6178 }
6179 return true;
6180 }
6181 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6182}
6183
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00006184//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00006185// Void expression evaluation, primarily for a cast to void on the LHS of a
6186// comma operator
6187//===----------------------------------------------------------------------===//
6188
6189namespace {
6190class VoidExprEvaluator
6191 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6192public:
6193 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6194
Richard Smith1aa0be82012-03-03 22:46:17 +00006195 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00006196
6197 bool VisitCastExpr(const CastExpr *E) {
6198 switch (E->getCastKind()) {
6199 default:
6200 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6201 case CK_ToVoid:
6202 VisitIgnoredValue(E->getSubExpr());
6203 return true;
6204 }
6205 }
6206};
6207} // end anonymous namespace
6208
6209static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6210 assert(E->isRValue() && E->getType()->isVoidType());
6211 return VoidExprEvaluator(Info).Visit(E);
6212}
6213
6214//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006215// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006216//===----------------------------------------------------------------------===//
6217
Richard Smith1aa0be82012-03-03 22:46:17 +00006218static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006219 // In C, function designators are not lvalues, but we evaluate them as if they
6220 // are.
6221 if (E->isGLValue() || E->getType()->isFunctionType()) {
6222 LValue LV;
6223 if (!EvaluateLValue(E, LV, Info))
6224 return false;
6225 LV.moveInto(Result);
6226 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006227 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006228 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006229 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006230 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006231 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006232 } else if (E->getType()->hasPointerRepresentation()) {
6233 LValue LV;
6234 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006235 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006236 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006237 } else if (E->getType()->isRealFloatingType()) {
6238 llvm::APFloat F(0.0);
6239 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006240 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006241 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006242 } else if (E->getType()->isAnyComplexType()) {
6243 ComplexValue C;
6244 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006245 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006246 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006247 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006248 MemberPtr P;
6249 if (!EvaluateMemberPointer(E, P, Info))
6250 return false;
6251 P.moveInto(Result);
6252 return true;
Richard Smith51201882011-12-30 21:15:51 +00006253 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006254 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006255 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006256 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006257 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006258 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006259 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006260 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006261 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006262 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6263 return false;
6264 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006265 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00006266 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006267 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00006268 << E->getType();
6269 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00006270 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00006271 if (!EvaluateVoid(E, Info))
6272 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006273 } else if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006274 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006275 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006276 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006277 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006278 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006279 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006280
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006281 return true;
6282}
6283
Richard Smith83587db2012-02-15 02:18:13 +00006284/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6285/// cases, the in-place evaluation is essential, since later initializers for
6286/// an object can indirectly refer to subobjects which were initialized earlier.
6287static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6288 const Expr *E, CheckConstantExpressionKind CCEK,
6289 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006290 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006291 return false;
6292
6293 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006294 // Evaluate arrays and record types in-place, so that later initializers can
6295 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006296 if (E->getType()->isArrayType())
6297 return EvaluateArray(E, This, Result, Info);
6298 else if (E->getType()->isRecordType())
6299 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006300 }
6301
6302 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006303 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006304}
6305
Richard Smithf48fdb02011-12-09 22:58:01 +00006306/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6307/// lvalue-to-rvalue cast if it is an lvalue.
6308static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006309 if (!CheckLiteralType(Info, E))
6310 return false;
6311
Richard Smith1aa0be82012-03-03 22:46:17 +00006312 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006313 return false;
6314
6315 if (E->isGLValue()) {
6316 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006317 LV.setFrom(Info.Ctx, Result);
6318 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006319 return false;
6320 }
6321
Richard Smith1aa0be82012-03-03 22:46:17 +00006322 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006323 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006324}
Richard Smithc49bd112011-10-28 17:51:58 +00006325
Richard Smith51f47082011-10-29 00:50:52 +00006326/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006327/// any crazy technique (that has nothing to do with language standards) that
6328/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006329/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6330/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006331bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006332 // Fast-path evaluations of integer literals, since we sometimes see files
6333 // containing vast quantities of these.
6334 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6335 Result.Val = APValue(APSInt(L->getValue(),
6336 L->getType()->isUnsignedIntegerType()));
6337 return true;
6338 }
6339
Richard Smith2d6a5672012-01-14 04:30:29 +00006340 // FIXME: Evaluating values of large array and record types can cause
6341 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006342 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006343 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006344 return false;
6345
Richard Smithf48fdb02011-12-09 22:58:01 +00006346 EvalInfo Info(Ctx, Result);
6347 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006348}
6349
Jay Foad4ba2a172011-01-12 09:06:06 +00006350bool Expr::EvaluateAsBooleanCondition(bool &Result,
6351 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006352 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006353 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006354 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006355}
6356
Richard Smith80d4b552011-12-28 19:48:30 +00006357bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6358 SideEffectsKind AllowSideEffects) const {
6359 if (!getType()->isIntegralOrEnumerationType())
6360 return false;
6361
Richard Smithc49bd112011-10-28 17:51:58 +00006362 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006363 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6364 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006365 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006366
Richard Smithc49bd112011-10-28 17:51:58 +00006367 Result = ExprResult.Val.getInt();
6368 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006369}
6370
Jay Foad4ba2a172011-01-12 09:06:06 +00006371bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006372 EvalInfo Info(Ctx, Result);
6373
John McCallefdb83e2010-05-07 21:00:08 +00006374 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006375 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6376 !CheckLValueConstantExpression(Info, getExprLoc(),
6377 Ctx.getLValueReferenceType(getType()), LV))
6378 return false;
6379
Richard Smith1aa0be82012-03-03 22:46:17 +00006380 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006381 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006382}
6383
Richard Smith099e7f62011-12-19 06:19:21 +00006384bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6385 const VarDecl *VD,
6386 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006387 // FIXME: Evaluating initializers for large array and record types can cause
6388 // performance problems. Only do so in C++11 for now.
6389 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006390 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith2d6a5672012-01-14 04:30:29 +00006391 return false;
6392
Richard Smith099e7f62011-12-19 06:19:21 +00006393 Expr::EvalStatus EStatus;
6394 EStatus.Diag = &Notes;
6395
6396 EvalInfo InitInfo(Ctx, EStatus);
6397 InitInfo.setEvaluatingDecl(VD, Value);
6398
6399 LValue LVal;
6400 LVal.set(VD);
6401
Richard Smith51201882011-12-30 21:15:51 +00006402 // C++11 [basic.start.init]p2:
6403 // Variables with static storage duration or thread storage duration shall be
6404 // zero-initialized before any other initialization takes place.
6405 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006406 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006407 !VD->getType()->isReferenceType()) {
6408 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006409 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6410 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006411 return false;
6412 }
6413
Richard Smith83587db2012-02-15 02:18:13 +00006414 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6415 /*AllowNonLiteralTypes=*/true) ||
6416 EStatus.HasSideEffects)
6417 return false;
6418
6419 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6420 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006421}
6422
Richard Smith51f47082011-10-29 00:50:52 +00006423/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6424/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006425bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006426 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006427 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006428}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006429
Jay Foad4ba2a172011-01-12 09:06:06 +00006430bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006431 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006432}
6433
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006434APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006435 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006436 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006437 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006438 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006439 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006440
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006441 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006442}
John McCalld905f5a2010-05-07 05:32:02 +00006443
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006444 bool Expr::EvalResult::isGlobalLValue() const {
6445 assert(Val.isLValue());
6446 return IsGlobalLValue(Val.getLValueBase());
6447 }
6448
6449
John McCalld905f5a2010-05-07 05:32:02 +00006450/// isIntegerConstantExpr - this recursive routine will test if an expression is
6451/// an integer constant expression.
6452
6453/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6454/// comma, etc
6455///
6456/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6457/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6458/// cast+dereference.
6459
6460// CheckICE - This function does the fundamental ICE checking: the returned
6461// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6462// Note that to reduce code duplication, this helper does no evaluation
6463// itself; the caller checks whether the expression is evaluatable, and
6464// in the rare cases where CheckICE actually cares about the evaluated
6465// value, it calls into Evalute.
6466//
6467// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006468// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006469// 1: This expression is not an ICE, but if it isn't evaluated, it's
6470// a legal subexpression for an ICE. This return value is used to handle
6471// the comma operator in C99 mode.
6472// 2: This expression is not an ICE, and is not a legal subexpression for one.
6473
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006474namespace {
6475
John McCalld905f5a2010-05-07 05:32:02 +00006476struct ICEDiag {
6477 unsigned Val;
6478 SourceLocation Loc;
6479
6480 public:
6481 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6482 ICEDiag() : Val(0) {}
6483};
6484
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006485}
6486
6487static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006488
6489static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6490 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006491 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006492 !EVResult.Val.isInt()) {
6493 return ICEDiag(2, E->getLocStart());
6494 }
6495 return NoDiag();
6496}
6497
6498static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6499 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006500 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006501 return ICEDiag(2, E->getLocStart());
6502 }
6503
6504 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006505#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006506#define STMT(Node, Base) case Expr::Node##Class:
6507#define EXPR(Node, Base)
6508#include "clang/AST/StmtNodes.inc"
6509 case Expr::PredefinedExprClass:
6510 case Expr::FloatingLiteralClass:
6511 case Expr::ImaginaryLiteralClass:
6512 case Expr::StringLiteralClass:
6513 case Expr::ArraySubscriptExprClass:
6514 case Expr::MemberExprClass:
6515 case Expr::CompoundAssignOperatorClass:
6516 case Expr::CompoundLiteralExprClass:
6517 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006518 case Expr::DesignatedInitExprClass:
6519 case Expr::ImplicitValueInitExprClass:
6520 case Expr::ParenListExprClass:
6521 case Expr::VAArgExprClass:
6522 case Expr::AddrLabelExprClass:
6523 case Expr::StmtExprClass:
6524 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006525 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006526 case Expr::CXXDynamicCastExprClass:
6527 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006528 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006529 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006530 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006531 case Expr::CXXThisExprClass:
6532 case Expr::CXXThrowExprClass:
6533 case Expr::CXXNewExprClass:
6534 case Expr::CXXDeleteExprClass:
6535 case Expr::CXXPseudoDestructorExprClass:
6536 case Expr::UnresolvedLookupExprClass:
6537 case Expr::DependentScopeDeclRefExprClass:
6538 case Expr::CXXConstructExprClass:
6539 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006540 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006541 case Expr::CXXTemporaryObjectExprClass:
6542 case Expr::CXXUnresolvedConstructExprClass:
6543 case Expr::CXXDependentScopeMemberExprClass:
6544 case Expr::UnresolvedMemberExprClass:
6545 case Expr::ObjCStringLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +00006546 case Expr::ObjCBoxedExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006547 case Expr::ObjCArrayLiteralClass:
6548 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006549 case Expr::ObjCEncodeExprClass:
6550 case Expr::ObjCMessageExprClass:
6551 case Expr::ObjCSelectorExprClass:
6552 case Expr::ObjCProtocolExprClass:
6553 case Expr::ObjCIvarRefExprClass:
6554 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006555 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006556 case Expr::ObjCIsaExprClass:
6557 case Expr::ShuffleVectorExprClass:
6558 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006559 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006560 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006561 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006562 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006563 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006564 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006565 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006566 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006567 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006568 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006569 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006570 return ICEDiag(2, E->getLocStart());
6571
Douglas Gregoree8aff02011-01-04 17:33:58 +00006572 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006573 case Expr::GNUNullExprClass:
6574 // GCC considers the GNU __null value to be an integral constant expression.
6575 return NoDiag();
6576
John McCall91a57552011-07-15 05:09:51 +00006577 case Expr::SubstNonTypeTemplateParmExprClass:
6578 return
6579 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6580
John McCalld905f5a2010-05-07 05:32:02 +00006581 case Expr::ParenExprClass:
6582 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006583 case Expr::GenericSelectionExprClass:
6584 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006585 case Expr::IntegerLiteralClass:
6586 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006587 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006588 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006589 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006590 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006591 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006592 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006593 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006594 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006595 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006596 return NoDiag();
6597 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006598 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006599 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6600 // constant expressions, but they can never be ICEs because an ICE cannot
6601 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006602 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006603 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006604 return CheckEvalInICE(E, Ctx);
6605 return ICEDiag(2, E->getLocStart());
6606 }
Richard Smith359c89d2012-02-24 22:12:32 +00006607 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006608 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6609 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006610 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006611 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006612 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006613 // Parameter variables are never constants. Without this check,
6614 // getAnyInitializer() can find a default argument, which leads
6615 // to chaos.
6616 if (isa<ParmVarDecl>(D))
6617 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6618
6619 // C++ 7.1.5.1p2
6620 // A variable of non-volatile const-qualified integral or enumeration
6621 // type initialized by an ICE can be used in ICEs.
6622 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006623 if (!Dcl->getType()->isIntegralOrEnumerationType())
6624 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6625
Richard Smith099e7f62011-12-19 06:19:21 +00006626 const VarDecl *VD;
6627 // Look for a declaration of this variable that has an initializer, and
6628 // check whether it is an ICE.
6629 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6630 return NoDiag();
6631 else
6632 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006633 }
6634 }
6635 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006636 }
John McCalld905f5a2010-05-07 05:32:02 +00006637 case Expr::UnaryOperatorClass: {
6638 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6639 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006640 case UO_PostInc:
6641 case UO_PostDec:
6642 case UO_PreInc:
6643 case UO_PreDec:
6644 case UO_AddrOf:
6645 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006646 // C99 6.6/3 allows increment and decrement within unevaluated
6647 // subexpressions of constant expressions, but they can never be ICEs
6648 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006649 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006650 case UO_Extension:
6651 case UO_LNot:
6652 case UO_Plus:
6653 case UO_Minus:
6654 case UO_Not:
6655 case UO_Real:
6656 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006657 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006658 }
6659
6660 // OffsetOf falls through here.
6661 }
6662 case Expr::OffsetOfExprClass: {
6663 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006664 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006665 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006666 // compliance: we should warn earlier for offsetof expressions with
6667 // array subscripts that aren't ICEs, and if the array subscripts
6668 // are ICEs, the value of the offsetof must be an integer constant.
6669 return CheckEvalInICE(E, Ctx);
6670 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006671 case Expr::UnaryExprOrTypeTraitExprClass: {
6672 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6673 if ((Exp->getKind() == UETT_SizeOf) &&
6674 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006675 return ICEDiag(2, E->getLocStart());
6676 return NoDiag();
6677 }
6678 case Expr::BinaryOperatorClass: {
6679 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6680 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006681 case BO_PtrMemD:
6682 case BO_PtrMemI:
6683 case BO_Assign:
6684 case BO_MulAssign:
6685 case BO_DivAssign:
6686 case BO_RemAssign:
6687 case BO_AddAssign:
6688 case BO_SubAssign:
6689 case BO_ShlAssign:
6690 case BO_ShrAssign:
6691 case BO_AndAssign:
6692 case BO_XorAssign:
6693 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006694 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6695 // constant expressions, but they can never be ICEs because an ICE cannot
6696 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006697 return ICEDiag(2, E->getLocStart());
6698
John McCall2de56d12010-08-25 11:45:40 +00006699 case BO_Mul:
6700 case BO_Div:
6701 case BO_Rem:
6702 case BO_Add:
6703 case BO_Sub:
6704 case BO_Shl:
6705 case BO_Shr:
6706 case BO_LT:
6707 case BO_GT:
6708 case BO_LE:
6709 case BO_GE:
6710 case BO_EQ:
6711 case BO_NE:
6712 case BO_And:
6713 case BO_Xor:
6714 case BO_Or:
6715 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006716 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6717 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006718 if (Exp->getOpcode() == BO_Div ||
6719 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006720 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006721 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006722 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006723 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006724 if (REval == 0)
6725 return ICEDiag(1, E->getLocStart());
6726 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006727 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006728 if (LEval.isMinSignedValue())
6729 return ICEDiag(1, E->getLocStart());
6730 }
6731 }
6732 }
John McCall2de56d12010-08-25 11:45:40 +00006733 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006734 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006735 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6736 // if it isn't evaluated.
6737 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6738 return ICEDiag(1, E->getLocStart());
6739 } else {
6740 // In both C89 and C++, commas in ICEs are illegal.
6741 return ICEDiag(2, E->getLocStart());
6742 }
6743 }
6744 if (LHSResult.Val >= RHSResult.Val)
6745 return LHSResult;
6746 return RHSResult;
6747 }
John McCall2de56d12010-08-25 11:45:40 +00006748 case BO_LAnd:
6749 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006750 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6751 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6752 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6753 // Rare case where the RHS has a comma "side-effect"; we need
6754 // to actually check the condition to see whether the side
6755 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006756 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006757 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006758 return RHSResult;
6759 return NoDiag();
6760 }
6761
6762 if (LHSResult.Val >= RHSResult.Val)
6763 return LHSResult;
6764 return RHSResult;
6765 }
6766 }
6767 }
6768 case Expr::ImplicitCastExprClass:
6769 case Expr::CStyleCastExprClass:
6770 case Expr::CXXFunctionalCastExprClass:
6771 case Expr::CXXStaticCastExprClass:
6772 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006773 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006774 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006775 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006776 if (isa<ExplicitCastExpr>(E)) {
6777 if (const FloatingLiteral *FL
6778 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6779 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6780 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6781 APSInt IgnoredVal(DestWidth, !DestSigned);
6782 bool Ignored;
6783 // If the value does not fit in the destination type, the behavior is
6784 // undefined, so we are not required to treat it as a constant
6785 // expression.
6786 if (FL->getValue().convertToInteger(IgnoredVal,
6787 llvm::APFloat::rmTowardZero,
6788 &Ignored) & APFloat::opInvalidOp)
6789 return ICEDiag(2, E->getLocStart());
6790 return NoDiag();
6791 }
6792 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006793 switch (cast<CastExpr>(E)->getCastKind()) {
6794 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006795 case CK_AtomicToNonAtomic:
6796 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006797 case CK_NoOp:
6798 case CK_IntegralToBoolean:
6799 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006800 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006801 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006802 return ICEDiag(2, E->getLocStart());
6803 }
John McCalld905f5a2010-05-07 05:32:02 +00006804 }
John McCall56ca35d2011-02-17 10:25:35 +00006805 case Expr::BinaryConditionalOperatorClass: {
6806 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6807 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6808 if (CommonResult.Val == 2) return CommonResult;
6809 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6810 if (FalseResult.Val == 2) return FalseResult;
6811 if (CommonResult.Val == 1) return CommonResult;
6812 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006813 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006814 return FalseResult;
6815 }
John McCalld905f5a2010-05-07 05:32:02 +00006816 case Expr::ConditionalOperatorClass: {
6817 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6818 // If the condition (ignoring parens) is a __builtin_constant_p call,
6819 // then only the true side is actually considered in an integer constant
6820 // expression, and it is fully evaluated. This is an important GNU
6821 // extension. See GCC PR38377 for discussion.
6822 if (const CallExpr *CallCE
6823 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006824 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6825 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006826 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006827 if (CondResult.Val == 2)
6828 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006829
Richard Smithf48fdb02011-12-09 22:58:01 +00006830 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6831 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006832
John McCalld905f5a2010-05-07 05:32:02 +00006833 if (TrueResult.Val == 2)
6834 return TrueResult;
6835 if (FalseResult.Val == 2)
6836 return FalseResult;
6837 if (CondResult.Val == 1)
6838 return CondResult;
6839 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6840 return NoDiag();
6841 // Rare case where the diagnostics depend on which side is evaluated
6842 // Note that if we get here, CondResult is 0, and at least one of
6843 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006844 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006845 return FalseResult;
6846 }
6847 return TrueResult;
6848 }
6849 case Expr::CXXDefaultArgExprClass:
6850 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6851 case Expr::ChooseExprClass: {
6852 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6853 }
6854 }
6855
David Blaikie30263482012-01-20 21:50:17 +00006856 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006857}
6858
Richard Smithf48fdb02011-12-09 22:58:01 +00006859/// Evaluate an expression as a C++11 integral constant expression.
6860static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6861 const Expr *E,
6862 llvm::APSInt *Value,
6863 SourceLocation *Loc) {
6864 if (!E->getType()->isIntegralOrEnumerationType()) {
6865 if (Loc) *Loc = E->getExprLoc();
6866 return false;
6867 }
6868
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006869 APValue Result;
6870 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006871 return false;
6872
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006873 assert(Result.isInt() && "pointer cast to int is not an ICE");
6874 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006875 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006876}
6877
Richard Smithdd1f29b2011-12-12 09:28:41 +00006878bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006879 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006880 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6881
John McCalld905f5a2010-05-07 05:32:02 +00006882 ICEDiag d = CheckICE(this, Ctx);
6883 if (d.Val != 0) {
6884 if (Loc) *Loc = d.Loc;
6885 return false;
6886 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006887 return true;
6888}
6889
6890bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6891 SourceLocation *Loc, bool isEvaluated) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006892 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006893 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6894
6895 if (!isIntegerConstantExpr(Ctx, Loc))
6896 return false;
6897 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006898 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006899 return true;
6900}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006901
Richard Smith70488e22012-02-14 21:38:30 +00006902bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6903 return CheckICE(this, Ctx).Val == 0;
6904}
6905
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006906bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6907 SourceLocation *Loc) const {
6908 // We support this checking in C++98 mode in order to diagnose compatibility
6909 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006910 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006911
Richard Smith70488e22012-02-14 21:38:30 +00006912 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006913 Expr::EvalStatus Status;
6914 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6915 Status.Diag = &Diags;
6916 EvalInfo Info(Ctx, Status);
6917
6918 APValue Scratch;
6919 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6920
6921 if (!Diags.empty()) {
6922 IsConstExpr = false;
6923 if (Loc) *Loc = Diags[0].first;
6924 } else if (!IsConstExpr) {
6925 // FIXME: This shouldn't happen.
6926 if (Loc) *Loc = getExprLoc();
6927 }
6928
6929 return IsConstExpr;
6930}
Richard Smith745f5142012-01-27 01:14:48 +00006931
6932bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6933 llvm::SmallVectorImpl<
6934 PartialDiagnosticAt> &Diags) {
6935 // FIXME: It would be useful to check constexpr function templates, but at the
6936 // moment the constant expression evaluator cannot cope with the non-rigorous
6937 // ASTs which we build for dependent expressions.
6938 if (FD->isDependentContext())
6939 return true;
6940
6941 Expr::EvalStatus Status;
6942 Status.Diag = &Diags;
6943
6944 EvalInfo Info(FD->getASTContext(), Status);
6945 Info.CheckingPotentialConstantExpression = true;
6946
6947 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6948 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6949
6950 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6951 // is a temporary being used as the 'this' pointer.
6952 LValue This;
6953 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006954 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006955
Richard Smith745f5142012-01-27 01:14:48 +00006956 ArrayRef<const Expr*> Args;
6957
6958 SourceLocation Loc = FD->getLocation();
6959
Richard Smith1aa0be82012-03-03 22:46:17 +00006960 APValue Scratch;
6961 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006962 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006963 else
Richard Smith745f5142012-01-27 01:14:48 +00006964 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6965 Args, FD->getBody(), Info, Scratch);
6966
6967 return Diags.empty();
6968}