blob: cbcd5e8f74b9100a969dfd6cd3e2505a4575cc40 [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
Eli Friedmanf6172ae2012-06-25 21:21:08 +0000290 // Note that we intentionally use std::map here so that references to
291 // values are stable.
292 typedef std::map<const Expr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000293 typedef MapTy::const_iterator temp_iterator;
294 /// Temporaries - Temporary lvalues materialized within this stack frame.
295 MapTy Temporaries;
296
Richard Smith08d6e032011-12-16 19:06:07 +0000297 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
298 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000299 const APValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000300 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000301 };
302
Richard Smithdd1f29b2011-12-12 09:28:41 +0000303 /// A partial diagnostic which we might know in advance that we are not going
304 /// to emit.
305 class OptionalDiagnostic {
306 PartialDiagnostic *Diag;
307
308 public:
309 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
310
311 template<typename T>
312 OptionalDiagnostic &operator<<(const T &v) {
313 if (Diag)
314 *Diag << v;
315 return *this;
316 }
Richard Smith789f9b62012-01-31 04:08:20 +0000317
318 OptionalDiagnostic &operator<<(const APSInt &I) {
319 if (Diag) {
320 llvm::SmallVector<char, 32> Buffer;
321 I.toString(Buffer);
322 *Diag << StringRef(Buffer.data(), Buffer.size());
323 }
324 return *this;
325 }
326
327 OptionalDiagnostic &operator<<(const APFloat &F) {
328 if (Diag) {
329 llvm::SmallVector<char, 32> Buffer;
330 F.toString(Buffer);
331 *Diag << StringRef(Buffer.data(), Buffer.size());
332 }
333 return *this;
334 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000335 };
336
Richard Smith83587db2012-02-15 02:18:13 +0000337 /// EvalInfo - This is a private struct used by the evaluator to capture
338 /// information about a subexpression as it is folded. It retains information
339 /// about the AST context, but also maintains information about the folded
340 /// expression.
341 ///
342 /// If an expression could be evaluated, it is still possible it is not a C
343 /// "integer constant expression" or constant expression. If not, this struct
344 /// captures information about how and why not.
345 ///
346 /// One bit of information passed *into* the request for constant folding
347 /// indicates whether the subexpression is "evaluated" or not according to C
348 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
349 /// evaluate the expression regardless of what the RHS is, but C only allows
350 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000351 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000352 ASTContext &Ctx;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000353
Richard Smithbd552ef2011-10-31 05:52:43 +0000354 /// EvalStatus - Contains information about the evaluation.
355 Expr::EvalStatus &EvalStatus;
356
357 /// CurrentCall - The top of the constexpr call stack.
358 CallStackFrame *CurrentCall;
359
Richard Smithbd552ef2011-10-31 05:52:43 +0000360 /// CallStackDepth - The number of calls in the call stack right now.
361 unsigned CallStackDepth;
362
Richard Smith83587db2012-02-15 02:18:13 +0000363 /// NextCallIndex - The next call index to assign.
364 unsigned NextCallIndex;
365
Richard Smithbd552ef2011-10-31 05:52:43 +0000366 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000367 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000368 CallStackFrame BottomFrame;
369
Richard Smith180f4792011-11-10 06:34:14 +0000370 /// EvaluatingDecl - This is the declaration whose initializer is being
371 /// evaluated, if any.
372 const VarDecl *EvaluatingDecl;
373
374 /// EvaluatingDeclValue - This is the value being constructed for the
375 /// declaration whose initializer is being evaluated, if any.
376 APValue *EvaluatingDeclValue;
377
Richard Smithc1c5f272011-12-13 06:39:58 +0000378 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
379 /// notes attached to it will also be stored, otherwise they will not be.
380 bool HasActiveDiagnostic;
381
Richard Smith745f5142012-01-27 01:14:48 +0000382 /// CheckingPotentialConstantExpression - Are we checking whether the
383 /// expression is a potential constant expression? If so, some diagnostics
384 /// are suppressed.
385 bool CheckingPotentialConstantExpression;
386
Richard Smithbd552ef2011-10-31 05:52:43 +0000387 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000388 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000389 CallStackDepth(0), NextCallIndex(1),
390 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000391 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Argyrios Kyrtzidis649dfbc2012-03-15 18:07:13 +0000392 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000393
Richard Smith180f4792011-11-10 06:34:14 +0000394 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
395 EvaluatingDecl = VD;
396 EvaluatingDeclValue = &Value;
397 }
398
David Blaikie4e4d0842012-03-11 07:00:24 +0000399 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000400
Richard Smithc1c5f272011-12-13 06:39:58 +0000401 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000402 // Don't perform any constexpr calls (other than the call we're checking)
403 // when checking a potential constant expression.
404 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
405 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000406 if (NextCallIndex == 0) {
407 // NextCallIndex has wrapped around.
408 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
409 return false;
410 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000411 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
412 return true;
413 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
414 << getLangOpts().ConstexprCallDepth;
415 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000416 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000417
Richard Smith83587db2012-02-15 02:18:13 +0000418 CallStackFrame *getCallFrame(unsigned CallIndex) {
419 assert(CallIndex && "no call index in getCallFrame");
420 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
421 // be null in this loop.
422 CallStackFrame *Frame = CurrentCall;
423 while (Frame->Index > CallIndex)
424 Frame = Frame->Caller;
425 return (Frame->Index == CallIndex) ? Frame : 0;
426 }
427
Richard Smithc1c5f272011-12-13 06:39:58 +0000428 private:
429 /// Add a diagnostic to the diagnostics list.
430 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
431 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
432 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
433 return EvalStatus.Diag->back().second;
434 }
435
Richard Smith08d6e032011-12-16 19:06:07 +0000436 /// Add notes containing a call stack to the current point of evaluation.
437 void addCallStack(unsigned Limit);
438
Richard Smithc1c5f272011-12-13 06:39:58 +0000439 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000440 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000441 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
442 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000443 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000444 // If we have a prior diagnostic, it will be noting that the expression
445 // isn't a constant expression. This diagnostic is more important.
446 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000447 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000448 unsigned CallStackNotes = CallStackDepth - 1;
449 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
450 if (Limit)
451 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000452 if (CheckingPotentialConstantExpression)
453 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000454
Richard Smithc1c5f272011-12-13 06:39:58 +0000455 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000456 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000457 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
458 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000459 if (!CheckingPotentialConstantExpression)
460 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000461 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000462 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000463 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000464 return OptionalDiagnostic();
465 }
466
Richard Smith5cfc7d82012-03-15 04:53:45 +0000467 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
468 = diag::note_invalid_subexpr_in_const_expr,
469 unsigned ExtraNotes = 0) {
470 if (EvalStatus.Diag)
471 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
472 HasActiveDiagnostic = false;
473 return OptionalDiagnostic();
474 }
475
Richard Smithdd1f29b2011-12-12 09:28:41 +0000476 /// Diagnose that the evaluation does not produce a C++11 core constant
477 /// expression.
Richard Smith5cfc7d82012-03-15 04:53:45 +0000478 template<typename LocArg>
479 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000480 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000481 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000482 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000483 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
484 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000485 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000486 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000487 return Diag(Loc, DiagId, ExtraNotes);
488 }
489
490 /// Add a note to a prior diagnostic.
491 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
492 if (!HasActiveDiagnostic)
493 return OptionalDiagnostic();
494 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000495 }
Richard Smith099e7f62011-12-19 06:19:21 +0000496
497 /// Add a stack of notes to a prior diagnostic.
498 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
499 if (HasActiveDiagnostic) {
500 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
501 Diags.begin(), Diags.end());
502 }
503 }
Richard Smith745f5142012-01-27 01:14:48 +0000504
505 /// Should we continue evaluation as much as possible after encountering a
506 /// construct which can't be folded?
507 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000508 return CheckingPotentialConstantExpression &&
509 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000510 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000511 };
Richard Smithf15fda02012-02-02 01:16:57 +0000512
513 /// Object used to treat all foldable expressions as constant expressions.
514 struct FoldConstant {
515 bool Enabled;
516
517 explicit FoldConstant(EvalInfo &Info)
518 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
519 !Info.EvalStatus.HasSideEffects) {
520 }
521 // Treat the value we've computed since this object was created as constant.
522 void Fold(EvalInfo &Info) {
523 if (Enabled && !Info.EvalStatus.Diag->empty() &&
524 !Info.EvalStatus.HasSideEffects)
525 Info.EvalStatus.Diag->clear();
526 }
527 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000528
529 /// RAII object used to suppress diagnostics and side-effects from a
530 /// speculative evaluation.
531 class SpeculativeEvaluationRAII {
532 EvalInfo &Info;
533 Expr::EvalStatus Old;
534
535 public:
536 SpeculativeEvaluationRAII(EvalInfo &Info,
537 llvm::SmallVectorImpl<PartialDiagnosticAt>
538 *NewDiag = 0)
539 : Info(Info), Old(Info.EvalStatus) {
540 Info.EvalStatus.Diag = NewDiag;
541 }
542 ~SpeculativeEvaluationRAII() {
543 Info.EvalStatus = Old;
544 }
545 };
Richard Smith08d6e032011-12-16 19:06:07 +0000546}
Richard Smithbd552ef2011-10-31 05:52:43 +0000547
Richard Smithb4e85ed2012-01-06 16:39:00 +0000548bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
549 CheckSubobjectKind CSK) {
550 if (Invalid)
551 return false;
552 if (isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000553 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000554 << CSK;
555 setInvalid();
556 return false;
557 }
558 return true;
559}
560
561void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
562 const Expr *E, uint64_t N) {
563 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000564 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000565 << static_cast<int>(N) << /*array*/ 0
566 << static_cast<unsigned>(MostDerivedArraySize);
567 else
Richard Smith5cfc7d82012-03-15 04:53:45 +0000568 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000569 << static_cast<int>(N) << /*non-array*/ 1;
570 setInvalid();
571}
572
Richard Smith08d6e032011-12-16 19:06:07 +0000573CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
574 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000575 const APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000576 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000577 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000578 Info.CurrentCall = this;
579 ++Info.CallStackDepth;
580}
581
582CallStackFrame::~CallStackFrame() {
583 assert(Info.CurrentCall == this && "calls retired out of order");
584 --Info.CallStackDepth;
585 Info.CurrentCall = Caller;
586}
587
588/// Produce a string describing the given constexpr call.
589static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
590 unsigned ArgIndex = 0;
591 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000592 !isa<CXXConstructorDecl>(Frame->Callee) &&
593 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000594
595 if (!IsMemberCall)
596 Out << *Frame->Callee << '(';
597
598 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
599 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000600 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000601 Out << ", ";
602
603 const ParmVarDecl *Param = *I;
Richard Smith1aa0be82012-03-03 22:46:17 +0000604 const APValue &Arg = Frame->Arguments[ArgIndex];
605 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smith08d6e032011-12-16 19:06:07 +0000606
607 if (ArgIndex == 0 && IsMemberCall)
608 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000609 }
610
Richard Smith08d6e032011-12-16 19:06:07 +0000611 Out << ')';
612}
613
614void EvalInfo::addCallStack(unsigned Limit) {
615 // Determine which calls to skip, if any.
616 unsigned ActiveCalls = CallStackDepth - 1;
617 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
618 if (Limit && Limit < ActiveCalls) {
619 SkipStart = Limit / 2 + Limit % 2;
620 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000621 }
622
Richard Smith08d6e032011-12-16 19:06:07 +0000623 // Walk the call stack and add the diagnostics.
624 unsigned CallIdx = 0;
625 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
626 Frame = Frame->Caller, ++CallIdx) {
627 // Skip this call?
628 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
629 if (CallIdx == SkipStart) {
630 // Note that we're skipping calls.
631 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
632 << unsigned(ActiveCalls - Limit);
633 }
634 continue;
635 }
636
637 llvm::SmallVector<char, 128> Buffer;
638 llvm::raw_svector_ostream Out(Buffer);
639 describeCall(Frame, Out);
640 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
641 }
642}
643
644namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000645 struct ComplexValue {
646 private:
647 bool IsInt;
648
649 public:
650 APSInt IntReal, IntImag;
651 APFloat FloatReal, FloatImag;
652
653 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
654
655 void makeComplexFloat() { IsInt = false; }
656 bool isComplexFloat() const { return !IsInt; }
657 APFloat &getComplexFloatReal() { return FloatReal; }
658 APFloat &getComplexFloatImag() { return FloatImag; }
659
660 void makeComplexInt() { IsInt = true; }
661 bool isComplexInt() const { return IsInt; }
662 APSInt &getComplexIntReal() { return IntReal; }
663 APSInt &getComplexIntImag() { return IntImag; }
664
Richard Smith1aa0be82012-03-03 22:46:17 +0000665 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000666 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000667 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000668 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000669 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000670 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000671 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000672 assert(v.isComplexFloat() || v.isComplexInt());
673 if (v.isComplexFloat()) {
674 makeComplexFloat();
675 FloatReal = v.getComplexFloatReal();
676 FloatImag = v.getComplexFloatImag();
677 } else {
678 makeComplexInt();
679 IntReal = v.getComplexIntReal();
680 IntImag = v.getComplexIntImag();
681 }
682 }
John McCallf4cf1a12010-05-07 17:22:02 +0000683 };
John McCallefdb83e2010-05-07 21:00:08 +0000684
685 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000686 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000687 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000688 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000689 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000690
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000691 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000692 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000693 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000694 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000695 SubobjectDesignator &getLValueDesignator() { return Designator; }
696 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000697
Richard Smith1aa0be82012-03-03 22:46:17 +0000698 void moveInto(APValue &V) const {
699 if (Designator.Invalid)
700 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
701 else
702 V = APValue(Base, Offset, Designator.Entries,
703 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000704 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000705 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000706 assert(V.isLValue());
707 Base = V.getLValueBase();
708 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000709 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000710 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000711 }
712
Richard Smith83587db2012-02-15 02:18:13 +0000713 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000714 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000715 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000716 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000717 Designator = SubobjectDesignator(getType(B));
718 }
719
720 // Check that this LValue is not based on a null pointer. If it is, produce
721 // a diagnostic and mark the designator as invalid.
722 bool checkNullPointer(EvalInfo &Info, const Expr *E,
723 CheckSubobjectKind CSK) {
724 if (Designator.Invalid)
725 return false;
726 if (!Base) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000727 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000728 << CSK;
729 Designator.setInvalid();
730 return false;
731 }
732 return true;
733 }
734
735 // Check this LValue refers to an object. If not, set the designator to be
736 // invalid and emit a diagnostic.
737 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000738 // Outside C++11, do not build a designator referring to a subobject of
739 // any object: we won't use such a designator for anything.
740 if (!Info.getLangOpts().CPlusPlus0x)
741 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000742 return checkNullPointer(Info, E, CSK) &&
743 Designator.checkSubobject(Info, E, CSK);
744 }
745
746 void addDecl(EvalInfo &Info, const Expr *E,
747 const Decl *D, bool Virtual = false) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000748 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
749 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000750 }
751 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000752 if (checkSubobject(Info, E, CSK_ArrayToPointer))
753 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000754 }
Richard Smith86024012012-02-18 22:04:06 +0000755 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000756 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
757 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000758 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000759 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000760 if (checkNullPointer(Info, E, CSK_ArrayIndex))
761 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000762 }
John McCallefdb83e2010-05-07 21:00:08 +0000763 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000764
765 struct MemberPtr {
766 MemberPtr() {}
767 explicit MemberPtr(const ValueDecl *Decl) :
768 DeclAndIsDerivedMember(Decl, false), Path() {}
769
770 /// The member or (direct or indirect) field referred to by this member
771 /// pointer, or 0 if this is a null member pointer.
772 const ValueDecl *getDecl() const {
773 return DeclAndIsDerivedMember.getPointer();
774 }
775 /// Is this actually a member of some type derived from the relevant class?
776 bool isDerivedMember() const {
777 return DeclAndIsDerivedMember.getInt();
778 }
779 /// Get the class which the declaration actually lives in.
780 const CXXRecordDecl *getContainingRecord() const {
781 return cast<CXXRecordDecl>(
782 DeclAndIsDerivedMember.getPointer()->getDeclContext());
783 }
784
Richard Smith1aa0be82012-03-03 22:46:17 +0000785 void moveInto(APValue &V) const {
786 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000787 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000788 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000789 assert(V.isMemberPointer());
790 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
791 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
792 Path.clear();
793 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
794 Path.insert(Path.end(), P.begin(), P.end());
795 }
796
797 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
798 /// whether the member is a member of some class derived from the class type
799 /// of the member pointer.
800 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
801 /// Path - The path of base/derived classes from the member declaration's
802 /// class (exclusive) to the class type of the member pointer (inclusive).
803 SmallVector<const CXXRecordDecl*, 4> Path;
804
805 /// Perform a cast towards the class of the Decl (either up or down the
806 /// hierarchy).
807 bool castBack(const CXXRecordDecl *Class) {
808 assert(!Path.empty());
809 const CXXRecordDecl *Expected;
810 if (Path.size() >= 2)
811 Expected = Path[Path.size() - 2];
812 else
813 Expected = getContainingRecord();
814 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
815 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
816 // if B does not contain the original member and is not a base or
817 // derived class of the class containing the original member, the result
818 // of the cast is undefined.
819 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
820 // (D::*). We consider that to be a language defect.
821 return false;
822 }
823 Path.pop_back();
824 return true;
825 }
826 /// Perform a base-to-derived member pointer cast.
827 bool castToDerived(const CXXRecordDecl *Derived) {
828 if (!getDecl())
829 return true;
830 if (!isDerivedMember()) {
831 Path.push_back(Derived);
832 return true;
833 }
834 if (!castBack(Derived))
835 return false;
836 if (Path.empty())
837 DeclAndIsDerivedMember.setInt(false);
838 return true;
839 }
840 /// Perform a derived-to-base member pointer cast.
841 bool castToBase(const CXXRecordDecl *Base) {
842 if (!getDecl())
843 return true;
844 if (Path.empty())
845 DeclAndIsDerivedMember.setInt(true);
846 if (isDerivedMember()) {
847 Path.push_back(Base);
848 return true;
849 }
850 return castBack(Base);
851 }
852 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000853
Richard Smithb02e4622012-02-01 01:42:44 +0000854 /// Compare two member pointers, which are assumed to be of the same type.
855 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
856 if (!LHS.getDecl() || !RHS.getDecl())
857 return !LHS.getDecl() && !RHS.getDecl();
858 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
859 return false;
860 return LHS.Path == RHS.Path;
861 }
862
Richard Smithc1c5f272011-12-13 06:39:58 +0000863 /// Kinds of constant expression checking, for diagnostics.
864 enum CheckConstantExpressionKind {
865 CCEK_Constant, ///< A normal constant.
866 CCEK_ReturnValue, ///< A constexpr function return value.
867 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
868 };
John McCallf4cf1a12010-05-07 17:22:02 +0000869}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000870
Richard Smith1aa0be82012-03-03 22:46:17 +0000871static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000872static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
873 const LValue &This, const Expr *E,
874 CheckConstantExpressionKind CCEK = CCEK_Constant,
875 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000876static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
877static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000878static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
879 EvalInfo &Info);
880static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000881static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000882static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000883 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000884static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000885static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000886
887//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000888// Misc utilities
889//===----------------------------------------------------------------------===//
890
Richard Smith180f4792011-11-10 06:34:14 +0000891/// Should this call expression be treated as a string literal?
892static bool IsStringLiteralCall(const CallExpr *E) {
893 unsigned Builtin = E->isBuiltinCall();
894 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
895 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
896}
897
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000898static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000899 // C++11 [expr.const]p3 An address constant expression is a prvalue core
900 // constant expression of pointer type that evaluates to...
901
902 // ... a null pointer value, or a prvalue core constant expression of type
903 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000904 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000905
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000906 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
907 // ... the address of an object with static storage duration,
908 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
909 return VD->hasGlobalStorage();
910 // ... the address of a function,
911 return isa<FunctionDecl>(D);
912 }
913
914 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000915 switch (E->getStmtClass()) {
916 default:
917 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000918 case Expr::CompoundLiteralExprClass: {
919 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
920 return CLE->isFileScope() && CLE->isLValue();
921 }
Richard Smith180f4792011-11-10 06:34:14 +0000922 // A string literal has static storage duration.
923 case Expr::StringLiteralClass:
924 case Expr::PredefinedExprClass:
925 case Expr::ObjCStringLiteralClass:
926 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000927 case Expr::CXXTypeidExprClass:
Francois Pichete275a182012-04-16 04:08:35 +0000928 case Expr::CXXUuidofExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000929 return true;
930 case Expr::CallExprClass:
931 return IsStringLiteralCall(cast<CallExpr>(E));
932 // For GCC compatibility, &&label has static storage duration.
933 case Expr::AddrLabelExprClass:
934 return true;
935 // A Block literal expression may be used as the initialization value for
936 // Block variables at global or local static scope.
937 case Expr::BlockExprClass:
938 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000939 case Expr::ImplicitValueInitExprClass:
940 // FIXME:
941 // We can never form an lvalue with an implicit value initialization as its
942 // base through expression evaluation, so these only appear in one case: the
943 // implicit variable declaration we invent when checking whether a constexpr
944 // constructor can produce a constant expression. We must assume that such
945 // an expression might be a global lvalue.
946 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000947 }
John McCall42c8f872010-05-10 23:27:23 +0000948}
949
Richard Smith83587db2012-02-15 02:18:13 +0000950static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
951 assert(Base && "no location for a null lvalue");
952 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
953 if (VD)
954 Info.Note(VD->getLocation(), diag::note_declared_at);
955 else
956 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
957 diag::note_constexpr_temporary_here);
958}
959
Richard Smith9a17a682011-11-07 05:07:52 +0000960/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000961/// value for an address or reference constant expression. Return true if we
962/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000963static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
964 QualType Type, const LValue &LVal) {
965 bool IsReferenceType = Type->isReferenceType();
966
Richard Smithc1c5f272011-12-13 06:39:58 +0000967 APValue::LValueBase Base = LVal.getLValueBase();
968 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
969
Richard Smithb78ae972012-02-18 04:58:18 +0000970 // Check that the object is a global. Note that the fake 'this' object we
971 // manufacture when checking potential constant expressions is conservatively
972 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000973 if (!IsGlobalLValue(Base)) {
974 if (Info.getLangOpts().CPlusPlus0x) {
975 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000976 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
977 << IsReferenceType << !Designator.Entries.empty()
978 << !!VD << VD;
979 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000980 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000981 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000982 }
Richard Smith61e61622012-01-12 06:08:57 +0000983 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000984 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000985 }
Richard Smith83587db2012-02-15 02:18:13 +0000986 assert((Info.CheckingPotentialConstantExpression ||
987 LVal.getLValueCallIndex() == 0) &&
988 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +0000989
990 // Allow address constant expressions to be past-the-end pointers. This is
991 // an extension: the standard requires them to point to an object.
992 if (!IsReferenceType)
993 return true;
994
995 // A reference constant expression must refer to an object.
996 if (!Base) {
997 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +0000998 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +0000999 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001000 }
1001
Richard Smithc1c5f272011-12-13 06:39:58 +00001002 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001003 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001004 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001005 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001006 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001007 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001008 }
1009
Richard Smith9a17a682011-11-07 05:07:52 +00001010 return true;
1011}
1012
Richard Smith51201882011-12-30 21:15:51 +00001013/// Check that this core constant expression is of literal type, and if not,
1014/// produce an appropriate diagnostic.
1015static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1016 if (!E->isRValue() || E->getType()->isLiteralType())
1017 return true;
1018
1019 // Prvalue constant expressions must be of literal types.
1020 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001021 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001022 << E->getType();
1023 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001024 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001025 return false;
1026}
1027
Richard Smith47a1eed2011-10-29 20:57:55 +00001028/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001029/// constant expression. If not, report an appropriate diagnostic. Does not
1030/// check that the expression is of literal type.
1031static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1032 QualType Type, const APValue &Value) {
1033 // Core issue 1454: For a literal constant expression of array or class type,
1034 // each subobject of its value shall have been initialized by a constant
1035 // expression.
1036 if (Value.isArray()) {
1037 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1038 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1039 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1040 Value.getArrayInitializedElt(I)))
1041 return false;
1042 }
1043 if (!Value.hasArrayFiller())
1044 return true;
1045 return CheckConstantExpression(Info, DiagLoc, EltTy,
1046 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001047 }
Richard Smith83587db2012-02-15 02:18:13 +00001048 if (Value.isUnion() && Value.getUnionField()) {
1049 return CheckConstantExpression(Info, DiagLoc,
1050 Value.getUnionField()->getType(),
1051 Value.getUnionValue());
1052 }
1053 if (Value.isStruct()) {
1054 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1055 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1056 unsigned BaseIndex = 0;
1057 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1058 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1059 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1060 Value.getStructBase(BaseIndex)))
1061 return false;
1062 }
1063 }
1064 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1065 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001066 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1067 Value.getStructField(I->getFieldIndex())))
Richard Smith83587db2012-02-15 02:18:13 +00001068 return false;
1069 }
1070 }
1071
1072 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001073 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001074 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001075 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1076 }
1077
1078 // Everything else is fine.
1079 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001080}
1081
Richard Smith9e36b532011-10-31 05:11:32 +00001082const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001083 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001084}
1085
1086static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001087 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001088}
1089
Richard Smith65ac5982011-11-01 21:06:14 +00001090static bool IsWeakLValue(const LValue &Value) {
1091 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001092 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001093}
1094
Richard Smith1aa0be82012-03-03 22:46:17 +00001095static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001096 // A null base expression indicates a null pointer. These are always
1097 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001098 if (!Value.getLValueBase()) {
1099 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001100 return true;
1101 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001102
Richard Smithe24f5fc2011-11-17 22:56:20 +00001103 // We have a non-null base. These are generally known to be true, but if it's
1104 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001105 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001106 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001107 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001108}
1109
Richard Smith1aa0be82012-03-03 22:46:17 +00001110static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001111 switch (Val.getKind()) {
1112 case APValue::Uninitialized:
1113 return false;
1114 case APValue::Int:
1115 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001116 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001117 case APValue::Float:
1118 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001119 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001120 case APValue::ComplexInt:
1121 Result = Val.getComplexIntReal().getBoolValue() ||
1122 Val.getComplexIntImag().getBoolValue();
1123 return true;
1124 case APValue::ComplexFloat:
1125 Result = !Val.getComplexFloatReal().isZero() ||
1126 !Val.getComplexFloatImag().isZero();
1127 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001128 case APValue::LValue:
1129 return EvalPointerValueAsBool(Val, Result);
1130 case APValue::MemberPointer:
1131 Result = Val.getMemberPointerDecl();
1132 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001133 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001134 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001135 case APValue::Struct:
1136 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001137 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001138 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001139 }
1140
Richard Smithc49bd112011-10-28 17:51:58 +00001141 llvm_unreachable("unknown APValue kind");
1142}
1143
1144static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1145 EvalInfo &Info) {
1146 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001147 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001148 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001149 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001150 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001151}
1152
Richard Smithc1c5f272011-12-13 06:39:58 +00001153template<typename T>
Eli Friedman26dc97c2012-07-17 21:03:05 +00001154static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +00001155 const T &SrcValue, QualType DestType) {
Eli Friedman26dc97c2012-07-17 21:03:05 +00001156 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001157 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001158}
1159
1160static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1161 QualType SrcType, const APFloat &Value,
1162 QualType DestType, APSInt &Result) {
1163 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001164 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001165 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001166
Richard Smithc1c5f272011-12-13 06:39:58 +00001167 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001168 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001169 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1170 & APFloat::opInvalidOp)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001171 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001172 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001173}
1174
Richard Smithc1c5f272011-12-13 06:39:58 +00001175static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1176 QualType SrcType, QualType DestType,
1177 APFloat &Result) {
1178 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001179 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001180 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1181 APFloat::rmNearestTiesToEven, &ignored)
1182 & APFloat::opOverflow)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001183 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001184 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001185}
1186
Richard Smithf72fccf2012-01-30 22:27:01 +00001187static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1188 QualType DestType, QualType SrcType,
1189 APSInt &Value) {
1190 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001191 APSInt Result = Value;
1192 // Figure out if this is a truncate, extend or noop cast.
1193 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001194 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001195 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001196 return Result;
1197}
1198
Richard Smithc1c5f272011-12-13 06:39:58 +00001199static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1200 QualType SrcType, const APSInt &Value,
1201 QualType DestType, APFloat &Result) {
1202 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1203 if (Result.convertFromAPInt(Value, Value.isSigned(),
1204 APFloat::rmNearestTiesToEven)
1205 & APFloat::opOverflow)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001206 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001207 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001208}
1209
Eli Friedmane6a24e82011-12-22 03:51:45 +00001210static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1211 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001212 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001213 if (!Evaluate(SVal, Info, E))
1214 return false;
1215 if (SVal.isInt()) {
1216 Res = SVal.getInt();
1217 return true;
1218 }
1219 if (SVal.isFloat()) {
1220 Res = SVal.getFloat().bitcastToAPInt();
1221 return true;
1222 }
1223 if (SVal.isVector()) {
1224 QualType VecTy = E->getType();
1225 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1226 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1227 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1228 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1229 Res = llvm::APInt::getNullValue(VecSize);
1230 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1231 APValue &Elt = SVal.getVectorElt(i);
1232 llvm::APInt EltAsInt;
1233 if (Elt.isInt()) {
1234 EltAsInt = Elt.getInt();
1235 } else if (Elt.isFloat()) {
1236 EltAsInt = Elt.getFloat().bitcastToAPInt();
1237 } else {
1238 // Don't try to handle vectors of anything other than int or float
1239 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001240 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001241 return false;
1242 }
1243 unsigned BaseEltSize = EltAsInt.getBitWidth();
1244 if (BigEndian)
1245 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1246 else
1247 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1248 }
1249 return true;
1250 }
1251 // Give up if the input isn't an int, float, or vector. For example, we
1252 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001253 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001254 return false;
1255}
1256
Richard Smithb4e85ed2012-01-06 16:39:00 +00001257/// Cast an lvalue referring to a base subobject to a derived class, by
1258/// truncating the lvalue's path to the given length.
1259static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1260 const RecordDecl *TruncatedType,
1261 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001262 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001263
1264 // Check we actually point to a derived class object.
1265 if (TruncatedElements == D.Entries.size())
1266 return true;
1267 assert(TruncatedElements >= D.MostDerivedPathLength &&
1268 "not casting to a derived class");
1269 if (!Result.checkSubobject(Info, E, CSK_Derived))
1270 return false;
1271
1272 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001273 const RecordDecl *RD = TruncatedType;
1274 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCall8d59dee2012-05-01 00:38:49 +00001275 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001276 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1277 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001278 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001279 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001280 else
Richard Smith180f4792011-11-10 06:34:14 +00001281 Result.Offset -= Layout.getBaseClassOffset(Base);
1282 RD = Base;
1283 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001284 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001285 return true;
1286}
1287
John McCall8d59dee2012-05-01 00:38:49 +00001288static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001289 const CXXRecordDecl *Derived,
1290 const CXXRecordDecl *Base,
1291 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001292 if (!RL) {
1293 if (Derived->isInvalidDecl()) return false;
1294 RL = &Info.Ctx.getASTRecordLayout(Derived);
1295 }
1296
Richard Smith180f4792011-11-10 06:34:14 +00001297 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001298 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCall8d59dee2012-05-01 00:38:49 +00001299 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001300}
1301
Richard Smithb4e85ed2012-01-06 16:39:00 +00001302static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001303 const CXXRecordDecl *DerivedDecl,
1304 const CXXBaseSpecifier *Base) {
1305 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1306
John McCall8d59dee2012-05-01 00:38:49 +00001307 if (!Base->isVirtual())
1308 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001309
Richard Smithb4e85ed2012-01-06 16:39:00 +00001310 SubobjectDesignator &D = Obj.Designator;
1311 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001312 return false;
1313
Richard Smithb4e85ed2012-01-06 16:39:00 +00001314 // Extract most-derived object and corresponding type.
1315 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1316 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1317 return false;
1318
1319 // Find the virtual base class.
John McCall8d59dee2012-05-01 00:38:49 +00001320 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001321 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1322 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001323 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001324 return true;
1325}
1326
1327/// Update LVal to refer to the given field, which must be a member of the type
1328/// currently described by LVal.
John McCall8d59dee2012-05-01 00:38:49 +00001329static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001330 const FieldDecl *FD,
1331 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001332 if (!RL) {
1333 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001334 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCall8d59dee2012-05-01 00:38:49 +00001335 }
Richard Smith180f4792011-11-10 06:34:14 +00001336
1337 unsigned I = FD->getFieldIndex();
1338 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001339 LVal.addDecl(Info, E, FD);
John McCall8d59dee2012-05-01 00:38:49 +00001340 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001341}
1342
Richard Smithd9b02e72012-01-25 22:15:11 +00001343/// Update LVal to refer to the given indirect field.
John McCall8d59dee2012-05-01 00:38:49 +00001344static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smithd9b02e72012-01-25 22:15:11 +00001345 LValue &LVal,
1346 const IndirectFieldDecl *IFD) {
1347 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1348 CE = IFD->chain_end(); C != CE; ++C)
John McCall8d59dee2012-05-01 00:38:49 +00001349 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1350 return false;
1351 return true;
Richard Smithd9b02e72012-01-25 22:15:11 +00001352}
1353
Richard Smith180f4792011-11-10 06:34:14 +00001354/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001355static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1356 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001357 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1358 // extension.
1359 if (Type->isVoidType() || Type->isFunctionType()) {
1360 Size = CharUnits::One();
1361 return true;
1362 }
1363
1364 if (!Type->isConstantSizeType()) {
1365 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001366 // FIXME: Better diagnostic.
1367 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001368 return false;
1369 }
1370
1371 Size = Info.Ctx.getTypeSizeInChars(Type);
1372 return true;
1373}
1374
1375/// Update a pointer value to model pointer arithmetic.
1376/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001377/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001378/// \param LVal - The pointer value to be updated.
1379/// \param EltTy - The pointee type represented by LVal.
1380/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001381static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1382 LValue &LVal, QualType EltTy,
1383 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001384 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001385 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001386 return false;
1387
1388 // Compute the new offset in the appropriate width.
1389 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001390 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001391 return true;
1392}
1393
Richard Smith86024012012-02-18 22:04:06 +00001394/// Update an lvalue to refer to a component of a complex number.
1395/// \param Info - Information about the ongoing evaluation.
1396/// \param LVal - The lvalue to be updated.
1397/// \param EltTy - The complex number's component type.
1398/// \param Imag - False for the real component, true for the imaginary.
1399static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1400 LValue &LVal, QualType EltTy,
1401 bool Imag) {
1402 if (Imag) {
1403 CharUnits SizeOfComponent;
1404 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1405 return false;
1406 LVal.Offset += SizeOfComponent;
1407 }
1408 LVal.addComplex(Info, E, EltTy, Imag);
1409 return true;
1410}
1411
Richard Smith03f96112011-10-24 17:54:18 +00001412/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001413static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1414 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001415 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001416 // If this is a parameter to an active constexpr function call, perform
1417 // argument substitution.
1418 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001419 // Assume arguments of a potential constant expression are unknown
1420 // constant expressions.
1421 if (Info.CheckingPotentialConstantExpression)
1422 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001423 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001424 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001425 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001426 }
Richard Smith177dce72011-11-01 16:57:24 +00001427 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1428 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001429 }
Richard Smith03f96112011-10-24 17:54:18 +00001430
Richard Smith099e7f62011-12-19 06:19:21 +00001431 // Dig out the initializer, and use the declaration which it's attached to.
1432 const Expr *Init = VD->getAnyInitializer(VD);
1433 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001434 // If we're checking a potential constant expression, the variable could be
1435 // initialized later.
1436 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001437 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001438 return false;
1439 }
1440
Richard Smith180f4792011-11-10 06:34:14 +00001441 // If we're currently evaluating the initializer of this declaration, use that
1442 // in-flight value.
1443 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001444 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001445 return !Result.isUninit();
1446 }
1447
Richard Smith65ac5982011-11-01 21:06:14 +00001448 // Never evaluate the initializer of a weak variable. We can't be sure that
1449 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001450 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001451 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001452 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001453 }
Richard Smith65ac5982011-11-01 21:06:14 +00001454
Richard Smith099e7f62011-12-19 06:19:21 +00001455 // Check that we can fold the initializer. In C++, we will have already done
1456 // this in the cases where it matters for conformance.
1457 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1458 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001459 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001460 Notes.size() + 1) << VD;
1461 Info.Note(VD->getLocation(), diag::note_declared_at);
1462 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001463 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001464 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001465 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001466 Notes.size() + 1) << VD;
1467 Info.Note(VD->getLocation(), diag::note_declared_at);
1468 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001469 }
Richard Smith03f96112011-10-24 17:54:18 +00001470
Richard Smith1aa0be82012-03-03 22:46:17 +00001471 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001472 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001473}
1474
Richard Smithc49bd112011-10-28 17:51:58 +00001475static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001476 Qualifiers Quals = T.getQualifiers();
1477 return Quals.hasConst() && !Quals.hasVolatile();
1478}
1479
Richard Smith59efe262011-11-11 04:05:33 +00001480/// Get the base index of the given base class within an APValue representing
1481/// the given derived class.
1482static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1483 const CXXRecordDecl *Base) {
1484 Base = Base->getCanonicalDecl();
1485 unsigned Index = 0;
1486 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1487 E = Derived->bases_end(); I != E; ++I, ++Index) {
1488 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1489 return Index;
1490 }
1491
1492 llvm_unreachable("base class missing from derived class's bases list");
1493}
1494
Richard Smithfe587202012-04-15 02:50:59 +00001495/// Extract the value of a character from a string literal. CharType is used to
1496/// determine the expected signedness of the result -- a string literal used to
1497/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1498/// of the wrong signedness.
Richard Smithf3908f22012-02-17 03:35:37 +00001499static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smithfe587202012-04-15 02:50:59 +00001500 uint64_t Index, QualType CharType) {
Richard Smithf3908f22012-02-17 03:35:37 +00001501 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1502 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1503 assert(S && "unexpected string literal expression kind");
Richard Smithfe587202012-04-15 02:50:59 +00001504 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smithf3908f22012-02-17 03:35:37 +00001505
1506 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smithfe587202012-04-15 02:50:59 +00001507 CharType->isUnsignedIntegerType());
Richard Smithf3908f22012-02-17 03:35:37 +00001508 if (Index < S->getLength())
1509 Value = S->getCodeUnit(Index);
1510 return Value;
1511}
1512
Richard Smithcc5d4f62011-11-07 09:22:26 +00001513/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001514static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001515 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001516 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001517 if (Sub.Invalid)
1518 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001519 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001520 if (Sub.isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001521 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001522 (unsigned)diag::note_constexpr_read_past_end :
1523 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001524 return false;
1525 }
Richard Smithf64699e2011-11-11 08:28:03 +00001526 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001527 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001528 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1529 // This object might be initialized later.
1530 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001531
Richard Smith0069b842012-03-10 00:28:11 +00001532 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001533 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001534 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001535 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001536 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001537 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001538 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001539 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001540 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001541 // Note, it should not be possible to form a pointer with a valid
1542 // designator which points more than one past the end of the array.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001543 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001544 (unsigned)diag::note_constexpr_read_past_end :
1545 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001546 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001547 }
Richard Smithf3908f22012-02-17 03:35:37 +00001548 // An array object is represented as either an Array APValue or as an
1549 // LValue which refers to a string literal.
1550 if (O->isLValue()) {
1551 assert(I == N - 1 && "extracting subobject of character?");
1552 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001553 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithfe587202012-04-15 02:50:59 +00001554 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smithf3908f22012-02-17 03:35:37 +00001555 return true;
1556 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001557 O = &O->getArrayInitializedElt(Index);
1558 else
1559 O = &O->getArrayFiller();
1560 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001561 } else if (ObjType->isAnyComplexType()) {
1562 // Next subobject is a complex number.
1563 uint64_t Index = Sub.Entries[I].ArrayIndex;
1564 if (Index > 1) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001565 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Richard Smith86024012012-02-18 22:04:06 +00001566 (unsigned)diag::note_constexpr_read_past_end :
1567 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1568 return false;
1569 }
1570 assert(I == N - 1 && "extracting subobject of scalar?");
1571 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001572 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001573 : O->getComplexIntReal());
1574 } else {
1575 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001576 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001577 : O->getComplexFloatReal());
1578 }
1579 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001580 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001581 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001582 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001583 << Field;
1584 Info.Note(Field->getLocation(), diag::note_declared_at);
1585 return false;
1586 }
1587
Richard Smith180f4792011-11-10 06:34:14 +00001588 // Next subobject is a class, struct or union field.
1589 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1590 if (RD->isUnion()) {
1591 const FieldDecl *UnionField = O->getUnionField();
1592 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001593 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001594 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001595 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001596 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001597 }
Richard Smith180f4792011-11-10 06:34:14 +00001598 O = &O->getUnionValue();
1599 } else
1600 O = &O->getStructField(Field->getFieldIndex());
1601 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001602
1603 if (ObjType.isVolatileQualified()) {
1604 if (Info.getLangOpts().CPlusPlus) {
1605 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001606 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001607 << 2 << Field;
1608 Info.Note(Field->getLocation(), diag::note_declared_at);
1609 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001610 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001611 }
1612 return false;
1613 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001614 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001615 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001616 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1617 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1618 O = &O->getStructBase(getBaseIndex(Derived, Base));
1619 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001620 }
Richard Smith180f4792011-11-10 06:34:14 +00001621
Richard Smithf48fdb02011-12-09 22:58:01 +00001622 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001623 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001624 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001625 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001626 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001627 }
1628
Richard Smith0069b842012-03-10 00:28:11 +00001629 // This may look super-stupid, but it serves an important purpose: if we just
1630 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1631 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1632 // object, which is destroyed by Tmp's destructor.
1633 APValue Tmp;
1634 O->swap(Tmp);
1635 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001636 return true;
1637}
1638
Richard Smithf15fda02012-02-02 01:16:57 +00001639/// Find the position where two subobject designators diverge, or equivalently
1640/// the length of the common initial subsequence.
1641static unsigned FindDesignatorMismatch(QualType ObjType,
1642 const SubobjectDesignator &A,
1643 const SubobjectDesignator &B,
1644 bool &WasArrayIndex) {
1645 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1646 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001647 if (!ObjType.isNull() &&
1648 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001649 // Next subobject is an array element.
1650 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1651 WasArrayIndex = true;
1652 return I;
1653 }
Richard Smith86024012012-02-18 22:04:06 +00001654 if (ObjType->isAnyComplexType())
1655 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1656 else
1657 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001658 } else {
1659 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1660 WasArrayIndex = false;
1661 return I;
1662 }
1663 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1664 // Next subobject is a field.
1665 ObjType = FD->getType();
1666 else
1667 // Next subobject is a base class.
1668 ObjType = QualType();
1669 }
1670 }
1671 WasArrayIndex = false;
1672 return I;
1673}
1674
1675/// Determine whether the given subobject designators refer to elements of the
1676/// same array object.
1677static bool AreElementsOfSameArray(QualType ObjType,
1678 const SubobjectDesignator &A,
1679 const SubobjectDesignator &B) {
1680 if (A.Entries.size() != B.Entries.size())
1681 return false;
1682
1683 bool IsArray = A.MostDerivedArraySize != 0;
1684 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1685 // A is a subobject of the array element.
1686 return false;
1687
1688 // If A (and B) designates an array element, the last entry will be the array
1689 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1690 // of length 1' case, and the entire path must match.
1691 bool WasArrayIndex;
1692 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1693 return CommonLength >= A.Entries.size() - IsArray;
1694}
1695
Richard Smith180f4792011-11-10 06:34:14 +00001696/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1697/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1698/// for looking up the glvalue referred to by an entity of reference type.
1699///
1700/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001701/// \param Conv - The expression for which we are performing the conversion.
1702/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001703/// \param Type - The type we expect this conversion to produce, before
1704/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001705/// \param LVal - The glvalue on which we are attempting to perform this action.
1706/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001707static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1708 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001709 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001710 if (LVal.Designator.Invalid)
1711 // A diagnostic will have already been produced.
1712 return false;
1713
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001714 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001715
Richard Smithf48fdb02011-12-09 22:58:01 +00001716 if (!LVal.Base) {
1717 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001718 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001719 return false;
1720 }
1721
Richard Smith83587db2012-02-15 02:18:13 +00001722 CallStackFrame *Frame = 0;
1723 if (LVal.CallIndex) {
1724 Frame = Info.getCallFrame(LVal.CallIndex);
1725 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001726 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001727 NoteLValueLocation(Info, LVal.Base);
1728 return false;
1729 }
1730 }
1731
Richard Smith7098cbd2011-12-21 05:04:46 +00001732 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1733 // is not a constant expression (even if the object is non-volatile). We also
1734 // apply this rule to C++98, in order to conform to the expected 'volatile'
1735 // semantics.
1736 if (Type.isVolatileQualified()) {
1737 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001738 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001739 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001740 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001741 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001742 }
Richard Smithc49bd112011-10-28 17:51:58 +00001743
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001744 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001745 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1746 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001747 // expressions are constant expressions too. Inside constexpr functions,
1748 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001749 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001750 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregord2008e22012-04-06 22:40:38 +00001751 if (VD) {
1752 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1753 VD = VDef;
1754 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001755 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001756 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001757 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001758 }
1759
Richard Smith7098cbd2011-12-21 05:04:46 +00001760 // DR1313: If the object is volatile-qualified but the glvalue was not,
1761 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001762 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001763 if (VT.isVolatileQualified()) {
1764 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001765 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001766 Info.Note(VD->getLocation(), diag::note_declared_at);
1767 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001768 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001769 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001770 return false;
1771 }
1772
1773 if (!isa<ParmVarDecl>(VD)) {
1774 if (VD->isConstexpr()) {
1775 // OK, we can read this variable.
1776 } else if (VT->isIntegralOrEnumerationType()) {
1777 if (!VT.isConstQualified()) {
1778 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001779 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001780 Info.Note(VD->getLocation(), diag::note_declared_at);
1781 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001782 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001783 }
1784 return false;
1785 }
1786 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1787 // We support folding of const floating-point types, in order to make
1788 // static const data members of such types (supported as an extension)
1789 // more useful.
1790 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001791 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001792 Info.Note(VD->getLocation(), diag::note_declared_at);
1793 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001794 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001795 }
1796 } else {
1797 // FIXME: Allow folding of values of any literal type in all languages.
1798 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001799 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001800 Info.Note(VD->getLocation(), diag::note_declared_at);
1801 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001802 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001803 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001804 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001805 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001806 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001807
Richard Smithf48fdb02011-12-09 22:58:01 +00001808 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001809 return false;
1810
Richard Smith47a1eed2011-10-29 20:57:55 +00001811 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001812 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001813
1814 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1815 // conversion. This happens when the declaration and the lvalue should be
1816 // considered synonymous, for instance when initializing an array of char
1817 // from a string literal. Continue as if the initializer lvalue was the
1818 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001819 assert(RVal.getLValueOffset().isZero() &&
1820 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001821 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001822
1823 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1824 Frame = Info.getCallFrame(CallIndex);
1825 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001826 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001827 NoteLValueLocation(Info, RVal.getLValueBase());
1828 return false;
1829 }
1830 } else {
1831 Frame = 0;
1832 }
Richard Smithc49bd112011-10-28 17:51:58 +00001833 }
1834
Richard Smith7098cbd2011-12-21 05:04:46 +00001835 // Volatile temporary objects cannot be read in constant expressions.
1836 if (Base->getType().isVolatileQualified()) {
1837 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001838 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001839 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1840 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001841 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001842 }
1843 return false;
1844 }
1845
Richard Smithcc5d4f62011-11-07 09:22:26 +00001846 if (Frame) {
1847 // If this is a temporary expression with a nontrivial initializer, grab the
1848 // value from the relevant stack frame.
1849 RVal = Frame->Temporaries[Base];
1850 } else if (const CompoundLiteralExpr *CLE
1851 = dyn_cast<CompoundLiteralExpr>(Base)) {
1852 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1853 // initializer until now for such expressions. Such an expression can't be
1854 // an ICE in C, so this only matters for fold.
1855 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1856 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1857 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001858 } else if (isa<StringLiteral>(Base)) {
1859 // We represent a string literal array as an lvalue pointing at the
1860 // corresponding expression, rather than building an array of chars.
1861 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001862 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001863 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001864 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001865 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001866 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001867
Richard Smithf48fdb02011-12-09 22:58:01 +00001868 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1869 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001870}
1871
Richard Smith59efe262011-11-11 04:05:33 +00001872/// Build an lvalue for the object argument of a member function call.
1873static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1874 LValue &This) {
1875 if (Object->getType()->isPointerType())
1876 return EvaluatePointer(Object, This, Info);
1877
1878 if (Object->isGLValue())
1879 return EvaluateLValue(Object, This, Info);
1880
Richard Smithe24f5fc2011-11-17 22:56:20 +00001881 if (Object->getType()->isLiteralType())
1882 return EvaluateTemporary(Object, This, Info);
1883
1884 return false;
1885}
1886
1887/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1888/// lvalue referring to the result.
1889///
1890/// \param Info - Information about the ongoing evaluation.
1891/// \param BO - The member pointer access operation.
1892/// \param LV - Filled in with a reference to the resulting object.
1893/// \param IncludeMember - Specifies whether the member itself is included in
1894/// the resulting LValue subobject designator. This is not possible when
1895/// creating a bound member function.
1896/// \return The field or method declaration to which the member pointer refers,
1897/// or 0 if evaluation fails.
1898static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1899 const BinaryOperator *BO,
1900 LValue &LV,
1901 bool IncludeMember = true) {
1902 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1903
Richard Smith745f5142012-01-27 01:14:48 +00001904 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1905 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001906 return 0;
1907
1908 MemberPtr MemPtr;
1909 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1910 return 0;
1911
1912 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1913 // member value, the behavior is undefined.
1914 if (!MemPtr.getDecl())
1915 return 0;
1916
Richard Smith745f5142012-01-27 01:14:48 +00001917 if (!EvalObjOK)
1918 return 0;
1919
Richard Smithe24f5fc2011-11-17 22:56:20 +00001920 if (MemPtr.isDerivedMember()) {
1921 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001922 // The end of the derived-to-base path for the base object must match the
1923 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001924 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001925 LV.Designator.Entries.size())
1926 return 0;
1927 unsigned PathLengthToMember =
1928 LV.Designator.Entries.size() - MemPtr.Path.size();
1929 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1930 const CXXRecordDecl *LVDecl = getAsBaseClass(
1931 LV.Designator.Entries[PathLengthToMember + I]);
1932 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1933 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1934 return 0;
1935 }
1936
1937 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001938 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1939 PathLengthToMember))
1940 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001941 } else if (!MemPtr.Path.empty()) {
1942 // Extend the LValue path with the member pointer's path.
1943 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1944 MemPtr.Path.size() + IncludeMember);
1945
1946 // Walk down to the appropriate base class.
1947 QualType LVType = BO->getLHS()->getType();
1948 if (const PointerType *PT = LVType->getAs<PointerType>())
1949 LVType = PT->getPointeeType();
1950 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1951 assert(RD && "member pointer access on non-class-type expression");
1952 // The first class in the path is that of the lvalue.
1953 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1954 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCall8d59dee2012-05-01 00:38:49 +00001955 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1956 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001957 RD = Base;
1958 }
1959 // Finally cast to the class containing the member.
John McCall8d59dee2012-05-01 00:38:49 +00001960 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1961 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001962 }
1963
1964 // Add the member. Note that we cannot build bound member functions here.
1965 if (IncludeMember) {
John McCall8d59dee2012-05-01 00:38:49 +00001966 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
1967 if (!HandleLValueMember(Info, BO, LV, FD))
1968 return 0;
1969 } else if (const IndirectFieldDecl *IFD =
1970 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
1971 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
1972 return 0;
1973 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00001974 llvm_unreachable("can't construct reference to bound member function");
John McCall8d59dee2012-05-01 00:38:49 +00001975 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001976 }
1977
1978 return MemPtr.getDecl();
1979}
1980
1981/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1982/// the provided lvalue, which currently refers to the base object.
1983static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1984 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001985 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001986 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001987 return false;
1988
Richard Smithb4e85ed2012-01-06 16:39:00 +00001989 QualType TargetQT = E->getType();
1990 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1991 TargetQT = PT->getPointeeType();
1992
1993 // Check this cast lands within the final derived-to-base subobject path.
1994 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001995 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00001996 << D.MostDerivedType << TargetQT;
1997 return false;
1998 }
1999
Richard Smithe24f5fc2011-11-17 22:56:20 +00002000 // Check the type of the final cast. We don't need to check the path,
2001 // since a cast can only be formed if the path is unique.
2002 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002003 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2004 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002005 if (NewEntriesSize == D.MostDerivedPathLength)
2006 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2007 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002008 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002009 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002010 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002011 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002012 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002013 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002014
2015 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002016 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002017}
2018
Mike Stumpc4c90452009-10-27 22:09:17 +00002019namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002020enum EvalStmtResult {
2021 /// Evaluation failed.
2022 ESR_Failed,
2023 /// Hit a 'return' statement.
2024 ESR_Returned,
2025 /// Evaluation succeeded.
2026 ESR_Succeeded
2027};
2028}
2029
2030// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002031static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002032 const Stmt *S) {
2033 switch (S->getStmtClass()) {
2034 default:
2035 return ESR_Failed;
2036
2037 case Stmt::NullStmtClass:
2038 case Stmt::DeclStmtClass:
2039 return ESR_Succeeded;
2040
Richard Smithc1c5f272011-12-13 06:39:58 +00002041 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002042 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002043 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002044 return ESR_Failed;
2045 return ESR_Returned;
2046 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002047
2048 case Stmt::CompoundStmtClass: {
2049 const CompoundStmt *CS = cast<CompoundStmt>(S);
2050 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2051 BE = CS->body_end(); BI != BE; ++BI) {
2052 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2053 if (ESR != ESR_Succeeded)
2054 return ESR;
2055 }
2056 return ESR_Succeeded;
2057 }
2058 }
2059}
2060
Richard Smith61802452011-12-22 02:22:31 +00002061/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2062/// default constructor. If so, we'll fold it whether or not it's marked as
2063/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2064/// so we need special handling.
2065static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002066 const CXXConstructorDecl *CD,
2067 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002068 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2069 return false;
2070
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002071 // Value-initialization does not call a trivial default constructor, so such a
2072 // call is a core constant expression whether or not the constructor is
2073 // constexpr.
2074 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002075 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002076 // FIXME: If DiagDecl is an implicitly-declared special member function,
2077 // we should be much more explicit about why it's not constexpr.
2078 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2079 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2080 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002081 } else {
2082 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2083 }
2084 }
2085 return true;
2086}
2087
Richard Smithc1c5f272011-12-13 06:39:58 +00002088/// CheckConstexprFunction - Check that a function can be called in a constant
2089/// expression.
2090static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2091 const FunctionDecl *Declaration,
2092 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002093 // Potential constant expressions can contain calls to declared, but not yet
2094 // defined, constexpr functions.
2095 if (Info.CheckingPotentialConstantExpression && !Definition &&
2096 Declaration->isConstexpr())
2097 return false;
2098
Richard Smithc1c5f272011-12-13 06:39:58 +00002099 // Can we evaluate this function call?
2100 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2101 return true;
2102
2103 if (Info.getLangOpts().CPlusPlus0x) {
2104 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002105 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2106 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002107 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2108 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2109 << DiagDecl;
2110 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2111 } else {
2112 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2113 }
2114 return false;
2115}
2116
Richard Smith180f4792011-11-10 06:34:14 +00002117namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002118typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002119}
2120
2121/// EvaluateArgs - Evaluate the arguments to a function call.
2122static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2123 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002124 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002125 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002126 I != E; ++I) {
2127 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2128 // If we're checking for a potential constant expression, evaluate all
2129 // initializers even if some of them fail.
2130 if (!Info.keepEvaluatingAfterFailure())
2131 return false;
2132 Success = false;
2133 }
2134 }
2135 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002136}
2137
Richard Smithd0dccea2011-10-28 22:34:42 +00002138/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002139static bool HandleFunctionCall(SourceLocation CallLoc,
2140 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002141 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002142 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002143 ArgVector ArgValues(Args.size());
2144 if (!EvaluateArgs(Args, ArgValues, Info))
2145 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002146
Richard Smith745f5142012-01-27 01:14:48 +00002147 if (!Info.CheckCallLimit(CallLoc))
2148 return false;
2149
2150 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002151 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2152}
2153
Richard Smith180f4792011-11-10 06:34:14 +00002154/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002155static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002156 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002157 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002158 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002159 ArgVector ArgValues(Args.size());
2160 if (!EvaluateArgs(Args, ArgValues, Info))
2161 return false;
2162
Richard Smith745f5142012-01-27 01:14:48 +00002163 if (!Info.CheckCallLimit(CallLoc))
2164 return false;
2165
Richard Smith86c3ae42012-02-13 03:54:03 +00002166 const CXXRecordDecl *RD = Definition->getParent();
2167 if (RD->getNumVBases()) {
2168 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2169 return false;
2170 }
2171
Richard Smith745f5142012-01-27 01:14:48 +00002172 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002173
2174 // If it's a delegating constructor, just delegate.
2175 if (Definition->isDelegatingConstructor()) {
2176 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002177 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002178 }
2179
Richard Smith610a60c2012-01-10 04:32:03 +00002180 // For a trivial copy or move constructor, perform an APValue copy. This is
2181 // essential for unions, where the operations performed by the constructor
2182 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002183 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002184 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2185 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002186 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002187 RHS.setFrom(Info.Ctx, ArgValues[0]);
2188 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2189 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002190 }
2191
2192 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002193 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002194 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2195 std::distance(RD->field_begin(), RD->field_end()));
2196
John McCall8d59dee2012-05-01 00:38:49 +00002197 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00002198 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2199
Richard Smith745f5142012-01-27 01:14:48 +00002200 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002201 unsigned BasesSeen = 0;
2202#ifndef NDEBUG
2203 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2204#endif
2205 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2206 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002207 LValue Subobject = This;
2208 APValue *Value = &Result;
2209
2210 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002211 if ((*I)->isBaseInitializer()) {
2212 QualType BaseType((*I)->getBaseClass(), 0);
2213#ifndef NDEBUG
2214 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002215 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002216 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2217 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2218 "base class initializers not in expected order");
2219 ++BaseIt;
2220#endif
John McCall8d59dee2012-05-01 00:38:49 +00002221 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2222 BaseType->getAsCXXRecordDecl(), &Layout))
2223 return false;
Richard Smith745f5142012-01-27 01:14:48 +00002224 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002225 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCall8d59dee2012-05-01 00:38:49 +00002226 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2227 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002228 if (RD->isUnion()) {
2229 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002230 Value = &Result.getUnionValue();
2231 } else {
2232 Value = &Result.getStructField(FD->getFieldIndex());
2233 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002234 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002235 // Walk the indirect field decl's chain to find the object to initialize,
2236 // and make sure we've initialized every step along it.
2237 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2238 CE = IFD->chain_end();
2239 C != CE; ++C) {
2240 FieldDecl *FD = cast<FieldDecl>(*C);
2241 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2242 // Switch the union field if it differs. This happens if we had
2243 // preceding zero-initialization, and we're now initializing a union
2244 // subobject other than the first.
2245 // FIXME: In this case, the values of the other subobjects are
2246 // specified, since zero-initialization sets all padding bits to zero.
2247 if (Value->isUninit() ||
2248 (Value->isUnion() && Value->getUnionField() != FD)) {
2249 if (CD->isUnion())
2250 *Value = APValue(FD);
2251 else
2252 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2253 std::distance(CD->field_begin(), CD->field_end()));
2254 }
John McCall8d59dee2012-05-01 00:38:49 +00002255 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2256 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002257 if (CD->isUnion())
2258 Value = &Value->getUnionValue();
2259 else
2260 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002261 }
Richard Smith180f4792011-11-10 06:34:14 +00002262 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002263 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002264 }
Richard Smith745f5142012-01-27 01:14:48 +00002265
Richard Smith83587db2012-02-15 02:18:13 +00002266 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2267 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002268 ? CCEK_Constant : CCEK_MemberInit)) {
2269 // If we're checking for a potential constant expression, evaluate all
2270 // initializers even if some of them fail.
2271 if (!Info.keepEvaluatingAfterFailure())
2272 return false;
2273 Success = false;
2274 }
Richard Smith180f4792011-11-10 06:34:14 +00002275 }
2276
Richard Smith745f5142012-01-27 01:14:48 +00002277 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002278}
2279
Richard Smithd0dccea2011-10-28 22:34:42 +00002280namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002281class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002282 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002283 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002284public:
2285
Richard Smith1e12c592011-10-16 21:26:27 +00002286 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002287
2288 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002289 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002290 return true;
2291 }
2292
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002293 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2294 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002295 return Visit(E->getResultExpr());
2296 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002297 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002298 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002299 return true;
2300 return false;
2301 }
John McCallf85e1932011-06-15 23:02:42 +00002302 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002303 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002304 return true;
2305 return false;
2306 }
John McCallf85e1932011-06-15 23:02:42 +00002307
Mike Stumpc4c90452009-10-27 22:09:17 +00002308 // We don't want to evaluate BlockExprs multiple times, as they generate
2309 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002310 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2311 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2312 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002313 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002314 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2315 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2316 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2317 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2318 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2319 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002320 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002321 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002322 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002323 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002324 { return Visit(E->getChosenSubExpr(Ctx)); }
Nuno Lopesf195f2c2012-07-13 20:48:52 +00002325 bool VisitAbstractConditionalOperator(const AbstractConditionalOperator *E)
2326 { return Visit(E->getCond()) || Visit(E->getTrueExpr())
2327 || Visit(E->getFalseExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002328 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2329 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2330 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2331 bool VisitBinaryOperator(const BinaryOperator *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 VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2334 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2335 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2336 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2337 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002338 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002339 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002340 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002341 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002342 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Nico Weber381767f2012-07-20 03:39:05 +00002343 bool VisitGNUNullExpr(const GNUNullExpr *E) { return false; }
2344 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { return false; }
2345 bool VisitCXXThisExpr(const CXXThisExpr *E) { return false; }
2346 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
2347 return false;
2348 }
Chris Lattner363ff232010-04-13 17:34:23 +00002349
2350 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002351 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002352 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2353 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002354 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002355 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002356 return false;
2357 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002358
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002359 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002360};
2361
Mike Stumpc4c90452009-10-27 22:09:17 +00002362} // end anonymous namespace
2363
Eli Friedman4efaa272008-11-12 09:44:48 +00002364//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002365// Generic Evaluation
2366//===----------------------------------------------------------------------===//
2367namespace {
2368
Richard Smithf48fdb02011-12-09 22:58:01 +00002369// FIXME: RetTy is always bool. Remove it.
2370template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002371class ExprEvaluatorBase
2372 : public ConstStmtVisitor<Derived, RetTy> {
2373private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002374 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002375 return static_cast<Derived*>(this)->Success(V, E);
2376 }
Richard Smith51201882011-12-30 21:15:51 +00002377 RetTy DerivedZeroInitialization(const Expr *E) {
2378 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002379 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002380
Richard Smith74e1ad92012-02-16 02:46:34 +00002381 // Check whether a conditional operator with a non-constant condition is a
2382 // potential constant expression. If neither arm is a potential constant
2383 // expression, then the conditional operator is not either.
2384 template<typename ConditionalOperator>
2385 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2386 assert(Info.CheckingPotentialConstantExpression);
2387
2388 // Speculatively evaluate both arms.
2389 {
2390 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2391 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2392
2393 StmtVisitorTy::Visit(E->getFalseExpr());
2394 if (Diag.empty())
2395 return;
2396
2397 Diag.clear();
2398 StmtVisitorTy::Visit(E->getTrueExpr());
2399 if (Diag.empty())
2400 return;
2401 }
2402
2403 Error(E, diag::note_constexpr_conditional_never_const);
2404 }
2405
2406
2407 template<typename ConditionalOperator>
2408 bool HandleConditionalOperator(const ConditionalOperator *E) {
2409 bool BoolResult;
2410 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2411 if (Info.CheckingPotentialConstantExpression)
2412 CheckPotentialConstantConditional(E);
2413 return false;
2414 }
2415
2416 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2417 return StmtVisitorTy::Visit(EvalExpr);
2418 }
2419
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002420protected:
2421 EvalInfo &Info;
2422 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2423 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2424
Richard Smithdd1f29b2011-12-12 09:28:41 +00002425 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002426 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002427 }
2428
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00002429 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2430
2431public:
2432 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2433
2434 EvalInfo &getEvalInfo() { return Info; }
2435
Richard Smithf48fdb02011-12-09 22:58:01 +00002436 /// Report an evaluation error. This should only be called when an error is
2437 /// first discovered. When propagating an error, just return false.
2438 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002439 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002440 return false;
2441 }
2442 bool Error(const Expr *E) {
2443 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2444 }
2445
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002446 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002447 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002448 }
2449 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002450 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002451 }
2452
2453 RetTy VisitParenExpr(const ParenExpr *E)
2454 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2455 RetTy VisitUnaryExtension(const UnaryOperator *E)
2456 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2457 RetTy VisitUnaryPlus(const UnaryOperator *E)
2458 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2459 RetTy VisitChooseExpr(const ChooseExpr *E)
2460 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2461 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2462 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002463 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2464 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002465 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2466 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002467 // We cannot create any objects for which cleanups are required, so there is
2468 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2469 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2470 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002471
Richard Smithc216a012011-12-12 12:46:16 +00002472 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2473 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2474 return static_cast<Derived*>(this)->VisitCastExpr(E);
2475 }
2476 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2477 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2478 return static_cast<Derived*>(this)->VisitCastExpr(E);
2479 }
2480
Richard Smithe24f5fc2011-11-17 22:56:20 +00002481 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2482 switch (E->getOpcode()) {
2483 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002484 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002485
2486 case BO_Comma:
2487 VisitIgnoredValue(E->getLHS());
2488 return StmtVisitorTy::Visit(E->getRHS());
2489
2490 case BO_PtrMemD:
2491 case BO_PtrMemI: {
2492 LValue Obj;
2493 if (!HandleMemberPointerAccess(Info, E, Obj))
2494 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002495 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002496 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002497 return false;
2498 return DerivedSuccess(Result, E);
2499 }
2500 }
2501 }
2502
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002503 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002504 // Evaluate and cache the common expression. We treat it as a temporary,
2505 // even though it's not quite the same thing.
2506 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2507 Info, E->getCommon()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002508 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002509
Richard Smith74e1ad92012-02-16 02:46:34 +00002510 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002511 }
2512
2513 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002514 bool IsBcpCall = false;
2515 // If the condition (ignoring parens) is a __builtin_constant_p call,
2516 // the result is a constant expression if it can be folded without
2517 // side-effects. This is an important GNU extension. See GCC PR38377
2518 // for discussion.
2519 if (const CallExpr *CallCE =
2520 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2521 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2522 IsBcpCall = true;
2523
2524 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2525 // constant expression; we can't check whether it's potentially foldable.
2526 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2527 return false;
2528
2529 FoldConstant Fold(Info);
2530
Richard Smith74e1ad92012-02-16 02:46:34 +00002531 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002532 return false;
2533
2534 if (IsBcpCall)
2535 Fold.Fold(Info);
2536
2537 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002538 }
2539
2540 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002541 APValue &Value = Info.CurrentCall->Temporaries[E];
2542 if (Value.isUninit()) {
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002543 const Expr *Source = E->getSourceExpr();
2544 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002545 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002546 if (Source == E) { // sanity checking.
2547 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002548 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002549 }
2550 return StmtVisitorTy::Visit(Source);
2551 }
Richard Smithe92b1f42012-06-26 08:12:11 +00002552 return DerivedSuccess(Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002553 }
Richard Smithf10d9172011-10-11 21:43:33 +00002554
Richard Smithd0dccea2011-10-28 22:34:42 +00002555 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002556 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002557 QualType CalleeType = Callee->getType();
2558
Richard Smithd0dccea2011-10-28 22:34:42 +00002559 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002560 LValue *This = 0, ThisVal;
2561 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002562 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002563
Richard Smith59efe262011-11-11 04:05:33 +00002564 // Extract function decl and 'this' pointer from the callee.
2565 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002566 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002567 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2568 // Explicit bound member calls, such as x.f() or p->g();
2569 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002570 return false;
2571 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002572 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002573 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002574 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2575 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002576 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2577 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002578 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002579 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002580 return Error(Callee);
2581
2582 FD = dyn_cast<FunctionDecl>(Member);
2583 if (!FD)
2584 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002585 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002586 LValue Call;
2587 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002588 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002589
Richard Smithb4e85ed2012-01-06 16:39:00 +00002590 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002591 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002592 FD = dyn_cast_or_null<FunctionDecl>(
2593 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002594 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002595 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002596
2597 // Overloaded operator calls to member functions are represented as normal
2598 // calls with '*this' as the first argument.
2599 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2600 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002601 // FIXME: When selecting an implicit conversion for an overloaded
2602 // operator delete, we sometimes try to evaluate calls to conversion
2603 // operators without a 'this' parameter!
2604 if (Args.empty())
2605 return Error(E);
2606
Richard Smith59efe262011-11-11 04:05:33 +00002607 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2608 return false;
2609 This = &ThisVal;
2610 Args = Args.slice(1);
2611 }
2612
2613 // Don't call function pointers which have been cast to some other type.
2614 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002615 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002616 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002617 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002618
Richard Smithb04035a2012-02-01 02:39:43 +00002619 if (This && !This->checkSubobject(Info, E, CSK_This))
2620 return false;
2621
Richard Smith86c3ae42012-02-13 03:54:03 +00002622 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2623 // calls to such functions in constant expressions.
2624 if (This && !HasQualifier &&
2625 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2626 return Error(E, diag::note_constexpr_virtual_call);
2627
Richard Smithc1c5f272011-12-13 06:39:58 +00002628 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002629 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002630 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002631
Richard Smithc1c5f272011-12-13 06:39:58 +00002632 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002633 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2634 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002635 return false;
2636
Richard Smith83587db2012-02-15 02:18:13 +00002637 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002638 }
2639
Richard Smithc49bd112011-10-28 17:51:58 +00002640 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2641 return StmtVisitorTy::Visit(E->getInitializer());
2642 }
Richard Smithf10d9172011-10-11 21:43:33 +00002643 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002644 if (E->getNumInits() == 0)
2645 return DerivedZeroInitialization(E);
2646 if (E->getNumInits() == 1)
2647 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002648 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002649 }
2650 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002651 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002652 }
2653 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002654 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002655 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002656 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002657 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002658 }
Richard Smithf10d9172011-10-11 21:43:33 +00002659
Richard Smith180f4792011-11-10 06:34:14 +00002660 /// A member expression where the object is a prvalue is itself a prvalue.
2661 RetTy VisitMemberExpr(const MemberExpr *E) {
2662 assert(!E->isArrow() && "missing call to bound member function?");
2663
Richard Smith1aa0be82012-03-03 22:46:17 +00002664 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002665 if (!Evaluate(Val, Info, E->getBase()))
2666 return false;
2667
2668 QualType BaseTy = E->getBase()->getType();
2669
2670 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002671 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002672 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2673 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2674 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2675
Richard Smithb4e85ed2012-01-06 16:39:00 +00002676 SubobjectDesignator Designator(BaseTy);
2677 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002678
Richard Smithf48fdb02011-12-09 22:58:01 +00002679 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002680 DerivedSuccess(Val, E);
2681 }
2682
Richard Smithc49bd112011-10-28 17:51:58 +00002683 RetTy VisitCastExpr(const CastExpr *E) {
2684 switch (E->getCastKind()) {
2685 default:
2686 break;
2687
David Chisnall7a7ee302012-01-16 17:27:18 +00002688 case CK_AtomicToNonAtomic:
2689 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002690 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002691 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002692 return StmtVisitorTy::Visit(E->getSubExpr());
2693
2694 case CK_LValueToRValue: {
2695 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002696 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2697 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002698 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002699 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2700 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2701 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002702 return false;
2703 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002704 }
2705 }
2706
Richard Smithf48fdb02011-12-09 22:58:01 +00002707 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002708 }
2709
Richard Smith8327fad2011-10-24 18:44:57 +00002710 /// Visit a value which is evaluated, but whose value is ignored.
2711 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002712 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002713 if (!Evaluate(Scratch, Info, E))
2714 Info.EvalStatus.HasSideEffects = true;
2715 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002716};
2717
2718}
2719
2720//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002721// Common base class for lvalue and temporary evaluation.
2722//===----------------------------------------------------------------------===//
2723namespace {
2724template<class Derived>
2725class LValueExprEvaluatorBase
2726 : public ExprEvaluatorBase<Derived, bool> {
2727protected:
2728 LValue &Result;
2729 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2730 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2731
2732 bool Success(APValue::LValueBase B) {
2733 Result.set(B);
2734 return true;
2735 }
2736
2737public:
2738 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2739 ExprEvaluatorBaseTy(Info), Result(Result) {}
2740
Richard Smith1aa0be82012-03-03 22:46:17 +00002741 bool Success(const APValue &V, const Expr *E) {
2742 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002743 return true;
2744 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002745
Richard Smithe24f5fc2011-11-17 22:56:20 +00002746 bool VisitMemberExpr(const MemberExpr *E) {
2747 // Handle non-static data members.
2748 QualType BaseTy;
2749 if (E->isArrow()) {
2750 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2751 return false;
2752 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002753 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002754 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002755 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2756 return false;
2757 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002758 } else {
2759 if (!this->Visit(E->getBase()))
2760 return false;
2761 BaseTy = E->getBase()->getType();
2762 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002763
Richard Smithd9b02e72012-01-25 22:15:11 +00002764 const ValueDecl *MD = E->getMemberDecl();
2765 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2766 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2767 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2768 (void)BaseTy;
John McCall8d59dee2012-05-01 00:38:49 +00002769 if (!HandleLValueMember(this->Info, E, Result, FD))
2770 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002771 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCall8d59dee2012-05-01 00:38:49 +00002772 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2773 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002774 } else
2775 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002776
Richard Smithd9b02e72012-01-25 22:15:11 +00002777 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002778 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002779 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002780 RefValue))
2781 return false;
2782 return Success(RefValue, E);
2783 }
2784 return true;
2785 }
2786
2787 bool VisitBinaryOperator(const BinaryOperator *E) {
2788 switch (E->getOpcode()) {
2789 default:
2790 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2791
2792 case BO_PtrMemD:
2793 case BO_PtrMemI:
2794 return HandleMemberPointerAccess(this->Info, E, Result);
2795 }
2796 }
2797
2798 bool VisitCastExpr(const CastExpr *E) {
2799 switch (E->getCastKind()) {
2800 default:
2801 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2802
2803 case CK_DerivedToBase:
2804 case CK_UncheckedDerivedToBase: {
2805 if (!this->Visit(E->getSubExpr()))
2806 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002807
2808 // Now figure out the necessary offset to add to the base LV to get from
2809 // the derived class to the base class.
2810 QualType Type = E->getSubExpr()->getType();
2811
2812 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2813 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002814 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002815 *PathI))
2816 return false;
2817 Type = (*PathI)->getType();
2818 }
2819
2820 return true;
2821 }
2822 }
2823 }
2824};
2825}
2826
2827//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002828// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002829//
2830// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2831// function designators (in C), decl references to void objects (in C), and
2832// temporaries (if building with -Wno-address-of-temporary).
2833//
2834// LValue evaluation produces values comprising a base expression of one of the
2835// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002836// - Declarations
2837// * VarDecl
2838// * FunctionDecl
2839// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002840// * CompoundLiteralExpr in C
2841// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002842// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002843// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002844// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002845// * ObjCEncodeExpr
2846// * AddrLabelExpr
2847// * BlockExpr
2848// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002849// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002850// * Any Expr, with a CallIndex indicating the function in which the temporary
2851// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002852// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002853//===----------------------------------------------------------------------===//
2854namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002855class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002856 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002857public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002858 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2859 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002860
Richard Smithc49bd112011-10-28 17:51:58 +00002861 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2862
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002863 bool VisitDeclRefExpr(const DeclRefExpr *E);
2864 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002865 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002866 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2867 bool VisitMemberExpr(const MemberExpr *E);
2868 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2869 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002870 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichete275a182012-04-16 04:08:35 +00002871 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002872 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2873 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002874 bool VisitUnaryReal(const UnaryOperator *E);
2875 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002876
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002877 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002878 switch (E->getCastKind()) {
2879 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002880 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002881
Eli Friedmandb924222011-10-11 00:13:24 +00002882 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002883 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002884 if (!Visit(E->getSubExpr()))
2885 return false;
2886 Result.Designator.setInvalid();
2887 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002888
Richard Smithe24f5fc2011-11-17 22:56:20 +00002889 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002890 if (!Visit(E->getSubExpr()))
2891 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002892 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002893 }
2894 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002895};
2896} // end anonymous namespace
2897
Richard Smithc49bd112011-10-28 17:51:58 +00002898/// Evaluate an expression as an lvalue. This can be legitimately called on
2899/// expressions which are not glvalues, in a few cases:
2900/// * function designators in C,
2901/// * "extern void" objects,
2902/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002903static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002904 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2905 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2906 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002907 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002908}
2909
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002910bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002911 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2912 return Success(FD);
2913 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002914 return VisitVarDecl(E, VD);
2915 return Error(E);
2916}
Richard Smith436c8892011-10-24 23:14:33 +00002917
Richard Smithc49bd112011-10-28 17:51:58 +00002918bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002919 if (!VD->getType()->isReferenceType()) {
2920 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002921 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002922 return true;
2923 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002924 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002925 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002926
Richard Smith1aa0be82012-03-03 22:46:17 +00002927 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002928 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2929 return false;
2930 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002931}
2932
Richard Smithbd552ef2011-10-31 05:52:43 +00002933bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2934 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002935 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002936 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002937 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2938
Richard Smith83587db2012-02-15 02:18:13 +00002939 Result.set(E, Info.CurrentCall->Index);
2940 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2941 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002942 }
2943
2944 // Materialization of an lvalue temporary occurs when we need to force a copy
2945 // (for instance, if it's a bitfield).
2946 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2947 if (!Visit(E->GetTemporaryExpr()))
2948 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002949 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002950 Info.CurrentCall->Temporaries[E]))
2951 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002952 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002953 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002954}
2955
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002956bool
2957LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002958 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2959 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2960 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002961 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002962}
2963
Richard Smith47d21452011-12-27 12:18:28 +00002964bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2965 if (E->isTypeOperand())
2966 return Success(E);
2967 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2968 if (RD && RD->isPolymorphic()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002969 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith47d21452011-12-27 12:18:28 +00002970 << E->getExprOperand()->getType()
2971 << E->getExprOperand()->getSourceRange();
2972 return false;
2973 }
2974 return Success(E);
2975}
2976
Francois Pichete275a182012-04-16 04:08:35 +00002977bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2978 return Success(E);
2979}
2980
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002981bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002982 // Handle static data members.
2983 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2984 VisitIgnoredValue(E->getBase());
2985 return VisitVarDecl(E, VD);
2986 }
2987
Richard Smithd0dccea2011-10-28 22:34:42 +00002988 // Handle static member functions.
2989 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2990 if (MD->isStatic()) {
2991 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002992 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002993 }
2994 }
2995
Richard Smith180f4792011-11-10 06:34:14 +00002996 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002997 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002998}
2999
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003000bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003001 // FIXME: Deal with vectors as array subscript bases.
3002 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003003 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003004
Anders Carlsson3068d112008-11-16 19:01:22 +00003005 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003006 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003007
Anders Carlsson3068d112008-11-16 19:01:22 +00003008 APSInt Index;
3009 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003010 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003011 int64_t IndexValue
3012 = Index.isSigned() ? Index.getSExtValue()
3013 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003014
Richard Smithb4e85ed2012-01-06 16:39:00 +00003015 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003016}
Eli Friedman4efaa272008-11-12 09:44:48 +00003017
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003018bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003019 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003020}
3021
Richard Smith86024012012-02-18 22:04:06 +00003022bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3023 if (!Visit(E->getSubExpr()))
3024 return false;
3025 // __real is a no-op on scalar lvalues.
3026 if (E->getSubExpr()->getType()->isAnyComplexType())
3027 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3028 return true;
3029}
3030
3031bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3032 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3033 "lvalue __imag__ on scalar?");
3034 if (!Visit(E->getSubExpr()))
3035 return false;
3036 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3037 return true;
3038}
3039
Eli Friedman4efaa272008-11-12 09:44:48 +00003040//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003041// Pointer Evaluation
3042//===----------------------------------------------------------------------===//
3043
Anders Carlssonc754aa62008-07-08 05:13:58 +00003044namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003045class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003046 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003047 LValue &Result;
3048
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003049 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003050 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003051 return true;
3052 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003053public:
Mike Stump1eb44332009-09-09 15:08:12 +00003054
John McCallefdb83e2010-05-07 21:00:08 +00003055 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003056 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003057
Richard Smith1aa0be82012-03-03 22:46:17 +00003058 bool Success(const APValue &V, const Expr *E) {
3059 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003060 return true;
3061 }
Richard Smith51201882011-12-30 21:15:51 +00003062 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003063 return Success((Expr*)0);
3064 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003065
John McCallefdb83e2010-05-07 21:00:08 +00003066 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003067 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003068 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003069 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003070 { return Success(E); }
Patrick Beardeb382ec2012-04-19 00:25:12 +00003071 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003072 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003073 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003074 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003075 bool VisitCallExpr(const CallExpr *E);
3076 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003077 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003078 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003079 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003080 }
Richard Smith180f4792011-11-10 06:34:14 +00003081 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3082 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003083 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003084 Result = *Info.CurrentCall->This;
3085 return true;
3086 }
John McCall56ca35d2011-02-17 10:25:35 +00003087
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003088 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003089};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003090} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003091
John McCallefdb83e2010-05-07 21:00:08 +00003092static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003093 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003094 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003095}
3096
John McCallefdb83e2010-05-07 21:00:08 +00003097bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003098 if (E->getOpcode() != BO_Add &&
3099 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003100 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003101
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003102 const Expr *PExp = E->getLHS();
3103 const Expr *IExp = E->getRHS();
3104 if (IExp->getType()->isPointerType())
3105 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003106
Richard Smith745f5142012-01-27 01:14:48 +00003107 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3108 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003109 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003110
John McCallefdb83e2010-05-07 21:00:08 +00003111 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003112 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003113 return false;
3114 int64_t AdditionalOffset
3115 = Offset.isSigned() ? Offset.getSExtValue()
3116 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003117 if (E->getOpcode() == BO_Sub)
3118 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003119
Richard Smith180f4792011-11-10 06:34:14 +00003120 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003121 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3122 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003123}
Eli Friedman4efaa272008-11-12 09:44:48 +00003124
John McCallefdb83e2010-05-07 21:00:08 +00003125bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3126 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003127}
Mike Stump1eb44332009-09-09 15:08:12 +00003128
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003129bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3130 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003131
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003132 switch (E->getCastKind()) {
3133 default:
3134 break;
3135
John McCall2de56d12010-08-25 11:45:40 +00003136 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003137 case CK_CPointerToObjCPointerCast:
3138 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003139 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003140 if (!Visit(SubExpr))
3141 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003142 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3143 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3144 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003145 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003146 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003147 if (SubExpr->getType()->isVoidPointerType())
3148 CCEDiag(E, diag::note_constexpr_invalid_cast)
3149 << 3 << SubExpr->getType();
3150 else
3151 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3152 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003153 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003154
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003155 case CK_DerivedToBase:
3156 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003157 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003158 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003159 if (!Result.Base && Result.Offset.isZero())
3160 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003161
Richard Smith180f4792011-11-10 06:34:14 +00003162 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003163 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003164 QualType Type =
3165 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003166
Richard Smith180f4792011-11-10 06:34:14 +00003167 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003168 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003169 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3170 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003171 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003172 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003173 }
3174
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003175 return true;
3176 }
3177
Richard Smithe24f5fc2011-11-17 22:56:20 +00003178 case CK_BaseToDerived:
3179 if (!Visit(E->getSubExpr()))
3180 return false;
3181 if (!Result.Base && Result.Offset.isZero())
3182 return true;
3183 return HandleBaseToDerivedCast(Info, E, Result);
3184
Richard Smith47a1eed2011-10-29 20:57:55 +00003185 case CK_NullToPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003186 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003187 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003188
John McCall2de56d12010-08-25 11:45:40 +00003189 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003190 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3191
Richard Smith1aa0be82012-03-03 22:46:17 +00003192 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003193 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003194 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003195
John McCallefdb83e2010-05-07 21:00:08 +00003196 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003197 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3198 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003199 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003200 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003201 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003202 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003203 return true;
3204 } else {
3205 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003206 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003207 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003208 }
3209 }
John McCall2de56d12010-08-25 11:45:40 +00003210 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003211 if (SubExpr->isGLValue()) {
3212 if (!EvaluateLValue(SubExpr, Result, Info))
3213 return false;
3214 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003215 Result.set(SubExpr, Info.CurrentCall->Index);
3216 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3217 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003218 return false;
3219 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003220 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003221 if (const ConstantArrayType *CAT
3222 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3223 Result.addArray(Info, E, CAT);
3224 else
3225 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003226 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003227
John McCall2de56d12010-08-25 11:45:40 +00003228 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003229 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003230 }
3231
Richard Smithc49bd112011-10-28 17:51:58 +00003232 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003233}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003234
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003235bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003236 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003237 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003238
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003239 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003240}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003241
3242//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003243// Member Pointer Evaluation
3244//===----------------------------------------------------------------------===//
3245
3246namespace {
3247class MemberPointerExprEvaluator
3248 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3249 MemberPtr &Result;
3250
3251 bool Success(const ValueDecl *D) {
3252 Result = MemberPtr(D);
3253 return true;
3254 }
3255public:
3256
3257 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3258 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3259
Richard Smith1aa0be82012-03-03 22:46:17 +00003260 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003261 Result.setFrom(V);
3262 return true;
3263 }
Richard Smith51201882011-12-30 21:15:51 +00003264 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003265 return Success((const ValueDecl*)0);
3266 }
3267
3268 bool VisitCastExpr(const CastExpr *E);
3269 bool VisitUnaryAddrOf(const UnaryOperator *E);
3270};
3271} // end anonymous namespace
3272
3273static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3274 EvalInfo &Info) {
3275 assert(E->isRValue() && E->getType()->isMemberPointerType());
3276 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3277}
3278
3279bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3280 switch (E->getCastKind()) {
3281 default:
3282 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3283
3284 case CK_NullToMemberPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003285 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003286 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003287
3288 case CK_BaseToDerivedMemberPointer: {
3289 if (!Visit(E->getSubExpr()))
3290 return false;
3291 if (E->path_empty())
3292 return true;
3293 // Base-to-derived member pointer casts store the path in derived-to-base
3294 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3295 // the wrong end of the derived->base arc, so stagger the path by one class.
3296 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3297 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3298 PathI != PathE; ++PathI) {
3299 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3300 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3301 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003302 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003303 }
3304 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3305 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003306 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003307 return true;
3308 }
3309
3310 case CK_DerivedToBaseMemberPointer:
3311 if (!Visit(E->getSubExpr()))
3312 return false;
3313 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3314 PathE = E->path_end(); PathI != PathE; ++PathI) {
3315 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3316 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3317 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003318 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003319 }
3320 return true;
3321 }
3322}
3323
3324bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3325 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3326 // member can be formed.
3327 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3328}
3329
3330//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003331// Record Evaluation
3332//===----------------------------------------------------------------------===//
3333
3334namespace {
3335 class RecordExprEvaluator
3336 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3337 const LValue &This;
3338 APValue &Result;
3339 public:
3340
3341 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3342 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3343
Richard Smith1aa0be82012-03-03 22:46:17 +00003344 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003345 Result = V;
3346 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003347 }
Richard Smith51201882011-12-30 21:15:51 +00003348 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003349
Richard Smith59efe262011-11-11 04:05:33 +00003350 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003351 bool VisitInitListExpr(const InitListExpr *E);
3352 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3353 };
3354}
3355
Richard Smith51201882011-12-30 21:15:51 +00003356/// Perform zero-initialization on an object of non-union class type.
3357/// C++11 [dcl.init]p5:
3358/// To zero-initialize an object or reference of type T means:
3359/// [...]
3360/// -- if T is a (possibly cv-qualified) non-union class type,
3361/// each non-static data member and each base-class subobject is
3362/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003363static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3364 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003365 const LValue &This, APValue &Result) {
3366 assert(!RD->isUnion() && "Expected non-union class type");
3367 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3368 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3369 std::distance(RD->field_begin(), RD->field_end()));
3370
John McCall8d59dee2012-05-01 00:38:49 +00003371 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003372 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3373
3374 if (CD) {
3375 unsigned Index = 0;
3376 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003377 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003378 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3379 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003380 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3381 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003382 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003383 Result.getStructBase(Index)))
3384 return false;
3385 }
3386 }
3387
Richard Smithb4e85ed2012-01-06 16:39:00 +00003388 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3389 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003390 // -- if T is a reference type, no initialization is performed.
David Blaikie262bc182012-04-30 02:36:29 +00003391 if (I->getType()->isReferenceType())
Richard Smith51201882011-12-30 21:15:51 +00003392 continue;
3393
3394 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003395 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003396 return false;
Richard Smith51201882011-12-30 21:15:51 +00003397
David Blaikie262bc182012-04-30 02:36:29 +00003398 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003399 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003400 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003401 return false;
3402 }
3403
3404 return true;
3405}
3406
3407bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3408 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003409 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003410 if (RD->isUnion()) {
3411 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3412 // object's first non-static named data member is zero-initialized
3413 RecordDecl::field_iterator I = RD->field_begin();
3414 if (I == RD->field_end()) {
3415 Result = APValue((const FieldDecl*)0);
3416 return true;
3417 }
3418
3419 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003420 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCall8d59dee2012-05-01 00:38:49 +00003421 return false;
David Blaikie581deb32012-06-06 20:45:41 +00003422 Result = APValue(*I);
David Blaikie262bc182012-04-30 02:36:29 +00003423 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003424 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003425 }
3426
Richard Smithce582fe2012-02-17 00:44:16 +00003427 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003428 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003429 return false;
3430 }
3431
Richard Smithb4e85ed2012-01-06 16:39:00 +00003432 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003433}
3434
Richard Smith59efe262011-11-11 04:05:33 +00003435bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3436 switch (E->getCastKind()) {
3437 default:
3438 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3439
3440 case CK_ConstructorConversion:
3441 return Visit(E->getSubExpr());
3442
3443 case CK_DerivedToBase:
3444 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003445 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003446 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003447 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003448 if (!DerivedObject.isStruct())
3449 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003450
3451 // Derived-to-base rvalue conversion: just slice off the derived part.
3452 APValue *Value = &DerivedObject;
3453 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3454 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3455 PathE = E->path_end(); PathI != PathE; ++PathI) {
3456 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3457 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3458 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3459 RD = Base;
3460 }
3461 Result = *Value;
3462 return true;
3463 }
3464 }
3465}
3466
Richard Smith180f4792011-11-10 06:34:14 +00003467bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003468 // Cannot constant-evaluate std::initializer_list inits.
3469 if (E->initializesStdInitializerList())
3470 return false;
3471
Richard Smith180f4792011-11-10 06:34:14 +00003472 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003473 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00003474 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3475
3476 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003477 const FieldDecl *Field = E->getInitializedFieldInUnion();
3478 Result = APValue(Field);
3479 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003480 return true;
Richard Smithec789162012-01-12 18:54:33 +00003481
3482 // If the initializer list for a union does not contain any elements, the
3483 // first element of the union is value-initialized.
3484 ImplicitValueInitExpr VIE(Field->getType());
3485 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3486
Richard Smith180f4792011-11-10 06:34:14 +00003487 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003488 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3489 return false;
Richard Smith83587db2012-02-15 02:18:13 +00003490 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003491 }
3492
3493 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3494 "initializer list for class with base classes");
3495 Result = APValue(APValue::UninitStruct(), 0,
3496 std::distance(RD->field_begin(), RD->field_end()));
3497 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003498 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003499 for (RecordDecl::field_iterator Field = RD->field_begin(),
3500 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3501 // Anonymous bit-fields are not considered members of the class for
3502 // purposes of aggregate initialization.
3503 if (Field->isUnnamedBitfield())
3504 continue;
3505
3506 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003507
Richard Smith745f5142012-01-27 01:14:48 +00003508 bool HaveInit = ElementNo < E->getNumInits();
3509
3510 // FIXME: Diagnostics here should point to the end of the initializer
3511 // list, not the start.
John McCall8d59dee2012-05-01 00:38:49 +00003512 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie581deb32012-06-06 20:45:41 +00003513 Subobject, *Field, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003514 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003515
3516 // Perform an implicit value-initialization for members beyond the end of
3517 // the initializer list.
3518 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3519
Richard Smith83587db2012-02-15 02:18:13 +00003520 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003521 Result.getStructField(Field->getFieldIndex()),
Richard Smith745f5142012-01-27 01:14:48 +00003522 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3523 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003524 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003525 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003526 }
3527 }
3528
Richard Smith745f5142012-01-27 01:14:48 +00003529 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003530}
3531
3532bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3533 const CXXConstructorDecl *FD = E->getConstructor();
John McCall1de9d7d2012-04-26 18:10:01 +00003534 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3535
Richard Smith51201882011-12-30 21:15:51 +00003536 bool ZeroInit = E->requiresZeroInitialization();
3537 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003538 // If we've already performed zero-initialization, we're already done.
3539 if (!Result.isUninit())
3540 return true;
3541
Richard Smith51201882011-12-30 21:15:51 +00003542 if (ZeroInit)
3543 return ZeroInitialization(E);
3544
Richard Smith61802452011-12-22 02:22:31 +00003545 const CXXRecordDecl *RD = FD->getParent();
3546 if (RD->isUnion())
3547 Result = APValue((FieldDecl*)0);
3548 else
3549 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3550 std::distance(RD->field_begin(), RD->field_end()));
3551 return true;
3552 }
3553
Richard Smith180f4792011-11-10 06:34:14 +00003554 const FunctionDecl *Definition = 0;
3555 FD->getBody(Definition);
3556
Richard Smithc1c5f272011-12-13 06:39:58 +00003557 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3558 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003559
Richard Smith610a60c2012-01-10 04:32:03 +00003560 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003561 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003562 if (const MaterializeTemporaryExpr *ME
3563 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3564 return Visit(ME->GetTemporaryExpr());
3565
Richard Smith51201882011-12-30 21:15:51 +00003566 if (ZeroInit && !ZeroInitialization(E))
3567 return false;
3568
Richard Smith180f4792011-11-10 06:34:14 +00003569 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003570 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003571 cast<CXXConstructorDecl>(Definition), Info,
3572 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003573}
3574
3575static bool EvaluateRecord(const Expr *E, const LValue &This,
3576 APValue &Result, EvalInfo &Info) {
3577 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003578 "can't evaluate expression as a record rvalue");
3579 return RecordExprEvaluator(Info, This, Result).Visit(E);
3580}
3581
3582//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003583// Temporary Evaluation
3584//
3585// Temporaries are represented in the AST as rvalues, but generally behave like
3586// lvalues. The full-object of which the temporary is a subobject is implicitly
3587// materialized so that a reference can bind to it.
3588//===----------------------------------------------------------------------===//
3589namespace {
3590class TemporaryExprEvaluator
3591 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3592public:
3593 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3594 LValueExprEvaluatorBaseTy(Info, Result) {}
3595
3596 /// Visit an expression which constructs the value of this temporary.
3597 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003598 Result.set(E, Info.CurrentCall->Index);
3599 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003600 }
3601
3602 bool VisitCastExpr(const CastExpr *E) {
3603 switch (E->getCastKind()) {
3604 default:
3605 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3606
3607 case CK_ConstructorConversion:
3608 return VisitConstructExpr(E->getSubExpr());
3609 }
3610 }
3611 bool VisitInitListExpr(const InitListExpr *E) {
3612 return VisitConstructExpr(E);
3613 }
3614 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3615 return VisitConstructExpr(E);
3616 }
3617 bool VisitCallExpr(const CallExpr *E) {
3618 return VisitConstructExpr(E);
3619 }
3620};
3621} // end anonymous namespace
3622
3623/// Evaluate an expression of record type as a temporary.
3624static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003625 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003626 return TemporaryExprEvaluator(Info, Result).Visit(E);
3627}
3628
3629//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003630// Vector Evaluation
3631//===----------------------------------------------------------------------===//
3632
3633namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003634 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003635 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3636 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003637 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003638
Richard Smith07fc6572011-10-22 21:10:00 +00003639 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3640 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003641
Richard Smith07fc6572011-10-22 21:10:00 +00003642 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3643 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3644 // FIXME: remove this APValue copy.
3645 Result = APValue(V.data(), V.size());
3646 return true;
3647 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003648 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003649 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003650 Result = V;
3651 return true;
3652 }
Richard Smith51201882011-12-30 21:15:51 +00003653 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003654
Richard Smith07fc6572011-10-22 21:10:00 +00003655 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003656 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003657 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003658 bool VisitInitListExpr(const InitListExpr *E);
3659 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003660 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003661 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003662 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003663 };
3664} // end anonymous namespace
3665
3666static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003667 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003668 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003669}
3670
Richard Smith07fc6572011-10-22 21:10:00 +00003671bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3672 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003673 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003674
Richard Smithd62ca372011-12-06 22:44:34 +00003675 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003676 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003677
Eli Friedman46a52322011-03-25 00:43:55 +00003678 switch (E->getCastKind()) {
3679 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003680 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003681 if (SETy->isIntegerType()) {
3682 APSInt IntResult;
3683 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003684 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003685 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003686 } else if (SETy->isRealFloatingType()) {
3687 APFloat F(0.0);
3688 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003689 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003690 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003691 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003692 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003693 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003694
3695 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003696 SmallVector<APValue, 4> Elts(NElts, Val);
3697 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003698 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003699 case CK_BitCast: {
3700 // Evaluate the operand into an APInt we can extract from.
3701 llvm::APInt SValInt;
3702 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3703 return false;
3704 // Extract the elements
3705 QualType EltTy = VTy->getElementType();
3706 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3707 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3708 SmallVector<APValue, 4> Elts;
3709 if (EltTy->isRealFloatingType()) {
3710 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3711 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3712 unsigned FloatEltSize = EltSize;
3713 if (&Sem == &APFloat::x87DoubleExtended)
3714 FloatEltSize = 80;
3715 for (unsigned i = 0; i < NElts; i++) {
3716 llvm::APInt Elt;
3717 if (BigEndian)
3718 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3719 else
3720 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3721 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3722 }
3723 } else if (EltTy->isIntegerType()) {
3724 for (unsigned i = 0; i < NElts; i++) {
3725 llvm::APInt Elt;
3726 if (BigEndian)
3727 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3728 else
3729 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3730 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3731 }
3732 } else {
3733 return Error(E);
3734 }
3735 return Success(Elts, E);
3736 }
Eli Friedman46a52322011-03-25 00:43:55 +00003737 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003738 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003739 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003740}
3741
Richard Smith07fc6572011-10-22 21:10:00 +00003742bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003743VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003744 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003745 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003746 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003747
Nate Begeman59b5da62009-01-18 03:20:47 +00003748 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003749 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003750
Eli Friedman3edd5a92012-01-03 23:24:20 +00003751 // The number of initializers can be less than the number of
3752 // vector elements. For OpenCL, this can be due to nested vector
3753 // initialization. For GCC compatibility, missing trailing elements
3754 // should be initialized with zeroes.
3755 unsigned CountInits = 0, CountElts = 0;
3756 while (CountElts < NumElements) {
3757 // Handle nested vector initialization.
3758 if (CountInits < NumInits
3759 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3760 APValue v;
3761 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3762 return Error(E);
3763 unsigned vlen = v.getVectorLength();
3764 for (unsigned j = 0; j < vlen; j++)
3765 Elements.push_back(v.getVectorElt(j));
3766 CountElts += vlen;
3767 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003768 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003769 if (CountInits < NumInits) {
3770 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003771 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003772 } else // trailing integer zero.
3773 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3774 Elements.push_back(APValue(sInt));
3775 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003776 } else {
3777 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003778 if (CountInits < NumInits) {
3779 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003780 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003781 } else // trailing float zero.
3782 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3783 Elements.push_back(APValue(f));
3784 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003785 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003786 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003787 }
Richard Smith07fc6572011-10-22 21:10:00 +00003788 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003789}
3790
Richard Smith07fc6572011-10-22 21:10:00 +00003791bool
Richard Smith51201882011-12-30 21:15:51 +00003792VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003793 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003794 QualType EltTy = VT->getElementType();
3795 APValue ZeroElement;
3796 if (EltTy->isIntegerType())
3797 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3798 else
3799 ZeroElement =
3800 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3801
Chris Lattner5f9e2722011-07-23 10:55:15 +00003802 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003803 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003804}
3805
Richard Smith07fc6572011-10-22 21:10:00 +00003806bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003807 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003808 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003809}
3810
Nate Begeman59b5da62009-01-18 03:20:47 +00003811//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003812// Array Evaluation
3813//===----------------------------------------------------------------------===//
3814
3815namespace {
3816 class ArrayExprEvaluator
3817 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003818 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003819 APValue &Result;
3820 public:
3821
Richard Smith180f4792011-11-10 06:34:14 +00003822 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3823 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003824
3825 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003826 assert((V.isArray() || V.isLValue()) &&
3827 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003828 Result = V;
3829 return true;
3830 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003831
Richard Smith51201882011-12-30 21:15:51 +00003832 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003833 const ConstantArrayType *CAT =
3834 Info.Ctx.getAsConstantArrayType(E->getType());
3835 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003836 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003837
3838 Result = APValue(APValue::UninitArray(), 0,
3839 CAT->getSize().getZExtValue());
3840 if (!Result.hasArrayFiller()) return true;
3841
Richard Smith51201882011-12-30 21:15:51 +00003842 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003843 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003844 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003845 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003846 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003847 }
3848
Richard Smithcc5d4f62011-11-07 09:22:26 +00003849 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003850 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003851 };
3852} // end anonymous namespace
3853
Richard Smith180f4792011-11-10 06:34:14 +00003854static bool EvaluateArray(const Expr *E, const LValue &This,
3855 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003856 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003857 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003858}
3859
3860bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3861 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3862 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003863 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003864
Richard Smith974c5f92011-12-22 01:07:19 +00003865 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3866 // an appropriately-typed string literal enclosed in braces.
Richard Smithfe587202012-04-15 02:50:59 +00003867 if (E->isStringLiteralInit()) {
Richard Smith974c5f92011-12-22 01:07:19 +00003868 LValue LV;
3869 if (!EvaluateLValue(E->getInit(0), LV, Info))
3870 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003871 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003872 LV.moveInto(Val);
3873 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003874 }
3875
Richard Smith745f5142012-01-27 01:14:48 +00003876 bool Success = true;
3877
Richard Smithde31aa72012-07-07 22:48:24 +00003878 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
3879 "zero-initialized array shouldn't have any initialized elts");
3880 APValue Filler;
3881 if (Result.isArray() && Result.hasArrayFiller())
3882 Filler = Result.getArrayFiller();
3883
Richard Smithcc5d4f62011-11-07 09:22:26 +00003884 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3885 CAT->getSize().getZExtValue());
Richard Smithde31aa72012-07-07 22:48:24 +00003886
3887 // If the array was previously zero-initialized, preserve the
3888 // zero-initialized values.
3889 if (!Filler.isUninit()) {
3890 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
3891 Result.getArrayInitializedElt(I) = Filler;
3892 if (Result.hasArrayFiller())
3893 Result.getArrayFiller() = Filler;
3894 }
3895
Richard Smith180f4792011-11-10 06:34:14 +00003896 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003897 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003898 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003899 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003900 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003901 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3902 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003903 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3904 CAT->getElementType(), 1)) {
3905 if (!Info.keepEvaluatingAfterFailure())
3906 return false;
3907 Success = false;
3908 }
Richard Smith180f4792011-11-10 06:34:14 +00003909 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003910
Richard Smith745f5142012-01-27 01:14:48 +00003911 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003912 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003913 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3914 // but sometimes does:
3915 // struct S { constexpr S() : p(&p) {} void *p; };
3916 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003917 return EvaluateInPlace(Result.getArrayFiller(), Info,
3918 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003919}
3920
Richard Smithe24f5fc2011-11-17 22:56:20 +00003921bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smithde31aa72012-07-07 22:48:24 +00003922 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3923 // but sometimes does:
3924 // struct S { constexpr S() : p(&p) {} void *p; };
3925 // S s[10];
3926 LValue Subobject = This;
3927
3928 APValue *Value = &Result;
3929 bool HadZeroInit = true;
Richard Smitha4334df2012-07-10 22:12:55 +00003930 QualType ElemTy = E->getType();
3931 while (const ConstantArrayType *CAT =
3932 Info.Ctx.getAsConstantArrayType(ElemTy)) {
Richard Smithde31aa72012-07-07 22:48:24 +00003933 Subobject.addArray(Info, E, CAT);
3934 HadZeroInit &= !Value->isUninit();
3935 if (!HadZeroInit)
3936 *Value = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3937 if (!Value->hasArrayFiller())
3938 return true;
Richard Smithde31aa72012-07-07 22:48:24 +00003939 Value = &Value->getArrayFiller();
Richard Smitha4334df2012-07-10 22:12:55 +00003940 ElemTy = CAT->getElementType();
Richard Smithde31aa72012-07-07 22:48:24 +00003941 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00003942
Richard Smitha4334df2012-07-10 22:12:55 +00003943 if (!ElemTy->isRecordType())
3944 return Error(E);
3945
Richard Smithe24f5fc2011-11-17 22:56:20 +00003946 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003947
Richard Smith51201882011-12-30 21:15:51 +00003948 bool ZeroInit = E->requiresZeroInitialization();
3949 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003950 if (HadZeroInit)
3951 return true;
3952
Richard Smith51201882011-12-30 21:15:51 +00003953 if (ZeroInit) {
Richard Smitha4334df2012-07-10 22:12:55 +00003954 ImplicitValueInitExpr VIE(ElemTy);
Richard Smithde31aa72012-07-07 22:48:24 +00003955 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003956 }
3957
Richard Smith61802452011-12-22 02:22:31 +00003958 const CXXRecordDecl *RD = FD->getParent();
3959 if (RD->isUnion())
Richard Smithde31aa72012-07-07 22:48:24 +00003960 *Value = APValue((FieldDecl*)0);
Richard Smith61802452011-12-22 02:22:31 +00003961 else
Richard Smithde31aa72012-07-07 22:48:24 +00003962 *Value =
Richard Smith61802452011-12-22 02:22:31 +00003963 APValue(APValue::UninitStruct(), RD->getNumBases(),
3964 std::distance(RD->field_begin(), RD->field_end()));
3965 return true;
3966 }
3967
Richard Smithe24f5fc2011-11-17 22:56:20 +00003968 const FunctionDecl *Definition = 0;
3969 FD->getBody(Definition);
3970
Richard Smithc1c5f272011-12-13 06:39:58 +00003971 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3972 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003973
Richard Smithec789162012-01-12 18:54:33 +00003974 if (ZeroInit && !HadZeroInit) {
Richard Smitha4334df2012-07-10 22:12:55 +00003975 ImplicitValueInitExpr VIE(ElemTy);
Richard Smithde31aa72012-07-07 22:48:24 +00003976 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003977 return false;
3978 }
3979
Richard Smithe24f5fc2011-11-17 22:56:20 +00003980 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003981 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003982 cast<CXXConstructorDecl>(Definition),
Richard Smithde31aa72012-07-07 22:48:24 +00003983 Info, *Value);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003984}
3985
Richard Smithcc5d4f62011-11-07 09:22:26 +00003986//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003987// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003988//
3989// As a GNU extension, we support casting pointers to sufficiently-wide integer
3990// types and back in constant folding. Integer values are thus represented
3991// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003992//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003993
3994namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003995class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003996 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003997 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003998public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003999 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004000 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004001
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004002 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004003 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004004 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004005 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004006 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004007 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004008 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004009 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004010 return true;
4011 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004012 bool Success(const llvm::APSInt &SI, const Expr *E) {
4013 return Success(SI, E, Result);
4014 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004015
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004016 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004017 assert(E->getType()->isIntegralOrEnumerationType() &&
4018 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004019 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004020 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004021 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00004022 Result.getInt().setIsUnsigned(
4023 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00004024 return true;
4025 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004026 bool Success(const llvm::APInt &I, const Expr *E) {
4027 return Success(I, E, Result);
4028 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00004029
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004030 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004031 assert(E->getType()->isIntegralOrEnumerationType() &&
4032 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004033 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00004034 return true;
4035 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004036 bool Success(uint64_t Value, const Expr *E) {
4037 return Success(Value, E, Result);
4038 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00004039
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004040 bool Success(CharUnits Size, const Expr *E) {
4041 return Success(Size.getQuantity(), E);
4042 }
4043
Richard Smith1aa0be82012-03-03 22:46:17 +00004044 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00004045 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00004046 Result = V;
4047 return true;
4048 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004049 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00004050 }
Mike Stump1eb44332009-09-09 15:08:12 +00004051
Richard Smith51201882011-12-30 21:15:51 +00004052 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00004053
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004054 //===--------------------------------------------------------------------===//
4055 // Visitor Methods
4056 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004057
Chris Lattner4c4867e2008-07-12 00:38:25 +00004058 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004059 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004060 }
4061 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004062 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004063 }
Eli Friedman04309752009-11-24 05:28:59 +00004064
4065 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4066 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004067 if (CheckReferencedDecl(E, E->getDecl()))
4068 return true;
4069
4070 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004071 }
4072 bool VisitMemberExpr(const MemberExpr *E) {
4073 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004074 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004075 return true;
4076 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004077
4078 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004079 }
4080
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004081 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004082 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004083 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004084 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004085
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004086 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004087 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004088
Anders Carlsson3068d112008-11-16 19:01:22 +00004089 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004090 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004091 }
Mike Stump1eb44332009-09-09 15:08:12 +00004092
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004093 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4094 return Success(E->getValue(), E);
4095 }
4096
Richard Smithf10d9172011-10-11 21:43:33 +00004097 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004098 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004099 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004100 }
4101
Sebastian Redl64b45f72009-01-05 20:52:13 +00004102 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004103 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004104 }
4105
Francois Pichet6ad6f282010-12-07 00:08:36 +00004106 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4107 return Success(E->getValue(), E);
4108 }
4109
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004110 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4111 return Success(E->getValue(), E);
4112 }
4113
John Wiegley21ff2e52011-04-28 00:16:57 +00004114 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4115 return Success(E->getValue(), E);
4116 }
4117
John Wiegley55262202011-04-25 06:54:41 +00004118 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4119 return Success(E->getValue(), E);
4120 }
4121
Eli Friedman722c7172009-02-28 03:59:05 +00004122 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004123 bool VisitUnaryImag(const UnaryOperator *E);
4124
Sebastian Redl295995c2010-09-10 20:55:47 +00004125 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004126 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004127
Chris Lattnerfcee0012008-07-11 21:24:13 +00004128private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004129 CharUnits GetAlignOfExpr(const Expr *E);
4130 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004131 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004132 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004133 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004134};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004135} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004136
Richard Smithc49bd112011-10-28 17:51:58 +00004137/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4138/// produce either the integer value or a pointer.
4139///
4140/// GCC has a heinous extension which folds casts between pointer types and
4141/// pointer-sized integral types. We support this by allowing the evaluation of
4142/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4143/// Some simple arithmetic on such values is supported (they are treated much
4144/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004145static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004146 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004147 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004148 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004149}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004150
Richard Smithf48fdb02011-12-09 22:58:01 +00004151static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004152 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004153 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004154 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004155 if (!Val.isInt()) {
4156 // FIXME: It would be better to produce the diagnostic for casting
4157 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004158 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004159 return false;
4160 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004161 Result = Val.getInt();
4162 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004163}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004164
Richard Smithf48fdb02011-12-09 22:58:01 +00004165/// Check whether the given declaration can be directly converted to an integral
4166/// rvalue. If not, no diagnostic is produced; there are other things we can
4167/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004168bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004169 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004170 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004171 // Check for signedness/width mismatches between E type and ECD value.
4172 bool SameSign = (ECD->getInitVal().isSigned()
4173 == E->getType()->isSignedIntegerOrEnumerationType());
4174 bool SameWidth = (ECD->getInitVal().getBitWidth()
4175 == Info.Ctx.getIntWidth(E->getType()));
4176 if (SameSign && SameWidth)
4177 return Success(ECD->getInitVal(), E);
4178 else {
4179 // Get rid of mismatch (otherwise Success assertions will fail)
4180 // by computing a new value matching the type of E.
4181 llvm::APSInt Val = ECD->getInitVal();
4182 if (!SameSign)
4183 Val.setIsSigned(!ECD->getInitVal().isSigned());
4184 if (!SameWidth)
4185 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4186 return Success(Val, E);
4187 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004188 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004189 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004190}
4191
Chris Lattnera4d55d82008-10-06 06:40:35 +00004192/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4193/// as GCC.
4194static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4195 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004196 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004197 enum gcc_type_class {
4198 no_type_class = -1,
4199 void_type_class, integer_type_class, char_type_class,
4200 enumeral_type_class, boolean_type_class,
4201 pointer_type_class, reference_type_class, offset_type_class,
4202 real_type_class, complex_type_class,
4203 function_type_class, method_type_class,
4204 record_type_class, union_type_class,
4205 array_type_class, string_type_class,
4206 lang_type_class
4207 };
Mike Stump1eb44332009-09-09 15:08:12 +00004208
4209 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004210 // ideal, however it is what gcc does.
4211 if (E->getNumArgs() == 0)
4212 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004213
Chris Lattnera4d55d82008-10-06 06:40:35 +00004214 QualType ArgTy = E->getArg(0)->getType();
4215 if (ArgTy->isVoidType())
4216 return void_type_class;
4217 else if (ArgTy->isEnumeralType())
4218 return enumeral_type_class;
4219 else if (ArgTy->isBooleanType())
4220 return boolean_type_class;
4221 else if (ArgTy->isCharType())
4222 return string_type_class; // gcc doesn't appear to use char_type_class
4223 else if (ArgTy->isIntegerType())
4224 return integer_type_class;
4225 else if (ArgTy->isPointerType())
4226 return pointer_type_class;
4227 else if (ArgTy->isReferenceType())
4228 return reference_type_class;
4229 else if (ArgTy->isRealType())
4230 return real_type_class;
4231 else if (ArgTy->isComplexType())
4232 return complex_type_class;
4233 else if (ArgTy->isFunctionType())
4234 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004235 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004236 return record_type_class;
4237 else if (ArgTy->isUnionType())
4238 return union_type_class;
4239 else if (ArgTy->isArrayType())
4240 return array_type_class;
4241 else if (ArgTy->isUnionType())
4242 return union_type_class;
4243 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004244 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004245}
4246
Richard Smith80d4b552011-12-28 19:48:30 +00004247/// EvaluateBuiltinConstantPForLValue - Determine the result of
4248/// __builtin_constant_p when applied to the given lvalue.
4249///
4250/// An lvalue is only "constant" if it is a pointer or reference to the first
4251/// character of a string literal.
4252template<typename LValue>
4253static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004254 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004255 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4256}
4257
4258/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4259/// GCC as we can manage.
4260static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4261 QualType ArgType = Arg->getType();
4262
4263 // __builtin_constant_p always has one operand. The rules which gcc follows
4264 // are not precisely documented, but are as follows:
4265 //
4266 // - If the operand is of integral, floating, complex or enumeration type,
4267 // and can be folded to a known value of that type, it returns 1.
4268 // - If the operand and can be folded to a pointer to the first character
4269 // of a string literal (or such a pointer cast to an integral type), it
4270 // returns 1.
4271 //
4272 // Otherwise, it returns 0.
4273 //
4274 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4275 // its support for this does not currently work.
4276 if (ArgType->isIntegralOrEnumerationType()) {
4277 Expr::EvalResult Result;
4278 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4279 return false;
4280
4281 APValue &V = Result.Val;
4282 if (V.getKind() == APValue::Int)
4283 return true;
4284
4285 return EvaluateBuiltinConstantPForLValue(V);
4286 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4287 return Arg->isEvaluatable(Ctx);
4288 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4289 LValue LV;
4290 Expr::EvalStatus Status;
4291 EvalInfo Info(Ctx, Status);
4292 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4293 : EvaluatePointer(Arg, LV, Info)) &&
4294 !Status.HasSideEffects)
4295 return EvaluateBuiltinConstantPForLValue(LV);
4296 }
4297
4298 // Anything else isn't considered to be sufficiently constant.
4299 return false;
4300}
4301
John McCall42c8f872010-05-10 23:27:23 +00004302/// Retrieves the "underlying object type" of the given expression,
4303/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004304QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4305 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4306 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004307 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004308 } else if (const Expr *E = B.get<const Expr*>()) {
4309 if (isa<CompoundLiteralExpr>(E))
4310 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004311 }
4312
4313 return QualType();
4314}
4315
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004316bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004317 LValue Base;
Richard Smithc6794852012-05-23 04:13:20 +00004318
4319 {
4320 // The operand of __builtin_object_size is never evaluated for side-effects.
4321 // If there are any, but we can determine the pointed-to object anyway, then
4322 // ignore the side-effects.
4323 SpeculativeEvaluationRAII SpeculativeEval(Info);
4324 if (!EvaluatePointer(E->getArg(0), Base, Info))
4325 return false;
4326 }
John McCall42c8f872010-05-10 23:27:23 +00004327
4328 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004329 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004330
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004331 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004332 if (T.isNull() ||
4333 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004334 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004335 T->isVariablyModifiedType() ||
4336 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004337 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004338
4339 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4340 CharUnits Offset = Base.getLValueOffset();
4341
4342 if (!Offset.isNegative() && Offset <= Size)
4343 Size -= Offset;
4344 else
4345 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004346 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004347}
4348
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004349bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith2c39d712012-04-13 00:45:38 +00004350 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004351 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004352 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004353
4354 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004355 if (TryEvaluateBuiltinObjectSize(E))
4356 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004357
Eric Christopherb2aaf512010-01-19 22:58:35 +00004358 // If evaluating the argument has side-effects we can't determine
Richard Smithc6794852012-05-23 04:13:20 +00004359 // the size of the object and lower it to unknown now. CodeGen relies on
4360 // us to handle all cases where the expression has side-effects.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004361 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004362 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004363 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004364 return Success(0, E);
4365 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004366
Richard Smithc6794852012-05-23 04:13:20 +00004367 // Expression had no side effects, but we couldn't statically determine the
4368 // size of the referenced object.
Richard Smithf48fdb02011-12-09 22:58:01 +00004369 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004370 }
4371
Chris Lattner019f4e82008-10-06 05:28:25 +00004372 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004373 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004374
Richard Smith80d4b552011-12-28 19:48:30 +00004375 case Builtin::BI__builtin_constant_p:
4376 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004377
Chris Lattner21fb98e2009-09-23 06:06:36 +00004378 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004379 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004380 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004381 return Success(Operand, E);
4382 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004383
4384 case Builtin::BI__builtin_expect:
4385 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004386
Douglas Gregor5726d402010-09-10 06:27:15 +00004387 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004388 // A call to strlen is not a constant expression.
4389 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004390 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004391 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4392 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004393 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004394 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004395 case Builtin::BI__builtin_strlen:
4396 // As an extension, we support strlen() and __builtin_strlen() as constant
4397 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004398 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004399 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4400 // The string literal may have embedded null characters. Find the first
4401 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004402 StringRef Str = S->getString();
4403 StringRef::size_type Pos = Str.find(0);
4404 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004405 Str = Str.substr(0, Pos);
4406
4407 return Success(Str.size(), E);
4408 }
4409
Richard Smithf48fdb02011-12-09 22:58:01 +00004410 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004411
Richard Smith2c39d712012-04-13 00:45:38 +00004412 case Builtin::BI__atomic_always_lock_free:
Richard Smithfafbf062012-04-11 17:55:32 +00004413 case Builtin::BI__atomic_is_lock_free:
4414 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedman454b57a2011-10-17 21:44:23 +00004415 APSInt SizeVal;
4416 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4417 return false;
4418
4419 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4420 // of two less than the maximum inline atomic width, we know it is
4421 // lock-free. If the size isn't a power of two, or greater than the
4422 // maximum alignment where we promote atomics, we know it is not lock-free
4423 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4424 // the answer can only be determined at runtime; for example, 16-byte
4425 // atomics have lock-free implementations on some, but not all,
4426 // x86-64 processors.
4427
4428 // Check power-of-two.
4429 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith2c39d712012-04-13 00:45:38 +00004430 if (Size.isPowerOfTwo()) {
4431 // Check against inlining width.
4432 unsigned InlineWidthBits =
4433 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4434 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4435 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4436 Size == CharUnits::One() ||
4437 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4438 Expr::NPC_NeverValueDependent))
4439 // OK, we will inline appropriately-aligned operations of this size,
4440 // and _Atomic(T) is appropriately-aligned.
4441 return Success(1, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004442
Richard Smith2c39d712012-04-13 00:45:38 +00004443 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4444 castAs<PointerType>()->getPointeeType();
4445 if (!PointeeType->isIncompleteType() &&
4446 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4447 // OK, we will inline operations on this object.
4448 return Success(1, E);
4449 }
4450 }
4451 }
Eli Friedman454b57a2011-10-17 21:44:23 +00004452
Richard Smith2c39d712012-04-13 00:45:38 +00004453 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4454 Success(0, E) : Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004455 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004456 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004457}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004458
Richard Smith625b8072011-10-31 01:37:14 +00004459static bool HasSameBase(const LValue &A, const LValue &B) {
4460 if (!A.getLValueBase())
4461 return !B.getLValueBase();
4462 if (!B.getLValueBase())
4463 return false;
4464
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004465 if (A.getLValueBase().getOpaqueValue() !=
4466 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004467 const Decl *ADecl = GetLValueBaseDecl(A);
4468 if (!ADecl)
4469 return false;
4470 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004471 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004472 return false;
4473 }
4474
4475 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004476 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004477}
4478
Richard Smith7b48a292012-02-01 05:53:12 +00004479/// Perform the given integer operation, which is known to need at most BitWidth
4480/// bits, and check for overflow in the original type (if that type was not an
4481/// unsigned type).
4482template<typename Operation>
4483static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4484 const APSInt &LHS, const APSInt &RHS,
4485 unsigned BitWidth, Operation Op) {
4486 if (LHS.isUnsigned())
4487 return Op(LHS, RHS);
4488
4489 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4490 APSInt Result = Value.trunc(LHS.getBitWidth());
4491 if (Result.extend(BitWidth) != Value)
4492 HandleOverflow(Info, E, Value, E->getType());
4493 return Result;
4494}
4495
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004496namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00004497
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004498/// \brief Data recursive integer evaluator of certain binary operators.
4499///
4500/// We use a data recursive algorithm for binary operators so that we are able
4501/// to handle extreme cases of chained binary operators without causing stack
4502/// overflow.
4503class DataRecursiveIntBinOpEvaluator {
4504 struct EvalResult {
4505 APValue Val;
4506 bool Failed;
4507
4508 EvalResult() : Failed(false) { }
4509
4510 void swap(EvalResult &RHS) {
4511 Val.swap(RHS.Val);
4512 Failed = RHS.Failed;
4513 RHS.Failed = false;
4514 }
4515 };
4516
4517 struct Job {
4518 const Expr *E;
4519 EvalResult LHSResult; // meaningful only for binary operator expression.
4520 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4521
4522 Job() : StoredInfo(0) { }
4523 void startSpeculativeEval(EvalInfo &Info) {
4524 OldEvalStatus = Info.EvalStatus;
4525 Info.EvalStatus.Diag = 0;
4526 StoredInfo = &Info;
4527 }
4528 ~Job() {
4529 if (StoredInfo) {
4530 StoredInfo->EvalStatus = OldEvalStatus;
4531 }
4532 }
4533 private:
4534 EvalInfo *StoredInfo; // non-null if status changed.
4535 Expr::EvalStatus OldEvalStatus;
4536 };
4537
4538 SmallVector<Job, 16> Queue;
4539
4540 IntExprEvaluator &IntEval;
4541 EvalInfo &Info;
4542 APValue &FinalResult;
4543
4544public:
4545 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4546 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4547
4548 /// \brief True if \param E is a binary operator that we are going to handle
4549 /// data recursively.
4550 /// We handle binary operators that are comma, logical, or that have operands
4551 /// with integral or enumeration type.
4552 static bool shouldEnqueue(const BinaryOperator *E) {
4553 return E->getOpcode() == BO_Comma ||
4554 E->isLogicalOp() ||
4555 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4556 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00004557 }
4558
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004559 bool Traverse(const BinaryOperator *E) {
4560 enqueue(E);
4561 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00004562 while (!Queue.empty())
4563 process(PrevResult);
4564
4565 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004566
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004567 FinalResult.swap(PrevResult.Val);
4568 return true;
4569 }
4570
4571private:
4572 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4573 return IntEval.Success(Value, E, Result);
4574 }
4575 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4576 return IntEval.Success(Value, E, Result);
4577 }
4578 bool Error(const Expr *E) {
4579 return IntEval.Error(E);
4580 }
4581 bool Error(const Expr *E, diag::kind D) {
4582 return IntEval.Error(E, D);
4583 }
4584
4585 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4586 return Info.CCEDiag(E, D);
4587 }
4588
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004589 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4590 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004591 bool &SuppressRHSDiags);
4592
4593 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4594 const BinaryOperator *E, APValue &Result);
4595
4596 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4597 Result.Failed = !Evaluate(Result.Val, Info, E);
4598 if (Result.Failed)
4599 Result.Val = APValue();
4600 }
4601
Richard Trieub7783052012-03-21 23:30:30 +00004602 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004603
4604 void enqueue(const Expr *E) {
4605 E = E->IgnoreParens();
4606 Queue.resize(Queue.size()+1);
4607 Queue.back().E = E;
4608 Queue.back().Kind = Job::AnyExprKind;
4609 }
4610};
4611
4612}
4613
4614bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004615 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004616 bool &SuppressRHSDiags) {
4617 if (E->getOpcode() == BO_Comma) {
4618 // Ignore LHS but note if we could not evaluate it.
4619 if (LHSResult.Failed)
4620 Info.EvalStatus.HasSideEffects = true;
4621 return true;
4622 }
4623
4624 if (E->isLogicalOp()) {
4625 bool lhsResult;
4626 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004627 // We were able to evaluate the LHS, see if we can get away with not
4628 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004629 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004630 Success(lhsResult, E, LHSResult.Val);
4631 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004632 }
4633 } else {
4634 // Since we weren't able to evaluate the left hand side, it
4635 // must have had side effects.
4636 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004637
4638 // We can't evaluate the LHS; however, sometimes the result
4639 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4640 // Don't ignore RHS and suppress diagnostics from this arm.
4641 SuppressRHSDiags = true;
4642 }
4643
4644 return true;
4645 }
4646
4647 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4648 E->getRHS()->getType()->isIntegralOrEnumerationType());
4649
4650 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004651 return false; // Ignore RHS;
4652
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004653 return true;
4654}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004655
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004656bool DataRecursiveIntBinOpEvaluator::
4657 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4658 const BinaryOperator *E, APValue &Result) {
4659 if (E->getOpcode() == BO_Comma) {
4660 if (RHSResult.Failed)
4661 return false;
4662 Result = RHSResult.Val;
4663 return true;
4664 }
4665
4666 if (E->isLogicalOp()) {
4667 bool lhsResult, rhsResult;
4668 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4669 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4670
4671 if (LHSIsOK) {
4672 if (RHSIsOK) {
4673 if (E->getOpcode() == BO_LOr)
4674 return Success(lhsResult || rhsResult, E, Result);
4675 else
4676 return Success(lhsResult && rhsResult, E, Result);
4677 }
4678 } else {
4679 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004680 // We can't evaluate the LHS; however, sometimes the result
4681 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4682 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004683 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004684 }
4685 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004686
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004687 return false;
4688 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004689
4690 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4691 E->getRHS()->getType()->isIntegralOrEnumerationType());
4692
4693 if (LHSResult.Failed || RHSResult.Failed)
4694 return false;
4695
4696 const APValue &LHSVal = LHSResult.Val;
4697 const APValue &RHSVal = RHSResult.Val;
4698
4699 // Handle cases like (unsigned long)&a + 4.
4700 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4701 Result = LHSVal;
4702 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4703 RHSVal.getInt().getZExtValue());
4704 if (E->getOpcode() == BO_Add)
4705 Result.getLValueOffset() += AdditionalOffset;
4706 else
4707 Result.getLValueOffset() -= AdditionalOffset;
4708 return true;
4709 }
4710
4711 // Handle cases like 4 + (unsigned long)&a
4712 if (E->getOpcode() == BO_Add &&
4713 RHSVal.isLValue() && LHSVal.isInt()) {
4714 Result = RHSVal;
4715 Result.getLValueOffset() += CharUnits::fromQuantity(
4716 LHSVal.getInt().getZExtValue());
4717 return true;
4718 }
4719
4720 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4721 // Handle (intptr_t)&&A - (intptr_t)&&B.
4722 if (!LHSVal.getLValueOffset().isZero() ||
4723 !RHSVal.getLValueOffset().isZero())
4724 return false;
4725 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4726 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4727 if (!LHSExpr || !RHSExpr)
4728 return false;
4729 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4730 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4731 if (!LHSAddrExpr || !RHSAddrExpr)
4732 return false;
4733 // Make sure both labels come from the same function.
4734 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4735 RHSAddrExpr->getLabel()->getDeclContext())
4736 return false;
4737 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4738 return true;
4739 }
4740
4741 // All the following cases expect both operands to be an integer
4742 if (!LHSVal.isInt() || !RHSVal.isInt())
4743 return Error(E);
4744
4745 const APSInt &LHS = LHSVal.getInt();
4746 APSInt RHS = RHSVal.getInt();
4747
4748 switch (E->getOpcode()) {
4749 default:
4750 return Error(E);
4751 case BO_Mul:
4752 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4753 LHS.getBitWidth() * 2,
4754 std::multiplies<APSInt>()), E,
4755 Result);
4756 case BO_Add:
4757 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4758 LHS.getBitWidth() + 1,
4759 std::plus<APSInt>()), E, Result);
4760 case BO_Sub:
4761 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4762 LHS.getBitWidth() + 1,
4763 std::minus<APSInt>()), E, Result);
4764 case BO_And: return Success(LHS & RHS, E, Result);
4765 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4766 case BO_Or: return Success(LHS | RHS, E, Result);
4767 case BO_Div:
4768 case BO_Rem:
4769 if (RHS == 0)
4770 return Error(E, diag::note_expr_divide_by_zero);
4771 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4772 // not actually undefined behavior in C++11 due to a language defect.
4773 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4774 LHS.isSigned() && LHS.isMinSignedValue())
4775 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4776 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4777 Result);
4778 case BO_Shl: {
4779 // During constant-folding, a negative shift is an opposite shift. Such
4780 // a shift is not a constant expression.
4781 if (RHS.isSigned() && RHS.isNegative()) {
4782 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4783 RHS = -RHS;
4784 goto shift_right;
4785 }
4786
4787 shift_left:
4788 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4789 // the shifted type.
4790 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4791 if (SA != RHS) {
4792 CCEDiag(E, diag::note_constexpr_large_shift)
4793 << RHS << E->getType() << LHS.getBitWidth();
4794 } else if (LHS.isSigned()) {
4795 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4796 // operand, and must not overflow the corresponding unsigned type.
4797 if (LHS.isNegative())
4798 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4799 else if (LHS.countLeadingZeros() < SA)
4800 CCEDiag(E, diag::note_constexpr_lshift_discards);
4801 }
4802
4803 return Success(LHS << SA, E, Result);
4804 }
4805 case BO_Shr: {
4806 // During constant-folding, a negative shift is an opposite shift. Such a
4807 // shift is not a constant expression.
4808 if (RHS.isSigned() && RHS.isNegative()) {
4809 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4810 RHS = -RHS;
4811 goto shift_left;
4812 }
4813
4814 shift_right:
4815 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4816 // shifted type.
4817 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4818 if (SA != RHS)
4819 CCEDiag(E, diag::note_constexpr_large_shift)
4820 << RHS << E->getType() << LHS.getBitWidth();
4821
4822 return Success(LHS >> SA, E, Result);
4823 }
4824
4825 case BO_LT: return Success(LHS < RHS, E, Result);
4826 case BO_GT: return Success(LHS > RHS, E, Result);
4827 case BO_LE: return Success(LHS <= RHS, E, Result);
4828 case BO_GE: return Success(LHS >= RHS, E, Result);
4829 case BO_EQ: return Success(LHS == RHS, E, Result);
4830 case BO_NE: return Success(LHS != RHS, E, Result);
4831 }
4832}
4833
Richard Trieub7783052012-03-21 23:30:30 +00004834void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004835 Job &job = Queue.back();
4836
4837 switch (job.Kind) {
4838 case Job::AnyExprKind: {
4839 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4840 if (shouldEnqueue(Bop)) {
4841 job.Kind = Job::BinOpKind;
4842 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00004843 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004844 }
4845 }
4846
4847 EvaluateExpr(job.E, Result);
4848 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004849 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004850 }
4851
4852 case Job::BinOpKind: {
4853 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004854 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004855 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004856 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004857 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004858 }
4859 if (SuppressRHSDiags)
4860 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004861 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004862 job.Kind = Job::BinOpVisitedLHSKind;
4863 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00004864 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004865 }
4866
4867 case Job::BinOpVisitedLHSKind: {
4868 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4869 EvalResult RHS;
4870 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00004871 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004872 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004873 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004874 }
4875 }
4876
4877 llvm_unreachable("Invalid Job::Kind!");
4878}
4879
4880bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4881 if (E->isAssignmentOp())
4882 return Error(E);
4883
4884 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4885 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004886
Anders Carlsson286f85e2008-11-16 07:17:21 +00004887 QualType LHSTy = E->getLHS()->getType();
4888 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004889
4890 if (LHSTy->isAnyComplexType()) {
4891 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004892 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004893
Richard Smith745f5142012-01-27 01:14:48 +00004894 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4895 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004896 return false;
4897
Richard Smith745f5142012-01-27 01:14:48 +00004898 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004899 return false;
4900
4901 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004902 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004903 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004904 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004905 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4906
John McCall2de56d12010-08-25 11:45:40 +00004907 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004908 return Success((CR_r == APFloat::cmpEqual &&
4909 CR_i == APFloat::cmpEqual), E);
4910 else {
John McCall2de56d12010-08-25 11:45:40 +00004911 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004912 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004913 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004914 CR_r == APFloat::cmpLessThan ||
4915 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004916 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004917 CR_i == APFloat::cmpLessThan ||
4918 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004919 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004920 } else {
John McCall2de56d12010-08-25 11:45:40 +00004921 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004922 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4923 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4924 else {
John McCall2de56d12010-08-25 11:45:40 +00004925 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004926 "Invalid compex comparison.");
4927 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4928 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4929 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004930 }
4931 }
Mike Stump1eb44332009-09-09 15:08:12 +00004932
Anders Carlsson286f85e2008-11-16 07:17:21 +00004933 if (LHSTy->isRealFloatingType() &&
4934 RHSTy->isRealFloatingType()) {
4935 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004936
Richard Smith745f5142012-01-27 01:14:48 +00004937 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4938 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004939 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004940
Richard Smith745f5142012-01-27 01:14:48 +00004941 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004942 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004943
Anders Carlsson286f85e2008-11-16 07:17:21 +00004944 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004945
Anders Carlsson286f85e2008-11-16 07:17:21 +00004946 switch (E->getOpcode()) {
4947 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004948 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004949 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004950 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004951 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004952 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004953 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004954 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004955 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004956 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004957 E);
John McCall2de56d12010-08-25 11:45:40 +00004958 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004959 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004960 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004961 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004962 || CR == APFloat::cmpLessThan
4963 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004964 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004965 }
Mike Stump1eb44332009-09-09 15:08:12 +00004966
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004967 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004968 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004969 LValue LHSValue, RHSValue;
4970
4971 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4972 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004973 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004974
Richard Smith745f5142012-01-27 01:14:48 +00004975 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004976 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004977
Richard Smith625b8072011-10-31 01:37:14 +00004978 // Reject differing bases from the normal codepath; we special-case
4979 // comparisons to null.
4980 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004981 if (E->getOpcode() == BO_Sub) {
4982 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004983 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4984 return false;
4985 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4986 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4987 if (!LHSExpr || !RHSExpr)
4988 return false;
4989 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4990 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4991 if (!LHSAddrExpr || !RHSAddrExpr)
4992 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004993 // Make sure both labels come from the same function.
4994 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4995 RHSAddrExpr->getLabel()->getDeclContext())
4996 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004997 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004998 return true;
4999 }
Richard Smith9e36b532011-10-31 05:11:32 +00005000 // Inequalities and subtractions between unrelated pointers have
5001 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00005002 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00005003 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00005004 // A constant address may compare equal to the address of a symbol.
5005 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00005006 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00005007 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5008 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00005009 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00005010 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00005011 // distinct addresses. In clang, the result of such a comparison is
5012 // unspecified, so it is not a constant expression. However, we do know
5013 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00005014 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5015 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00005016 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00005017 // We can't tell whether weak symbols will end up pointing to the same
5018 // object.
5019 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00005020 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00005021 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00005022 // (Note that clang defaults to -fmerge-all-constants, which can
5023 // lead to inconsistent results for comparisons involving the address
5024 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00005025 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00005026 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005027
Richard Smith15efc4d2012-02-01 08:10:20 +00005028 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5029 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5030
Richard Smithf15fda02012-02-02 01:16:57 +00005031 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5032 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5033
John McCall2de56d12010-08-25 11:45:40 +00005034 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00005035 // C++11 [expr.add]p6:
5036 // Unless both pointers point to elements of the same array object, or
5037 // one past the last element of the array object, the behavior is
5038 // undefined.
5039 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5040 !AreElementsOfSameArray(getType(LHSValue.Base),
5041 LHSDesignator, RHSDesignator))
5042 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5043
Chris Lattner4992bdd2010-04-20 17:13:14 +00005044 QualType Type = E->getLHS()->getType();
5045 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00005046
Richard Smith180f4792011-11-10 06:34:14 +00005047 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00005048 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00005049 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00005050
Richard Smith15efc4d2012-02-01 08:10:20 +00005051 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5052 // and produce incorrect results when it overflows. Such behavior
5053 // appears to be non-conforming, but is common, so perhaps we should
5054 // assume the standard intended for such cases to be undefined behavior
5055 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00005056
Richard Smith15efc4d2012-02-01 08:10:20 +00005057 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5058 // overflow in the final conversion to ptrdiff_t.
5059 APSInt LHS(
5060 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5061 APSInt RHS(
5062 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5063 APSInt ElemSize(
5064 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5065 APSInt TrueResult = (LHS - RHS) / ElemSize;
5066 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5067
5068 if (Result.extend(65) != TrueResult)
5069 HandleOverflow(Info, E, TrueResult, E->getType());
5070 return Success(Result, E);
5071 }
Richard Smith82f28582012-01-31 06:41:30 +00005072
5073 // C++11 [expr.rel]p3:
5074 // Pointers to void (after pointer conversions) can be compared, with a
5075 // result defined as follows: If both pointers represent the same
5076 // address or are both the null pointer value, the result is true if the
5077 // operator is <= or >= and false otherwise; otherwise the result is
5078 // unspecified.
5079 // We interpret this as applying to pointers to *cv* void.
5080 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00005081 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00005082 CCEDiag(E, diag::note_constexpr_void_comparison);
5083
Richard Smithf15fda02012-02-02 01:16:57 +00005084 // C++11 [expr.rel]p2:
5085 // - If two pointers point to non-static data members of the same object,
5086 // or to subobjects or array elements fo such members, recursively, the
5087 // pointer to the later declared member compares greater provided the
5088 // two members have the same access control and provided their class is
5089 // not a union.
5090 // [...]
5091 // - Otherwise pointer comparisons are unspecified.
5092 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5093 E->isRelationalOp()) {
5094 bool WasArrayIndex;
5095 unsigned Mismatch =
5096 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5097 RHSDesignator, WasArrayIndex);
5098 // At the point where the designators diverge, the comparison has a
5099 // specified value if:
5100 // - we are comparing array indices
5101 // - we are comparing fields of a union, or fields with the same access
5102 // Otherwise, the result is unspecified and thus the comparison is not a
5103 // constant expression.
5104 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5105 Mismatch < RHSDesignator.Entries.size()) {
5106 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5107 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5108 if (!LF && !RF)
5109 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5110 else if (!LF)
5111 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5112 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5113 << RF->getParent() << RF;
5114 else if (!RF)
5115 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5116 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5117 << LF->getParent() << LF;
5118 else if (!LF->getParent()->isUnion() &&
5119 LF->getAccess() != RF->getAccess())
5120 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5121 << LF << LF->getAccess() << RF << RF->getAccess()
5122 << LF->getParent();
5123 }
5124 }
5125
Eli Friedmana3169882012-04-16 04:30:08 +00005126 // The comparison here must be unsigned, and performed with the same
5127 // width as the pointer.
Eli Friedmana3169882012-04-16 04:30:08 +00005128 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5129 uint64_t CompareLHS = LHSOffset.getQuantity();
5130 uint64_t CompareRHS = RHSOffset.getQuantity();
5131 assert(PtrSize <= 64 && "Unexpected pointer width");
5132 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5133 CompareLHS &= Mask;
5134 CompareRHS &= Mask;
5135
Eli Friedman28503762012-04-16 19:23:57 +00005136 // If there is a base and this is a relational operator, we can only
5137 // compare pointers within the object in question; otherwise, the result
5138 // depends on where the object is located in memory.
5139 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5140 QualType BaseTy = getType(LHSValue.Base);
5141 if (BaseTy->isIncompleteType())
5142 return Error(E);
5143 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5144 uint64_t OffsetLimit = Size.getQuantity();
5145 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5146 return Error(E);
5147 }
5148
Richard Smith625b8072011-10-31 01:37:14 +00005149 switch (E->getOpcode()) {
5150 default: llvm_unreachable("missing comparison operator");
Eli Friedmana3169882012-04-16 04:30:08 +00005151 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5152 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5153 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5154 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5155 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5156 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00005157 }
Anders Carlsson3068d112008-11-16 19:01:22 +00005158 }
5159 }
Richard Smithb02e4622012-02-01 01:42:44 +00005160
5161 if (LHSTy->isMemberPointerType()) {
5162 assert(E->isEqualityOp() && "unexpected member pointer operation");
5163 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5164
5165 MemberPtr LHSValue, RHSValue;
5166
5167 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5168 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5169 return false;
5170
5171 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5172 return false;
5173
5174 // C++11 [expr.eq]p2:
5175 // If both operands are null, they compare equal. Otherwise if only one is
5176 // null, they compare unequal.
5177 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5178 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5179 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5180 }
5181
5182 // Otherwise if either is a pointer to a virtual member function, the
5183 // result is unspecified.
5184 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5185 if (MD->isVirtual())
5186 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5187 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5188 if (MD->isVirtual())
5189 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5190
5191 // Otherwise they compare equal if and only if they would refer to the
5192 // same member of the same most derived object or the same subobject if
5193 // they were dereferenced with a hypothetical object of the associated
5194 // class type.
5195 bool Equal = LHSValue == RHSValue;
5196 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5197 }
5198
Richard Smith26f2cac2012-02-14 22:35:28 +00005199 if (LHSTy->isNullPtrType()) {
5200 assert(E->isComparisonOp() && "unexpected nullptr operation");
5201 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5202 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5203 // are compared, the result is true of the operator is <=, >= or ==, and
5204 // false otherwise.
5205 BinaryOperator::Opcode Opcode = E->getOpcode();
5206 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5207 }
5208
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005209 assert((!LHSTy->isIntegralOrEnumerationType() ||
5210 !RHSTy->isIntegralOrEnumerationType()) &&
5211 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5212 // We can't continue from here for non-integral types.
5213 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005214}
5215
Ken Dyck8b752f12010-01-27 17:10:57 +00005216CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005217 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5218 // result shall be the alignment of the referenced type."
5219 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5220 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005221
5222 // __alignof is defined to return the preferred alignment.
5223 return Info.Ctx.toCharUnitsFromBits(
5224 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005225}
5226
Ken Dyck8b752f12010-01-27 17:10:57 +00005227CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005228 E = E->IgnoreParens();
5229
5230 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005231 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005232 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005233 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5234 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005235
Chris Lattneraf707ab2009-01-24 21:53:27 +00005236 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005237 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5238 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005239
Chris Lattnere9feb472009-01-24 21:09:06 +00005240 return GetAlignOfType(E->getType());
5241}
5242
5243
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005244/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5245/// a result as the expression's type.
5246bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5247 const UnaryExprOrTypeTraitExpr *E) {
5248 switch(E->getKind()) {
5249 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005250 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005251 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005252 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005253 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005254 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005255
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005256 case UETT_VecStep: {
5257 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005258
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005259 if (Ty->isVectorType()) {
5260 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005261
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005262 // The vec_step built-in functions that take a 3-component
5263 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5264 if (n == 3)
5265 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005266
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005267 return Success(n, E);
5268 } else
5269 return Success(1, E);
5270 }
5271
5272 case UETT_SizeOf: {
5273 QualType SrcTy = E->getTypeOfArgument();
5274 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5275 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005276 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5277 SrcTy = Ref->getPointeeType();
5278
Richard Smith180f4792011-11-10 06:34:14 +00005279 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005280 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005281 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005282 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005283 }
5284 }
5285
5286 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005287}
5288
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005289bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005290 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005291 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005292 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005293 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005294 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005295 for (unsigned i = 0; i != n; ++i) {
5296 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5297 switch (ON.getKind()) {
5298 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005299 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005300 APSInt IdxResult;
5301 if (!EvaluateInteger(Idx, IdxResult, Info))
5302 return false;
5303 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5304 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005305 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005306 CurrentType = AT->getElementType();
5307 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5308 Result += IdxResult.getSExtValue() * ElementSize;
5309 break;
5310 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005311
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005312 case OffsetOfExpr::OffsetOfNode::Field: {
5313 FieldDecl *MemberDecl = ON.getField();
5314 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005315 if (!RT)
5316 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005317 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005318 if (RD->isInvalidDecl()) return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005319 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005320 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005321 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005322 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005323 CurrentType = MemberDecl->getType().getNonReferenceType();
5324 break;
5325 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005326
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005327 case OffsetOfExpr::OffsetOfNode::Identifier:
5328 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005329
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005330 case OffsetOfExpr::OffsetOfNode::Base: {
5331 CXXBaseSpecifier *BaseSpec = ON.getBase();
5332 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005333 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005334
5335 // Find the layout of the class whose base we are looking into.
5336 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005337 if (!RT)
5338 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005339 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005340 if (RD->isInvalidDecl()) return false;
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005341 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5342
5343 // Find the base class itself.
5344 CurrentType = BaseSpec->getType();
5345 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5346 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005347 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005348
5349 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005350 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005351 break;
5352 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005353 }
5354 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005355 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005356}
5357
Chris Lattnerb542afe2008-07-11 19:10:17 +00005358bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005359 switch (E->getOpcode()) {
5360 default:
5361 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5362 // See C99 6.6p3.
5363 return Error(E);
5364 case UO_Extension:
5365 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5366 // If so, we could clear the diagnostic ID.
5367 return Visit(E->getSubExpr());
5368 case UO_Plus:
5369 // The result is just the value.
5370 return Visit(E->getSubExpr());
5371 case UO_Minus: {
5372 if (!Visit(E->getSubExpr()))
5373 return false;
5374 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005375 const APSInt &Value = Result.getInt();
5376 if (Value.isSigned() && Value.isMinSignedValue())
5377 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5378 E->getType());
5379 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005380 }
5381 case UO_Not: {
5382 if (!Visit(E->getSubExpr()))
5383 return false;
5384 if (!Result.isInt()) return Error(E);
5385 return Success(~Result.getInt(), E);
5386 }
5387 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005388 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005389 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005390 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005391 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005392 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005393 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005394}
Mike Stump1eb44332009-09-09 15:08:12 +00005395
Chris Lattner732b2232008-07-12 01:15:53 +00005396/// HandleCast - This is used to evaluate implicit or explicit casts where the
5397/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005398bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5399 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005400 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005401 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005402
Eli Friedman46a52322011-03-25 00:43:55 +00005403 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005404 case CK_BaseToDerived:
5405 case CK_DerivedToBase:
5406 case CK_UncheckedDerivedToBase:
5407 case CK_Dynamic:
5408 case CK_ToUnion:
5409 case CK_ArrayToPointerDecay:
5410 case CK_FunctionToPointerDecay:
5411 case CK_NullToPointer:
5412 case CK_NullToMemberPointer:
5413 case CK_BaseToDerivedMemberPointer:
5414 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005415 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005416 case CK_ConstructorConversion:
5417 case CK_IntegralToPointer:
5418 case CK_ToVoid:
5419 case CK_VectorSplat:
5420 case CK_IntegralToFloating:
5421 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005422 case CK_CPointerToObjCPointerCast:
5423 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005424 case CK_AnyPointerToBlockPointerCast:
5425 case CK_ObjCObjectLValueCast:
5426 case CK_FloatingRealToComplex:
5427 case CK_FloatingComplexToReal:
5428 case CK_FloatingComplexCast:
5429 case CK_FloatingComplexToIntegralComplex:
5430 case CK_IntegralRealToComplex:
5431 case CK_IntegralComplexCast:
5432 case CK_IntegralComplexToFloatingComplex:
5433 llvm_unreachable("invalid cast kind for integral value");
5434
Eli Friedmane50c2972011-03-25 19:07:11 +00005435 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005436 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005437 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005438 case CK_ARCProduceObject:
5439 case CK_ARCConsumeObject:
5440 case CK_ARCReclaimReturnedObject:
5441 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005442 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005443 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005444
Richard Smith7d580a42012-01-17 21:17:26 +00005445 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005446 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005447 case CK_AtomicToNonAtomic:
5448 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005449 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005450 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005451
5452 case CK_MemberPointerToBoolean:
5453 case CK_PointerToBoolean:
5454 case CK_IntegralToBoolean:
5455 case CK_FloatingToBoolean:
5456 case CK_FloatingComplexToBoolean:
5457 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005458 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005459 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005460 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005461 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005462 }
5463
Eli Friedman46a52322011-03-25 00:43:55 +00005464 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005465 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005466 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005467
Eli Friedmanbe265702009-02-20 01:15:07 +00005468 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005469 // Allow casts of address-of-label differences if they are no-ops
5470 // or narrowing. (The narrowing case isn't actually guaranteed to
5471 // be constant-evaluatable except in some narrow cases which are hard
5472 // to detect here. We let it through on the assumption the user knows
5473 // what they are doing.)
5474 if (Result.isAddrLabelDiff())
5475 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005476 // Only allow casts of lvalues if they are lossless.
5477 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5478 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005479
Richard Smithf72fccf2012-01-30 22:27:01 +00005480 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5481 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005482 }
Mike Stump1eb44332009-09-09 15:08:12 +00005483
Eli Friedman46a52322011-03-25 00:43:55 +00005484 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005485 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5486
John McCallefdb83e2010-05-07 21:00:08 +00005487 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005488 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005489 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005490
Daniel Dunbardd211642009-02-19 22:24:01 +00005491 if (LV.getLValueBase()) {
5492 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005493 // FIXME: Allow a larger integer size than the pointer size, and allow
5494 // narrowing back down to pointer width in subsequent integral casts.
5495 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005496 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005497 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005498
Richard Smithb755a9d2011-11-16 07:18:12 +00005499 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005500 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005501 return true;
5502 }
5503
Ken Dycka7305832010-01-15 12:37:54 +00005504 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5505 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005506 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005507 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005508
Eli Friedman46a52322011-03-25 00:43:55 +00005509 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005510 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005511 if (!EvaluateComplex(SubExpr, C, Info))
5512 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005513 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005514 }
Eli Friedman2217c872009-02-22 11:46:18 +00005515
Eli Friedman46a52322011-03-25 00:43:55 +00005516 case CK_FloatingToIntegral: {
5517 APFloat F(0.0);
5518 if (!EvaluateFloat(SubExpr, F, Info))
5519 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005520
Richard Smithc1c5f272011-12-13 06:39:58 +00005521 APSInt Value;
5522 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5523 return false;
5524 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005525 }
5526 }
Mike Stump1eb44332009-09-09 15:08:12 +00005527
Eli Friedman46a52322011-03-25 00:43:55 +00005528 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005529}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005530
Eli Friedman722c7172009-02-28 03:59:05 +00005531bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5532 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005533 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005534 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5535 return false;
5536 if (!LV.isComplexInt())
5537 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005538 return Success(LV.getComplexIntReal(), E);
5539 }
5540
5541 return Visit(E->getSubExpr());
5542}
5543
Eli Friedman664a1042009-02-27 04:45:43 +00005544bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005545 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005546 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005547 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5548 return false;
5549 if (!LV.isComplexInt())
5550 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005551 return Success(LV.getComplexIntImag(), E);
5552 }
5553
Richard Smith8327fad2011-10-24 18:44:57 +00005554 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005555 return Success(0, E);
5556}
5557
Douglas Gregoree8aff02011-01-04 17:33:58 +00005558bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5559 return Success(E->getPackLength(), E);
5560}
5561
Sebastian Redl295995c2010-09-10 20:55:47 +00005562bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5563 return Success(E->getValue(), E);
5564}
5565
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005566//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005567// Float Evaluation
5568//===----------------------------------------------------------------------===//
5569
5570namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005571class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005572 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005573 APFloat &Result;
5574public:
5575 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005576 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005577
Richard Smith1aa0be82012-03-03 22:46:17 +00005578 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005579 Result = V.getFloat();
5580 return true;
5581 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005582
Richard Smith51201882011-12-30 21:15:51 +00005583 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005584 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5585 return true;
5586 }
5587
Chris Lattner019f4e82008-10-06 05:28:25 +00005588 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005589
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005590 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005591 bool VisitBinaryOperator(const BinaryOperator *E);
5592 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005593 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005594
John McCallabd3a852010-05-07 22:08:54 +00005595 bool VisitUnaryReal(const UnaryOperator *E);
5596 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005597
Richard Smith51201882011-12-30 21:15:51 +00005598 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005599};
5600} // end anonymous namespace
5601
5602static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005603 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005604 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005605}
5606
Jay Foad4ba2a172011-01-12 09:06:06 +00005607static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005608 QualType ResultTy,
5609 const Expr *Arg,
5610 bool SNaN,
5611 llvm::APFloat &Result) {
5612 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5613 if (!S) return false;
5614
5615 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5616
5617 llvm::APInt fill;
5618
5619 // Treat empty strings as if they were zero.
5620 if (S->getString().empty())
5621 fill = llvm::APInt(32, 0);
5622 else if (S->getString().getAsInteger(0, fill))
5623 return false;
5624
5625 if (SNaN)
5626 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5627 else
5628 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5629 return true;
5630}
5631
Chris Lattner019f4e82008-10-06 05:28:25 +00005632bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005633 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005634 default:
5635 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5636
Chris Lattner019f4e82008-10-06 05:28:25 +00005637 case Builtin::BI__builtin_huge_val:
5638 case Builtin::BI__builtin_huge_valf:
5639 case Builtin::BI__builtin_huge_vall:
5640 case Builtin::BI__builtin_inf:
5641 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005642 case Builtin::BI__builtin_infl: {
5643 const llvm::fltSemantics &Sem =
5644 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005645 Result = llvm::APFloat::getInf(Sem);
5646 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005647 }
Mike Stump1eb44332009-09-09 15:08:12 +00005648
John McCalldb7b72a2010-02-28 13:00:19 +00005649 case Builtin::BI__builtin_nans:
5650 case Builtin::BI__builtin_nansf:
5651 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005652 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5653 true, Result))
5654 return Error(E);
5655 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005656
Chris Lattner9e621712008-10-06 06:31:58 +00005657 case Builtin::BI__builtin_nan:
5658 case Builtin::BI__builtin_nanf:
5659 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005660 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005661 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005662 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5663 false, Result))
5664 return Error(E);
5665 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005666
5667 case Builtin::BI__builtin_fabs:
5668 case Builtin::BI__builtin_fabsf:
5669 case Builtin::BI__builtin_fabsl:
5670 if (!EvaluateFloat(E->getArg(0), Result, Info))
5671 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005672
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005673 if (Result.isNegative())
5674 Result.changeSign();
5675 return true;
5676
Mike Stump1eb44332009-09-09 15:08:12 +00005677 case Builtin::BI__builtin_copysign:
5678 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005679 case Builtin::BI__builtin_copysignl: {
5680 APFloat RHS(0.);
5681 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5682 !EvaluateFloat(E->getArg(1), RHS, Info))
5683 return false;
5684 Result.copySign(RHS);
5685 return true;
5686 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005687 }
5688}
5689
John McCallabd3a852010-05-07 22:08:54 +00005690bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005691 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5692 ComplexValue CV;
5693 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5694 return false;
5695 Result = CV.FloatReal;
5696 return true;
5697 }
5698
5699 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005700}
5701
5702bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005703 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5704 ComplexValue CV;
5705 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5706 return false;
5707 Result = CV.FloatImag;
5708 return true;
5709 }
5710
Richard Smith8327fad2011-10-24 18:44:57 +00005711 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005712 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5713 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005714 return true;
5715}
5716
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005717bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005718 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005719 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005720 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005721 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005722 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005723 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5724 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005725 Result.changeSign();
5726 return true;
5727 }
5728}
Chris Lattner019f4e82008-10-06 05:28:25 +00005729
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005730bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005731 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5732 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005733
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005734 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005735 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5736 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005737 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005738 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005739 return false;
5740
5741 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005742 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005743 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005744 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005745 break;
John McCall2de56d12010-08-25 11:45:40 +00005746 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005747 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005748 break;
John McCall2de56d12010-08-25 11:45:40 +00005749 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005750 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005751 break;
John McCall2de56d12010-08-25 11:45:40 +00005752 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005753 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005754 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005755 }
Richard Smith7b48a292012-02-01 05:53:12 +00005756
5757 if (Result.isInfinity() || Result.isNaN())
5758 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5759 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005760}
5761
5762bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5763 Result = E->getValue();
5764 return true;
5765}
5766
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005767bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5768 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005769
Eli Friedman2a523ee2011-03-25 00:54:52 +00005770 switch (E->getCastKind()) {
5771 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005772 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005773
5774 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005775 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005776 return EvaluateInteger(SubExpr, IntResult, Info) &&
5777 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5778 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005779 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005780
5781 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005782 if (!Visit(SubExpr))
5783 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005784 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5785 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005786 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005787
Eli Friedman2a523ee2011-03-25 00:54:52 +00005788 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005789 ComplexValue V;
5790 if (!EvaluateComplex(SubExpr, V, Info))
5791 return false;
5792 Result = V.getComplexFloatReal();
5793 return true;
5794 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005795 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005796}
5797
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005798//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005799// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005800//===----------------------------------------------------------------------===//
5801
5802namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005803class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005804 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005805 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005806
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005807public:
John McCallf4cf1a12010-05-07 17:22:02 +00005808 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005809 : ExprEvaluatorBaseTy(info), Result(Result) {}
5810
Richard Smith1aa0be82012-03-03 22:46:17 +00005811 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005812 Result.setFrom(V);
5813 return true;
5814 }
Mike Stump1eb44332009-09-09 15:08:12 +00005815
Eli Friedman7ead5c72012-01-10 04:58:17 +00005816 bool ZeroInitialization(const Expr *E);
5817
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005818 //===--------------------------------------------------------------------===//
5819 // Visitor Methods
5820 //===--------------------------------------------------------------------===//
5821
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005822 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005823 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005824 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005825 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005826 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005827};
5828} // end anonymous namespace
5829
John McCallf4cf1a12010-05-07 17:22:02 +00005830static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5831 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005832 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005833 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005834}
5835
Eli Friedman7ead5c72012-01-10 04:58:17 +00005836bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005837 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005838 if (ElemTy->isRealFloatingType()) {
5839 Result.makeComplexFloat();
5840 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5841 Result.FloatReal = Zero;
5842 Result.FloatImag = Zero;
5843 } else {
5844 Result.makeComplexInt();
5845 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5846 Result.IntReal = Zero;
5847 Result.IntImag = Zero;
5848 }
5849 return true;
5850}
5851
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005852bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5853 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005854
5855 if (SubExpr->getType()->isRealFloatingType()) {
5856 Result.makeComplexFloat();
5857 APFloat &Imag = Result.FloatImag;
5858 if (!EvaluateFloat(SubExpr, Imag, Info))
5859 return false;
5860
5861 Result.FloatReal = APFloat(Imag.getSemantics());
5862 return true;
5863 } else {
5864 assert(SubExpr->getType()->isIntegerType() &&
5865 "Unexpected imaginary literal.");
5866
5867 Result.makeComplexInt();
5868 APSInt &Imag = Result.IntImag;
5869 if (!EvaluateInteger(SubExpr, Imag, Info))
5870 return false;
5871
5872 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5873 return true;
5874 }
5875}
5876
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005877bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005878
John McCall8786da72010-12-14 17:51:41 +00005879 switch (E->getCastKind()) {
5880 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005881 case CK_BaseToDerived:
5882 case CK_DerivedToBase:
5883 case CK_UncheckedDerivedToBase:
5884 case CK_Dynamic:
5885 case CK_ToUnion:
5886 case CK_ArrayToPointerDecay:
5887 case CK_FunctionToPointerDecay:
5888 case CK_NullToPointer:
5889 case CK_NullToMemberPointer:
5890 case CK_BaseToDerivedMemberPointer:
5891 case CK_DerivedToBaseMemberPointer:
5892 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005893 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005894 case CK_ConstructorConversion:
5895 case CK_IntegralToPointer:
5896 case CK_PointerToIntegral:
5897 case CK_PointerToBoolean:
5898 case CK_ToVoid:
5899 case CK_VectorSplat:
5900 case CK_IntegralCast:
5901 case CK_IntegralToBoolean:
5902 case CK_IntegralToFloating:
5903 case CK_FloatingToIntegral:
5904 case CK_FloatingToBoolean:
5905 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005906 case CK_CPointerToObjCPointerCast:
5907 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005908 case CK_AnyPointerToBlockPointerCast:
5909 case CK_ObjCObjectLValueCast:
5910 case CK_FloatingComplexToReal:
5911 case CK_FloatingComplexToBoolean:
5912 case CK_IntegralComplexToReal:
5913 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005914 case CK_ARCProduceObject:
5915 case CK_ARCConsumeObject:
5916 case CK_ARCReclaimReturnedObject:
5917 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005918 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005919 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005920
John McCall8786da72010-12-14 17:51:41 +00005921 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005922 case CK_AtomicToNonAtomic:
5923 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005924 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005925 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005926
5927 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005928 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005929 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005930 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005931
5932 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005933 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005934 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005935 return false;
5936
John McCall8786da72010-12-14 17:51:41 +00005937 Result.makeComplexFloat();
5938 Result.FloatImag = APFloat(Real.getSemantics());
5939 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005940 }
5941
John McCall8786da72010-12-14 17:51:41 +00005942 case CK_FloatingComplexCast: {
5943 if (!Visit(E->getSubExpr()))
5944 return false;
5945
5946 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5947 QualType From
5948 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5949
Richard Smithc1c5f272011-12-13 06:39:58 +00005950 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5951 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005952 }
5953
5954 case CK_FloatingComplexToIntegralComplex: {
5955 if (!Visit(E->getSubExpr()))
5956 return false;
5957
5958 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5959 QualType From
5960 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5961 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005962 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5963 To, Result.IntReal) &&
5964 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5965 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005966 }
5967
5968 case CK_IntegralRealToComplex: {
5969 APSInt &Real = Result.IntReal;
5970 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5971 return false;
5972
5973 Result.makeComplexInt();
5974 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5975 return true;
5976 }
5977
5978 case CK_IntegralComplexCast: {
5979 if (!Visit(E->getSubExpr()))
5980 return false;
5981
5982 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5983 QualType From
5984 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5985
Richard Smithf72fccf2012-01-30 22:27:01 +00005986 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5987 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005988 return true;
5989 }
5990
5991 case CK_IntegralComplexToFloatingComplex: {
5992 if (!Visit(E->getSubExpr()))
5993 return false;
5994
5995 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5996 QualType From
5997 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5998 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005999 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
6000 To, Result.FloatReal) &&
6001 HandleIntToFloatCast(Info, E, From, Result.IntImag,
6002 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00006003 }
6004 }
6005
6006 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00006007}
6008
John McCallf4cf1a12010-05-07 17:22:02 +00006009bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006010 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00006011 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6012
Richard Smith745f5142012-01-27 01:14:48 +00006013 bool LHSOK = Visit(E->getLHS());
6014 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00006015 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006016
John McCallf4cf1a12010-05-07 17:22:02 +00006017 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00006018 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00006019 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006020
Daniel Dunbar3f279872009-01-29 01:32:56 +00006021 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6022 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006023 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00006024 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00006025 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006026 if (Result.isComplexFloat()) {
6027 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6028 APFloat::rmNearestTiesToEven);
6029 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6030 APFloat::rmNearestTiesToEven);
6031 } else {
6032 Result.getComplexIntReal() += RHS.getComplexIntReal();
6033 Result.getComplexIntImag() += RHS.getComplexIntImag();
6034 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00006035 break;
John McCall2de56d12010-08-25 11:45:40 +00006036 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006037 if (Result.isComplexFloat()) {
6038 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6039 APFloat::rmNearestTiesToEven);
6040 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6041 APFloat::rmNearestTiesToEven);
6042 } else {
6043 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6044 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6045 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00006046 break;
John McCall2de56d12010-08-25 11:45:40 +00006047 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00006048 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00006049 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00006050 APFloat &LHS_r = LHS.getComplexFloatReal();
6051 APFloat &LHS_i = LHS.getComplexFloatImag();
6052 APFloat &RHS_r = RHS.getComplexFloatReal();
6053 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00006054
Daniel Dunbar3f279872009-01-29 01:32:56 +00006055 APFloat Tmp = LHS_r;
6056 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6057 Result.getComplexFloatReal() = Tmp;
6058 Tmp = LHS_i;
6059 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6060 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6061
6062 Tmp = LHS_r;
6063 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6064 Result.getComplexFloatImag() = Tmp;
6065 Tmp = LHS_i;
6066 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6067 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6068 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00006069 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00006070 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006071 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6072 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00006073 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006074 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6075 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6076 }
6077 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006078 case BO_Div:
6079 if (Result.isComplexFloat()) {
6080 ComplexValue LHS = Result;
6081 APFloat &LHS_r = LHS.getComplexFloatReal();
6082 APFloat &LHS_i = LHS.getComplexFloatImag();
6083 APFloat &RHS_r = RHS.getComplexFloatReal();
6084 APFloat &RHS_i = RHS.getComplexFloatImag();
6085 APFloat &Res_r = Result.getComplexFloatReal();
6086 APFloat &Res_i = Result.getComplexFloatImag();
6087
6088 APFloat Den = RHS_r;
6089 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6090 APFloat Tmp = RHS_i;
6091 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6092 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6093
6094 Res_r = LHS_r;
6095 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6096 Tmp = LHS_i;
6097 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6098 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6099 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6100
6101 Res_i = LHS_i;
6102 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6103 Tmp = LHS_r;
6104 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6105 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6106 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6107 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00006108 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6109 return Error(E, diag::note_expr_divide_by_zero);
6110
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006111 ComplexValue LHS = Result;
6112 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6113 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6114 Result.getComplexIntReal() =
6115 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6116 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6117 Result.getComplexIntImag() =
6118 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6119 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6120 }
6121 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006122 }
6123
John McCallf4cf1a12010-05-07 17:22:02 +00006124 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006125}
6126
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006127bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6128 // Get the operand value into 'Result'.
6129 if (!Visit(E->getSubExpr()))
6130 return false;
6131
6132 switch (E->getOpcode()) {
6133 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00006134 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006135 case UO_Extension:
6136 return true;
6137 case UO_Plus:
6138 // The result is always just the subexpr.
6139 return true;
6140 case UO_Minus:
6141 if (Result.isComplexFloat()) {
6142 Result.getComplexFloatReal().changeSign();
6143 Result.getComplexFloatImag().changeSign();
6144 }
6145 else {
6146 Result.getComplexIntReal() = -Result.getComplexIntReal();
6147 Result.getComplexIntImag() = -Result.getComplexIntImag();
6148 }
6149 return true;
6150 case UO_Not:
6151 if (Result.isComplexFloat())
6152 Result.getComplexFloatImag().changeSign();
6153 else
6154 Result.getComplexIntImag() = -Result.getComplexIntImag();
6155 return true;
6156 }
6157}
6158
Eli Friedman7ead5c72012-01-10 04:58:17 +00006159bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6160 if (E->getNumInits() == 2) {
6161 if (E->getType()->isComplexType()) {
6162 Result.makeComplexFloat();
6163 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6164 return false;
6165 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6166 return false;
6167 } else {
6168 Result.makeComplexInt();
6169 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6170 return false;
6171 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6172 return false;
6173 }
6174 return true;
6175 }
6176 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6177}
6178
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00006179//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00006180// Void expression evaluation, primarily for a cast to void on the LHS of a
6181// comma operator
6182//===----------------------------------------------------------------------===//
6183
6184namespace {
6185class VoidExprEvaluator
6186 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6187public:
6188 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6189
Richard Smith1aa0be82012-03-03 22:46:17 +00006190 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00006191
6192 bool VisitCastExpr(const CastExpr *E) {
6193 switch (E->getCastKind()) {
6194 default:
6195 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6196 case CK_ToVoid:
6197 VisitIgnoredValue(E->getSubExpr());
6198 return true;
6199 }
6200 }
6201};
6202} // end anonymous namespace
6203
6204static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6205 assert(E->isRValue() && E->getType()->isVoidType());
6206 return VoidExprEvaluator(Info).Visit(E);
6207}
6208
6209//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006210// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006211//===----------------------------------------------------------------------===//
6212
Richard Smith1aa0be82012-03-03 22:46:17 +00006213static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006214 // In C, function designators are not lvalues, but we evaluate them as if they
6215 // are.
6216 if (E->isGLValue() || E->getType()->isFunctionType()) {
6217 LValue LV;
6218 if (!EvaluateLValue(E, LV, Info))
6219 return false;
6220 LV.moveInto(Result);
6221 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006222 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006223 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006224 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006225 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006226 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006227 } else if (E->getType()->hasPointerRepresentation()) {
6228 LValue LV;
6229 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006230 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006231 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006232 } else if (E->getType()->isRealFloatingType()) {
6233 llvm::APFloat F(0.0);
6234 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006235 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006236 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006237 } else if (E->getType()->isAnyComplexType()) {
6238 ComplexValue C;
6239 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006240 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006241 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006242 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006243 MemberPtr P;
6244 if (!EvaluateMemberPointer(E, P, Info))
6245 return false;
6246 P.moveInto(Result);
6247 return true;
Richard Smith51201882011-12-30 21:15:51 +00006248 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006249 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006250 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006251 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006252 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006253 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006254 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006255 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006256 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006257 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6258 return false;
6259 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006260 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00006261 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006262 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00006263 << E->getType();
6264 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00006265 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00006266 if (!EvaluateVoid(E, Info))
6267 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006268 } else if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006269 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006270 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006271 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006272 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006273 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006274 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006275
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006276 return true;
6277}
6278
Richard Smith83587db2012-02-15 02:18:13 +00006279/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6280/// cases, the in-place evaluation is essential, since later initializers for
6281/// an object can indirectly refer to subobjects which were initialized earlier.
6282static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6283 const Expr *E, CheckConstantExpressionKind CCEK,
6284 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006285 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006286 return false;
6287
6288 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006289 // Evaluate arrays and record types in-place, so that later initializers can
6290 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006291 if (E->getType()->isArrayType())
6292 return EvaluateArray(E, This, Result, Info);
6293 else if (E->getType()->isRecordType())
6294 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006295 }
6296
6297 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006298 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006299}
6300
Richard Smithf48fdb02011-12-09 22:58:01 +00006301/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6302/// lvalue-to-rvalue cast if it is an lvalue.
6303static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006304 if (!CheckLiteralType(Info, E))
6305 return false;
6306
Richard Smith1aa0be82012-03-03 22:46:17 +00006307 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006308 return false;
6309
6310 if (E->isGLValue()) {
6311 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006312 LV.setFrom(Info.Ctx, Result);
6313 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006314 return false;
6315 }
6316
Richard Smith1aa0be82012-03-03 22:46:17 +00006317 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006318 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006319}
Richard Smithc49bd112011-10-28 17:51:58 +00006320
Richard Smith51f47082011-10-29 00:50:52 +00006321/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006322/// any crazy technique (that has nothing to do with language standards) that
6323/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006324/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6325/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006326bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006327 // Fast-path evaluations of integer literals, since we sometimes see files
6328 // containing vast quantities of these.
6329 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6330 Result.Val = APValue(APSInt(L->getValue(),
6331 L->getType()->isUnsignedIntegerType()));
6332 return true;
6333 }
6334
Richard Smith2d6a5672012-01-14 04:30:29 +00006335 // FIXME: Evaluating values of large array and record types can cause
6336 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006337 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006338 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006339 return false;
6340
Richard Smithf48fdb02011-12-09 22:58:01 +00006341 EvalInfo Info(Ctx, Result);
6342 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006343}
6344
Jay Foad4ba2a172011-01-12 09:06:06 +00006345bool Expr::EvaluateAsBooleanCondition(bool &Result,
6346 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006347 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006348 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006349 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006350}
6351
Richard Smith80d4b552011-12-28 19:48:30 +00006352bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6353 SideEffectsKind AllowSideEffects) const {
6354 if (!getType()->isIntegralOrEnumerationType())
6355 return false;
6356
Richard Smithc49bd112011-10-28 17:51:58 +00006357 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006358 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6359 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006360 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006361
Richard Smithc49bd112011-10-28 17:51:58 +00006362 Result = ExprResult.Val.getInt();
6363 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006364}
6365
Jay Foad4ba2a172011-01-12 09:06:06 +00006366bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006367 EvalInfo Info(Ctx, Result);
6368
John McCallefdb83e2010-05-07 21:00:08 +00006369 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006370 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6371 !CheckLValueConstantExpression(Info, getExprLoc(),
6372 Ctx.getLValueReferenceType(getType()), LV))
6373 return false;
6374
Richard Smith1aa0be82012-03-03 22:46:17 +00006375 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006376 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006377}
6378
Richard Smith099e7f62011-12-19 06:19:21 +00006379bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6380 const VarDecl *VD,
6381 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006382 // FIXME: Evaluating initializers for large array and record types can cause
6383 // performance problems. Only do so in C++11 for now.
6384 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006385 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith2d6a5672012-01-14 04:30:29 +00006386 return false;
6387
Richard Smith099e7f62011-12-19 06:19:21 +00006388 Expr::EvalStatus EStatus;
6389 EStatus.Diag = &Notes;
6390
6391 EvalInfo InitInfo(Ctx, EStatus);
6392 InitInfo.setEvaluatingDecl(VD, Value);
6393
6394 LValue LVal;
6395 LVal.set(VD);
6396
Richard Smith51201882011-12-30 21:15:51 +00006397 // C++11 [basic.start.init]p2:
6398 // Variables with static storage duration or thread storage duration shall be
6399 // zero-initialized before any other initialization takes place.
6400 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006401 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006402 !VD->getType()->isReferenceType()) {
6403 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006404 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6405 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006406 return false;
6407 }
6408
Richard Smith83587db2012-02-15 02:18:13 +00006409 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6410 /*AllowNonLiteralTypes=*/true) ||
6411 EStatus.HasSideEffects)
6412 return false;
6413
6414 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6415 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006416}
6417
Richard Smith51f47082011-10-29 00:50:52 +00006418/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6419/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006420bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006421 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006422 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006423}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006424
Jay Foad4ba2a172011-01-12 09:06:06 +00006425bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006426 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006427}
6428
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006429APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006430 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006431 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006432 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006433 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006434 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006435
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006436 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006437}
John McCalld905f5a2010-05-07 05:32:02 +00006438
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006439 bool Expr::EvalResult::isGlobalLValue() const {
6440 assert(Val.isLValue());
6441 return IsGlobalLValue(Val.getLValueBase());
6442 }
6443
6444
John McCalld905f5a2010-05-07 05:32:02 +00006445/// isIntegerConstantExpr - this recursive routine will test if an expression is
6446/// an integer constant expression.
6447
6448/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6449/// comma, etc
6450///
6451/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6452/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6453/// cast+dereference.
6454
6455// CheckICE - This function does the fundamental ICE checking: the returned
6456// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6457// Note that to reduce code duplication, this helper does no evaluation
6458// itself; the caller checks whether the expression is evaluatable, and
6459// in the rare cases where CheckICE actually cares about the evaluated
6460// value, it calls into Evalute.
6461//
6462// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006463// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006464// 1: This expression is not an ICE, but if it isn't evaluated, it's
6465// a legal subexpression for an ICE. This return value is used to handle
6466// the comma operator in C99 mode.
6467// 2: This expression is not an ICE, and is not a legal subexpression for one.
6468
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006469namespace {
6470
John McCalld905f5a2010-05-07 05:32:02 +00006471struct ICEDiag {
6472 unsigned Val;
6473 SourceLocation Loc;
6474
6475 public:
6476 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6477 ICEDiag() : Val(0) {}
6478};
6479
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006480}
6481
6482static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006483
6484static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6485 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006486 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006487 !EVResult.Val.isInt()) {
6488 return ICEDiag(2, E->getLocStart());
6489 }
6490 return NoDiag();
6491}
6492
6493static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6494 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006495 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006496 return ICEDiag(2, E->getLocStart());
6497 }
6498
6499 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006500#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006501#define STMT(Node, Base) case Expr::Node##Class:
6502#define EXPR(Node, Base)
6503#include "clang/AST/StmtNodes.inc"
6504 case Expr::PredefinedExprClass:
6505 case Expr::FloatingLiteralClass:
6506 case Expr::ImaginaryLiteralClass:
6507 case Expr::StringLiteralClass:
6508 case Expr::ArraySubscriptExprClass:
6509 case Expr::MemberExprClass:
6510 case Expr::CompoundAssignOperatorClass:
6511 case Expr::CompoundLiteralExprClass:
6512 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006513 case Expr::DesignatedInitExprClass:
6514 case Expr::ImplicitValueInitExprClass:
6515 case Expr::ParenListExprClass:
6516 case Expr::VAArgExprClass:
6517 case Expr::AddrLabelExprClass:
6518 case Expr::StmtExprClass:
6519 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006520 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006521 case Expr::CXXDynamicCastExprClass:
6522 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006523 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006524 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006525 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006526 case Expr::CXXThisExprClass:
6527 case Expr::CXXThrowExprClass:
6528 case Expr::CXXNewExprClass:
6529 case Expr::CXXDeleteExprClass:
6530 case Expr::CXXPseudoDestructorExprClass:
6531 case Expr::UnresolvedLookupExprClass:
6532 case Expr::DependentScopeDeclRefExprClass:
6533 case Expr::CXXConstructExprClass:
6534 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006535 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006536 case Expr::CXXTemporaryObjectExprClass:
6537 case Expr::CXXUnresolvedConstructExprClass:
6538 case Expr::CXXDependentScopeMemberExprClass:
6539 case Expr::UnresolvedMemberExprClass:
6540 case Expr::ObjCStringLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +00006541 case Expr::ObjCBoxedExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006542 case Expr::ObjCArrayLiteralClass:
6543 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006544 case Expr::ObjCEncodeExprClass:
6545 case Expr::ObjCMessageExprClass:
6546 case Expr::ObjCSelectorExprClass:
6547 case Expr::ObjCProtocolExprClass:
6548 case Expr::ObjCIvarRefExprClass:
6549 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006550 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006551 case Expr::ObjCIsaExprClass:
6552 case Expr::ShuffleVectorExprClass:
6553 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006554 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006555 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006556 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006557 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006558 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006559 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006560 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006561 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006562 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006563 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006564 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006565 return ICEDiag(2, E->getLocStart());
6566
Douglas Gregoree8aff02011-01-04 17:33:58 +00006567 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006568 case Expr::GNUNullExprClass:
6569 // GCC considers the GNU __null value to be an integral constant expression.
6570 return NoDiag();
6571
John McCall91a57552011-07-15 05:09:51 +00006572 case Expr::SubstNonTypeTemplateParmExprClass:
6573 return
6574 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6575
John McCalld905f5a2010-05-07 05:32:02 +00006576 case Expr::ParenExprClass:
6577 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006578 case Expr::GenericSelectionExprClass:
6579 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006580 case Expr::IntegerLiteralClass:
6581 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006582 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006583 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006584 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006585 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006586 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006587 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006588 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006589 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006590 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006591 return NoDiag();
6592 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006593 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006594 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6595 // constant expressions, but they can never be ICEs because an ICE cannot
6596 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006597 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006598 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006599 return CheckEvalInICE(E, Ctx);
6600 return ICEDiag(2, E->getLocStart());
6601 }
Richard Smith359c89d2012-02-24 22:12:32 +00006602 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006603 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6604 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006605 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006606 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006607 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006608 // Parameter variables are never constants. Without this check,
6609 // getAnyInitializer() can find a default argument, which leads
6610 // to chaos.
6611 if (isa<ParmVarDecl>(D))
6612 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6613
6614 // C++ 7.1.5.1p2
6615 // A variable of non-volatile const-qualified integral or enumeration
6616 // type initialized by an ICE can be used in ICEs.
6617 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006618 if (!Dcl->getType()->isIntegralOrEnumerationType())
6619 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6620
Richard Smith099e7f62011-12-19 06:19:21 +00006621 const VarDecl *VD;
6622 // Look for a declaration of this variable that has an initializer, and
6623 // check whether it is an ICE.
6624 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6625 return NoDiag();
6626 else
6627 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006628 }
6629 }
6630 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006631 }
John McCalld905f5a2010-05-07 05:32:02 +00006632 case Expr::UnaryOperatorClass: {
6633 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6634 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006635 case UO_PostInc:
6636 case UO_PostDec:
6637 case UO_PreInc:
6638 case UO_PreDec:
6639 case UO_AddrOf:
6640 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006641 // C99 6.6/3 allows increment and decrement within unevaluated
6642 // subexpressions of constant expressions, but they can never be ICEs
6643 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006644 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006645 case UO_Extension:
6646 case UO_LNot:
6647 case UO_Plus:
6648 case UO_Minus:
6649 case UO_Not:
6650 case UO_Real:
6651 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006652 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006653 }
6654
6655 // OffsetOf falls through here.
6656 }
6657 case Expr::OffsetOfExprClass: {
6658 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006659 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006660 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006661 // compliance: we should warn earlier for offsetof expressions with
6662 // array subscripts that aren't ICEs, and if the array subscripts
6663 // are ICEs, the value of the offsetof must be an integer constant.
6664 return CheckEvalInICE(E, Ctx);
6665 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006666 case Expr::UnaryExprOrTypeTraitExprClass: {
6667 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6668 if ((Exp->getKind() == UETT_SizeOf) &&
6669 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006670 return ICEDiag(2, E->getLocStart());
6671 return NoDiag();
6672 }
6673 case Expr::BinaryOperatorClass: {
6674 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6675 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006676 case BO_PtrMemD:
6677 case BO_PtrMemI:
6678 case BO_Assign:
6679 case BO_MulAssign:
6680 case BO_DivAssign:
6681 case BO_RemAssign:
6682 case BO_AddAssign:
6683 case BO_SubAssign:
6684 case BO_ShlAssign:
6685 case BO_ShrAssign:
6686 case BO_AndAssign:
6687 case BO_XorAssign:
6688 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006689 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6690 // constant expressions, but they can never be ICEs because an ICE cannot
6691 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006692 return ICEDiag(2, E->getLocStart());
6693
John McCall2de56d12010-08-25 11:45:40 +00006694 case BO_Mul:
6695 case BO_Div:
6696 case BO_Rem:
6697 case BO_Add:
6698 case BO_Sub:
6699 case BO_Shl:
6700 case BO_Shr:
6701 case BO_LT:
6702 case BO_GT:
6703 case BO_LE:
6704 case BO_GE:
6705 case BO_EQ:
6706 case BO_NE:
6707 case BO_And:
6708 case BO_Xor:
6709 case BO_Or:
6710 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006711 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6712 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006713 if (Exp->getOpcode() == BO_Div ||
6714 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006715 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006716 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006717 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006718 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006719 if (REval == 0)
6720 return ICEDiag(1, E->getLocStart());
6721 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006722 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006723 if (LEval.isMinSignedValue())
6724 return ICEDiag(1, E->getLocStart());
6725 }
6726 }
6727 }
John McCall2de56d12010-08-25 11:45:40 +00006728 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006729 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006730 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6731 // if it isn't evaluated.
6732 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6733 return ICEDiag(1, E->getLocStart());
6734 } else {
6735 // In both C89 and C++, commas in ICEs are illegal.
6736 return ICEDiag(2, E->getLocStart());
6737 }
6738 }
6739 if (LHSResult.Val >= RHSResult.Val)
6740 return LHSResult;
6741 return RHSResult;
6742 }
John McCall2de56d12010-08-25 11:45:40 +00006743 case BO_LAnd:
6744 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006745 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6746 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6747 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6748 // Rare case where the RHS has a comma "side-effect"; we need
6749 // to actually check the condition to see whether the side
6750 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006751 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006752 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006753 return RHSResult;
6754 return NoDiag();
6755 }
6756
6757 if (LHSResult.Val >= RHSResult.Val)
6758 return LHSResult;
6759 return RHSResult;
6760 }
6761 }
6762 }
6763 case Expr::ImplicitCastExprClass:
6764 case Expr::CStyleCastExprClass:
6765 case Expr::CXXFunctionalCastExprClass:
6766 case Expr::CXXStaticCastExprClass:
6767 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006768 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006769 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006770 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006771 if (isa<ExplicitCastExpr>(E)) {
6772 if (const FloatingLiteral *FL
6773 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6774 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6775 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6776 APSInt IgnoredVal(DestWidth, !DestSigned);
6777 bool Ignored;
6778 // If the value does not fit in the destination type, the behavior is
6779 // undefined, so we are not required to treat it as a constant
6780 // expression.
6781 if (FL->getValue().convertToInteger(IgnoredVal,
6782 llvm::APFloat::rmTowardZero,
6783 &Ignored) & APFloat::opInvalidOp)
6784 return ICEDiag(2, E->getLocStart());
6785 return NoDiag();
6786 }
6787 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006788 switch (cast<CastExpr>(E)->getCastKind()) {
6789 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006790 case CK_AtomicToNonAtomic:
6791 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006792 case CK_NoOp:
6793 case CK_IntegralToBoolean:
6794 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006795 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006796 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006797 return ICEDiag(2, E->getLocStart());
6798 }
John McCalld905f5a2010-05-07 05:32:02 +00006799 }
John McCall56ca35d2011-02-17 10:25:35 +00006800 case Expr::BinaryConditionalOperatorClass: {
6801 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6802 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6803 if (CommonResult.Val == 2) return CommonResult;
6804 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6805 if (FalseResult.Val == 2) return FalseResult;
6806 if (CommonResult.Val == 1) return CommonResult;
6807 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006808 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006809 return FalseResult;
6810 }
John McCalld905f5a2010-05-07 05:32:02 +00006811 case Expr::ConditionalOperatorClass: {
6812 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6813 // If the condition (ignoring parens) is a __builtin_constant_p call,
6814 // then only the true side is actually considered in an integer constant
6815 // expression, and it is fully evaluated. This is an important GNU
6816 // extension. See GCC PR38377 for discussion.
6817 if (const CallExpr *CallCE
6818 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006819 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6820 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006821 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006822 if (CondResult.Val == 2)
6823 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006824
Richard Smithf48fdb02011-12-09 22:58:01 +00006825 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6826 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006827
John McCalld905f5a2010-05-07 05:32:02 +00006828 if (TrueResult.Val == 2)
6829 return TrueResult;
6830 if (FalseResult.Val == 2)
6831 return FalseResult;
6832 if (CondResult.Val == 1)
6833 return CondResult;
6834 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6835 return NoDiag();
6836 // Rare case where the diagnostics depend on which side is evaluated
6837 // Note that if we get here, CondResult is 0, and at least one of
6838 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006839 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006840 return FalseResult;
6841 }
6842 return TrueResult;
6843 }
6844 case Expr::CXXDefaultArgExprClass:
6845 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6846 case Expr::ChooseExprClass: {
6847 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6848 }
6849 }
6850
David Blaikie30263482012-01-20 21:50:17 +00006851 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006852}
6853
Richard Smithf48fdb02011-12-09 22:58:01 +00006854/// Evaluate an expression as a C++11 integral constant expression.
6855static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6856 const Expr *E,
6857 llvm::APSInt *Value,
6858 SourceLocation *Loc) {
6859 if (!E->getType()->isIntegralOrEnumerationType()) {
6860 if (Loc) *Loc = E->getExprLoc();
6861 return false;
6862 }
6863
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006864 APValue Result;
6865 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006866 return false;
6867
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006868 assert(Result.isInt() && "pointer cast to int is not an ICE");
6869 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006870 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006871}
6872
Richard Smithdd1f29b2011-12-12 09:28:41 +00006873bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006874 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006875 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6876
John McCalld905f5a2010-05-07 05:32:02 +00006877 ICEDiag d = CheckICE(this, Ctx);
6878 if (d.Val != 0) {
6879 if (Loc) *Loc = d.Loc;
6880 return false;
6881 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006882 return true;
6883}
6884
6885bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6886 SourceLocation *Loc, bool isEvaluated) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006887 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006888 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6889
6890 if (!isIntegerConstantExpr(Ctx, Loc))
6891 return false;
6892 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006893 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006894 return true;
6895}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006896
Richard Smith70488e22012-02-14 21:38:30 +00006897bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6898 return CheckICE(this, Ctx).Val == 0;
6899}
6900
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006901bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6902 SourceLocation *Loc) const {
6903 // We support this checking in C++98 mode in order to diagnose compatibility
6904 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006905 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006906
Richard Smith70488e22012-02-14 21:38:30 +00006907 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006908 Expr::EvalStatus Status;
6909 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6910 Status.Diag = &Diags;
6911 EvalInfo Info(Ctx, Status);
6912
6913 APValue Scratch;
6914 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6915
6916 if (!Diags.empty()) {
6917 IsConstExpr = false;
6918 if (Loc) *Loc = Diags[0].first;
6919 } else if (!IsConstExpr) {
6920 // FIXME: This shouldn't happen.
6921 if (Loc) *Loc = getExprLoc();
6922 }
6923
6924 return IsConstExpr;
6925}
Richard Smith745f5142012-01-27 01:14:48 +00006926
6927bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6928 llvm::SmallVectorImpl<
6929 PartialDiagnosticAt> &Diags) {
6930 // FIXME: It would be useful to check constexpr function templates, but at the
6931 // moment the constant expression evaluator cannot cope with the non-rigorous
6932 // ASTs which we build for dependent expressions.
6933 if (FD->isDependentContext())
6934 return true;
6935
6936 Expr::EvalStatus Status;
6937 Status.Diag = &Diags;
6938
6939 EvalInfo Info(FD->getASTContext(), Status);
6940 Info.CheckingPotentialConstantExpression = true;
6941
6942 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6943 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6944
6945 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6946 // is a temporary being used as the 'this' pointer.
6947 LValue This;
6948 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006949 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006950
Richard Smith745f5142012-01-27 01:14:48 +00006951 ArrayRef<const Expr*> Args;
6952
6953 SourceLocation Loc = FD->getLocation();
6954
Richard Smith1aa0be82012-03-03 22:46:17 +00006955 APValue Scratch;
6956 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006957 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006958 else
Richard Smith745f5142012-01-27 01:14:48 +00006959 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6960 Args, FD->getBody(), Info, Scratch);
6961
6962 return Diags.empty();
6963}