blob: b16ba8fb52ea094297e7c813ac36b0938be7d35f [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
Eli Friedmanf6172ae2012-06-25 21:21:08 +0000366 // Note that we intentionally use std::map here so that references
367 // to values are stable.
368 typedef std::map<const OpaqueValueExpr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000369 /// OpaqueValues - Values used as the common expression in a
370 /// BinaryConditionalOperator.
371 MapTy OpaqueValues;
372
373 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000374 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000375 CallStackFrame BottomFrame;
376
Richard Smith180f4792011-11-10 06:34:14 +0000377 /// EvaluatingDecl - This is the declaration whose initializer is being
378 /// evaluated, if any.
379 const VarDecl *EvaluatingDecl;
380
381 /// EvaluatingDeclValue - This is the value being constructed for the
382 /// declaration whose initializer is being evaluated, if any.
383 APValue *EvaluatingDeclValue;
384
Richard Smithc1c5f272011-12-13 06:39:58 +0000385 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
386 /// notes attached to it will also be stored, otherwise they will not be.
387 bool HasActiveDiagnostic;
388
Richard Smith745f5142012-01-27 01:14:48 +0000389 /// CheckingPotentialConstantExpression - Are we checking whether the
390 /// expression is a potential constant expression? If so, some diagnostics
391 /// are suppressed.
392 bool CheckingPotentialConstantExpression;
393
Richard Smithbd552ef2011-10-31 05:52:43 +0000394 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000395 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000396 CallStackDepth(0), NextCallIndex(1),
397 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000398 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Argyrios Kyrtzidis649dfbc2012-03-15 18:07:13 +0000399 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000400
Richard Smith1aa0be82012-03-03 22:46:17 +0000401 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
Richard Smithbd552ef2011-10-31 05:52:43 +0000402 MapTy::const_iterator i = OpaqueValues.find(e);
403 if (i == OpaqueValues.end()) return 0;
404 return &i->second;
405 }
406
Richard Smith180f4792011-11-10 06:34:14 +0000407 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
408 EvaluatingDecl = VD;
409 EvaluatingDeclValue = &Value;
410 }
411
David Blaikie4e4d0842012-03-11 07:00:24 +0000412 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000413
Richard Smithc1c5f272011-12-13 06:39:58 +0000414 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000415 // Don't perform any constexpr calls (other than the call we're checking)
416 // when checking a potential constant expression.
417 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
418 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000419 if (NextCallIndex == 0) {
420 // NextCallIndex has wrapped around.
421 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
422 return false;
423 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000424 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
425 return true;
426 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
427 << getLangOpts().ConstexprCallDepth;
428 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000429 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000430
Richard Smith83587db2012-02-15 02:18:13 +0000431 CallStackFrame *getCallFrame(unsigned CallIndex) {
432 assert(CallIndex && "no call index in getCallFrame");
433 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
434 // be null in this loop.
435 CallStackFrame *Frame = CurrentCall;
436 while (Frame->Index > CallIndex)
437 Frame = Frame->Caller;
438 return (Frame->Index == CallIndex) ? Frame : 0;
439 }
440
Richard Smithc1c5f272011-12-13 06:39:58 +0000441 private:
442 /// Add a diagnostic to the diagnostics list.
443 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
444 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
445 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
446 return EvalStatus.Diag->back().second;
447 }
448
Richard Smith08d6e032011-12-16 19:06:07 +0000449 /// Add notes containing a call stack to the current point of evaluation.
450 void addCallStack(unsigned Limit);
451
Richard Smithc1c5f272011-12-13 06:39:58 +0000452 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000453 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000454 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
455 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000456 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000457 // If we have a prior diagnostic, it will be noting that the expression
458 // isn't a constant expression. This diagnostic is more important.
459 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000460 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000461 unsigned CallStackNotes = CallStackDepth - 1;
462 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
463 if (Limit)
464 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000465 if (CheckingPotentialConstantExpression)
466 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000467
Richard Smithc1c5f272011-12-13 06:39:58 +0000468 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000469 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000470 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
471 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000472 if (!CheckingPotentialConstantExpression)
473 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000474 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000475 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000476 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000477 return OptionalDiagnostic();
478 }
479
Richard Smith5cfc7d82012-03-15 04:53:45 +0000480 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
481 = diag::note_invalid_subexpr_in_const_expr,
482 unsigned ExtraNotes = 0) {
483 if (EvalStatus.Diag)
484 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
485 HasActiveDiagnostic = false;
486 return OptionalDiagnostic();
487 }
488
Richard Smithdd1f29b2011-12-12 09:28:41 +0000489 /// Diagnose that the evaluation does not produce a C++11 core constant
490 /// expression.
Richard Smith5cfc7d82012-03-15 04:53:45 +0000491 template<typename LocArg>
492 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000493 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000494 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000495 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000496 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
497 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000498 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000499 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000500 return Diag(Loc, DiagId, ExtraNotes);
501 }
502
503 /// Add a note to a prior diagnostic.
504 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
505 if (!HasActiveDiagnostic)
506 return OptionalDiagnostic();
507 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000508 }
Richard Smith099e7f62011-12-19 06:19:21 +0000509
510 /// Add a stack of notes to a prior diagnostic.
511 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
512 if (HasActiveDiagnostic) {
513 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
514 Diags.begin(), Diags.end());
515 }
516 }
Richard Smith745f5142012-01-27 01:14:48 +0000517
518 /// Should we continue evaluation as much as possible after encountering a
519 /// construct which can't be folded?
520 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000521 return CheckingPotentialConstantExpression &&
522 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000523 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000524 };
Richard Smithf15fda02012-02-02 01:16:57 +0000525
526 /// Object used to treat all foldable expressions as constant expressions.
527 struct FoldConstant {
528 bool Enabled;
529
530 explicit FoldConstant(EvalInfo &Info)
531 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
532 !Info.EvalStatus.HasSideEffects) {
533 }
534 // Treat the value we've computed since this object was created as constant.
535 void Fold(EvalInfo &Info) {
536 if (Enabled && !Info.EvalStatus.Diag->empty() &&
537 !Info.EvalStatus.HasSideEffects)
538 Info.EvalStatus.Diag->clear();
539 }
540 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000541
542 /// RAII object used to suppress diagnostics and side-effects from a
543 /// speculative evaluation.
544 class SpeculativeEvaluationRAII {
545 EvalInfo &Info;
546 Expr::EvalStatus Old;
547
548 public:
549 SpeculativeEvaluationRAII(EvalInfo &Info,
550 llvm::SmallVectorImpl<PartialDiagnosticAt>
551 *NewDiag = 0)
552 : Info(Info), Old(Info.EvalStatus) {
553 Info.EvalStatus.Diag = NewDiag;
554 }
555 ~SpeculativeEvaluationRAII() {
556 Info.EvalStatus = Old;
557 }
558 };
Richard Smith08d6e032011-12-16 19:06:07 +0000559}
Richard Smithbd552ef2011-10-31 05:52:43 +0000560
Richard Smithb4e85ed2012-01-06 16:39:00 +0000561bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
562 CheckSubobjectKind CSK) {
563 if (Invalid)
564 return false;
565 if (isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000566 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000567 << CSK;
568 setInvalid();
569 return false;
570 }
571 return true;
572}
573
574void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
575 const Expr *E, uint64_t N) {
576 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000577 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000578 << static_cast<int>(N) << /*array*/ 0
579 << static_cast<unsigned>(MostDerivedArraySize);
580 else
Richard Smith5cfc7d82012-03-15 04:53:45 +0000581 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000582 << static_cast<int>(N) << /*non-array*/ 1;
583 setInvalid();
584}
585
Richard Smith08d6e032011-12-16 19:06:07 +0000586CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
587 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000588 const APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000589 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000590 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000591 Info.CurrentCall = this;
592 ++Info.CallStackDepth;
593}
594
595CallStackFrame::~CallStackFrame() {
596 assert(Info.CurrentCall == this && "calls retired out of order");
597 --Info.CallStackDepth;
598 Info.CurrentCall = Caller;
599}
600
601/// Produce a string describing the given constexpr call.
602static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
603 unsigned ArgIndex = 0;
604 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000605 !isa<CXXConstructorDecl>(Frame->Callee) &&
606 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000607
608 if (!IsMemberCall)
609 Out << *Frame->Callee << '(';
610
611 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
612 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000613 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000614 Out << ", ";
615
616 const ParmVarDecl *Param = *I;
Richard Smith1aa0be82012-03-03 22:46:17 +0000617 const APValue &Arg = Frame->Arguments[ArgIndex];
618 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smith08d6e032011-12-16 19:06:07 +0000619
620 if (ArgIndex == 0 && IsMemberCall)
621 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000622 }
623
Richard Smith08d6e032011-12-16 19:06:07 +0000624 Out << ')';
625}
626
627void EvalInfo::addCallStack(unsigned Limit) {
628 // Determine which calls to skip, if any.
629 unsigned ActiveCalls = CallStackDepth - 1;
630 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
631 if (Limit && Limit < ActiveCalls) {
632 SkipStart = Limit / 2 + Limit % 2;
633 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000634 }
635
Richard Smith08d6e032011-12-16 19:06:07 +0000636 // Walk the call stack and add the diagnostics.
637 unsigned CallIdx = 0;
638 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
639 Frame = Frame->Caller, ++CallIdx) {
640 // Skip this call?
641 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
642 if (CallIdx == SkipStart) {
643 // Note that we're skipping calls.
644 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
645 << unsigned(ActiveCalls - Limit);
646 }
647 continue;
648 }
649
650 llvm::SmallVector<char, 128> Buffer;
651 llvm::raw_svector_ostream Out(Buffer);
652 describeCall(Frame, Out);
653 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
654 }
655}
656
657namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000658 struct ComplexValue {
659 private:
660 bool IsInt;
661
662 public:
663 APSInt IntReal, IntImag;
664 APFloat FloatReal, FloatImag;
665
666 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
667
668 void makeComplexFloat() { IsInt = false; }
669 bool isComplexFloat() const { return !IsInt; }
670 APFloat &getComplexFloatReal() { return FloatReal; }
671 APFloat &getComplexFloatImag() { return FloatImag; }
672
673 void makeComplexInt() { IsInt = true; }
674 bool isComplexInt() const { return IsInt; }
675 APSInt &getComplexIntReal() { return IntReal; }
676 APSInt &getComplexIntImag() { return IntImag; }
677
Richard Smith1aa0be82012-03-03 22:46:17 +0000678 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000679 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000680 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000681 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000682 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000683 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000684 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000685 assert(v.isComplexFloat() || v.isComplexInt());
686 if (v.isComplexFloat()) {
687 makeComplexFloat();
688 FloatReal = v.getComplexFloatReal();
689 FloatImag = v.getComplexFloatImag();
690 } else {
691 makeComplexInt();
692 IntReal = v.getComplexIntReal();
693 IntImag = v.getComplexIntImag();
694 }
695 }
John McCallf4cf1a12010-05-07 17:22:02 +0000696 };
John McCallefdb83e2010-05-07 21:00:08 +0000697
698 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000699 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000700 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000701 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000702 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000703
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000704 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000705 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000706 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000707 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000708 SubobjectDesignator &getLValueDesignator() { return Designator; }
709 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000710
Richard Smith1aa0be82012-03-03 22:46:17 +0000711 void moveInto(APValue &V) const {
712 if (Designator.Invalid)
713 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
714 else
715 V = APValue(Base, Offset, Designator.Entries,
716 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000717 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000718 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000719 assert(V.isLValue());
720 Base = V.getLValueBase();
721 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000722 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000723 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000724 }
725
Richard Smith83587db2012-02-15 02:18:13 +0000726 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000727 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000728 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000729 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000730 Designator = SubobjectDesignator(getType(B));
731 }
732
733 // Check that this LValue is not based on a null pointer. If it is, produce
734 // a diagnostic and mark the designator as invalid.
735 bool checkNullPointer(EvalInfo &Info, const Expr *E,
736 CheckSubobjectKind CSK) {
737 if (Designator.Invalid)
738 return false;
739 if (!Base) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000740 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000741 << CSK;
742 Designator.setInvalid();
743 return false;
744 }
745 return true;
746 }
747
748 // Check this LValue refers to an object. If not, set the designator to be
749 // invalid and emit a diagnostic.
750 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000751 // Outside C++11, do not build a designator referring to a subobject of
752 // any object: we won't use such a designator for anything.
753 if (!Info.getLangOpts().CPlusPlus0x)
754 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000755 return checkNullPointer(Info, E, CSK) &&
756 Designator.checkSubobject(Info, E, CSK);
757 }
758
759 void addDecl(EvalInfo &Info, const Expr *E,
760 const Decl *D, bool Virtual = false) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000761 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
762 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000763 }
764 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000765 if (checkSubobject(Info, E, CSK_ArrayToPointer))
766 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000767 }
Richard Smith86024012012-02-18 22:04:06 +0000768 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000769 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
770 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000771 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000772 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000773 if (checkNullPointer(Info, E, CSK_ArrayIndex))
774 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000775 }
John McCallefdb83e2010-05-07 21:00:08 +0000776 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000777
778 struct MemberPtr {
779 MemberPtr() {}
780 explicit MemberPtr(const ValueDecl *Decl) :
781 DeclAndIsDerivedMember(Decl, false), Path() {}
782
783 /// The member or (direct or indirect) field referred to by this member
784 /// pointer, or 0 if this is a null member pointer.
785 const ValueDecl *getDecl() const {
786 return DeclAndIsDerivedMember.getPointer();
787 }
788 /// Is this actually a member of some type derived from the relevant class?
789 bool isDerivedMember() const {
790 return DeclAndIsDerivedMember.getInt();
791 }
792 /// Get the class which the declaration actually lives in.
793 const CXXRecordDecl *getContainingRecord() const {
794 return cast<CXXRecordDecl>(
795 DeclAndIsDerivedMember.getPointer()->getDeclContext());
796 }
797
Richard Smith1aa0be82012-03-03 22:46:17 +0000798 void moveInto(APValue &V) const {
799 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000800 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000801 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000802 assert(V.isMemberPointer());
803 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
804 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
805 Path.clear();
806 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
807 Path.insert(Path.end(), P.begin(), P.end());
808 }
809
810 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
811 /// whether the member is a member of some class derived from the class type
812 /// of the member pointer.
813 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
814 /// Path - The path of base/derived classes from the member declaration's
815 /// class (exclusive) to the class type of the member pointer (inclusive).
816 SmallVector<const CXXRecordDecl*, 4> Path;
817
818 /// Perform a cast towards the class of the Decl (either up or down the
819 /// hierarchy).
820 bool castBack(const CXXRecordDecl *Class) {
821 assert(!Path.empty());
822 const CXXRecordDecl *Expected;
823 if (Path.size() >= 2)
824 Expected = Path[Path.size() - 2];
825 else
826 Expected = getContainingRecord();
827 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
828 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
829 // if B does not contain the original member and is not a base or
830 // derived class of the class containing the original member, the result
831 // of the cast is undefined.
832 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
833 // (D::*). We consider that to be a language defect.
834 return false;
835 }
836 Path.pop_back();
837 return true;
838 }
839 /// Perform a base-to-derived member pointer cast.
840 bool castToDerived(const CXXRecordDecl *Derived) {
841 if (!getDecl())
842 return true;
843 if (!isDerivedMember()) {
844 Path.push_back(Derived);
845 return true;
846 }
847 if (!castBack(Derived))
848 return false;
849 if (Path.empty())
850 DeclAndIsDerivedMember.setInt(false);
851 return true;
852 }
853 /// Perform a derived-to-base member pointer cast.
854 bool castToBase(const CXXRecordDecl *Base) {
855 if (!getDecl())
856 return true;
857 if (Path.empty())
858 DeclAndIsDerivedMember.setInt(true);
859 if (isDerivedMember()) {
860 Path.push_back(Base);
861 return true;
862 }
863 return castBack(Base);
864 }
865 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000866
Richard Smithb02e4622012-02-01 01:42:44 +0000867 /// Compare two member pointers, which are assumed to be of the same type.
868 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
869 if (!LHS.getDecl() || !RHS.getDecl())
870 return !LHS.getDecl() && !RHS.getDecl();
871 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
872 return false;
873 return LHS.Path == RHS.Path;
874 }
875
Richard Smithc1c5f272011-12-13 06:39:58 +0000876 /// Kinds of constant expression checking, for diagnostics.
877 enum CheckConstantExpressionKind {
878 CCEK_Constant, ///< A normal constant.
879 CCEK_ReturnValue, ///< A constexpr function return value.
880 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
881 };
John McCallf4cf1a12010-05-07 17:22:02 +0000882}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000883
Richard Smith1aa0be82012-03-03 22:46:17 +0000884static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000885static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
886 const LValue &This, const Expr *E,
887 CheckConstantExpressionKind CCEK = CCEK_Constant,
888 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000889static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
890static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000891static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
892 EvalInfo &Info);
893static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000894static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000895static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000896 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000897static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000898static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000899
900//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000901// Misc utilities
902//===----------------------------------------------------------------------===//
903
Richard Smith180f4792011-11-10 06:34:14 +0000904/// Should this call expression be treated as a string literal?
905static bool IsStringLiteralCall(const CallExpr *E) {
906 unsigned Builtin = E->isBuiltinCall();
907 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
908 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
909}
910
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000911static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000912 // C++11 [expr.const]p3 An address constant expression is a prvalue core
913 // constant expression of pointer type that evaluates to...
914
915 // ... a null pointer value, or a prvalue core constant expression of type
916 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000917 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000918
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000919 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
920 // ... the address of an object with static storage duration,
921 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
922 return VD->hasGlobalStorage();
923 // ... the address of a function,
924 return isa<FunctionDecl>(D);
925 }
926
927 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000928 switch (E->getStmtClass()) {
929 default:
930 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000931 case Expr::CompoundLiteralExprClass: {
932 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
933 return CLE->isFileScope() && CLE->isLValue();
934 }
Richard Smith180f4792011-11-10 06:34:14 +0000935 // A string literal has static storage duration.
936 case Expr::StringLiteralClass:
937 case Expr::PredefinedExprClass:
938 case Expr::ObjCStringLiteralClass:
939 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000940 case Expr::CXXTypeidExprClass:
Francois Pichete275a182012-04-16 04:08:35 +0000941 case Expr::CXXUuidofExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000942 return true;
943 case Expr::CallExprClass:
944 return IsStringLiteralCall(cast<CallExpr>(E));
945 // For GCC compatibility, &&label has static storage duration.
946 case Expr::AddrLabelExprClass:
947 return true;
948 // A Block literal expression may be used as the initialization value for
949 // Block variables at global or local static scope.
950 case Expr::BlockExprClass:
951 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000952 case Expr::ImplicitValueInitExprClass:
953 // FIXME:
954 // We can never form an lvalue with an implicit value initialization as its
955 // base through expression evaluation, so these only appear in one case: the
956 // implicit variable declaration we invent when checking whether a constexpr
957 // constructor can produce a constant expression. We must assume that such
958 // an expression might be a global lvalue.
959 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000960 }
John McCall42c8f872010-05-10 23:27:23 +0000961}
962
Richard Smith83587db2012-02-15 02:18:13 +0000963static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
964 assert(Base && "no location for a null lvalue");
965 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
966 if (VD)
967 Info.Note(VD->getLocation(), diag::note_declared_at);
968 else
969 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
970 diag::note_constexpr_temporary_here);
971}
972
Richard Smith9a17a682011-11-07 05:07:52 +0000973/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000974/// value for an address or reference constant expression. Return true if we
975/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000976static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
977 QualType Type, const LValue &LVal) {
978 bool IsReferenceType = Type->isReferenceType();
979
Richard Smithc1c5f272011-12-13 06:39:58 +0000980 APValue::LValueBase Base = LVal.getLValueBase();
981 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
982
Richard Smithb78ae972012-02-18 04:58:18 +0000983 // Check that the object is a global. Note that the fake 'this' object we
984 // manufacture when checking potential constant expressions is conservatively
985 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000986 if (!IsGlobalLValue(Base)) {
987 if (Info.getLangOpts().CPlusPlus0x) {
988 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000989 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
990 << IsReferenceType << !Designator.Entries.empty()
991 << !!VD << VD;
992 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000993 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000994 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000995 }
Richard Smith61e61622012-01-12 06:08:57 +0000996 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000997 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000998 }
Richard Smith83587db2012-02-15 02:18:13 +0000999 assert((Info.CheckingPotentialConstantExpression ||
1000 LVal.getLValueCallIndex() == 0) &&
1001 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +00001002
1003 // Allow address constant expressions to be past-the-end pointers. This is
1004 // an extension: the standard requires them to point to an object.
1005 if (!IsReferenceType)
1006 return true;
1007
1008 // A reference constant expression must refer to an object.
1009 if (!Base) {
1010 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001011 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001012 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001013 }
1014
Richard Smithc1c5f272011-12-13 06:39:58 +00001015 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001016 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001017 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001018 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001019 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001020 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001021 }
1022
Richard Smith9a17a682011-11-07 05:07:52 +00001023 return true;
1024}
1025
Richard Smith51201882011-12-30 21:15:51 +00001026/// Check that this core constant expression is of literal type, and if not,
1027/// produce an appropriate diagnostic.
1028static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1029 if (!E->isRValue() || E->getType()->isLiteralType())
1030 return true;
1031
1032 // Prvalue constant expressions must be of literal types.
1033 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001034 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001035 << E->getType();
1036 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001037 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001038 return false;
1039}
1040
Richard Smith47a1eed2011-10-29 20:57:55 +00001041/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001042/// constant expression. If not, report an appropriate diagnostic. Does not
1043/// check that the expression is of literal type.
1044static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1045 QualType Type, const APValue &Value) {
1046 // Core issue 1454: For a literal constant expression of array or class type,
1047 // each subobject of its value shall have been initialized by a constant
1048 // expression.
1049 if (Value.isArray()) {
1050 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1051 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1052 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1053 Value.getArrayInitializedElt(I)))
1054 return false;
1055 }
1056 if (!Value.hasArrayFiller())
1057 return true;
1058 return CheckConstantExpression(Info, DiagLoc, EltTy,
1059 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001060 }
Richard Smith83587db2012-02-15 02:18:13 +00001061 if (Value.isUnion() && Value.getUnionField()) {
1062 return CheckConstantExpression(Info, DiagLoc,
1063 Value.getUnionField()->getType(),
1064 Value.getUnionValue());
1065 }
1066 if (Value.isStruct()) {
1067 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1068 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1069 unsigned BaseIndex = 0;
1070 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1071 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1072 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1073 Value.getStructBase(BaseIndex)))
1074 return false;
1075 }
1076 }
1077 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1078 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001079 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1080 Value.getStructField(I->getFieldIndex())))
Richard Smith83587db2012-02-15 02:18:13 +00001081 return false;
1082 }
1083 }
1084
1085 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001086 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001087 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001088 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1089 }
1090
1091 // Everything else is fine.
1092 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001093}
1094
Richard Smith9e36b532011-10-31 05:11:32 +00001095const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001096 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001097}
1098
1099static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001100 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001101}
1102
Richard Smith65ac5982011-11-01 21:06:14 +00001103static bool IsWeakLValue(const LValue &Value) {
1104 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001105 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001106}
1107
Richard Smith1aa0be82012-03-03 22:46:17 +00001108static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001109 // A null base expression indicates a null pointer. These are always
1110 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001111 if (!Value.getLValueBase()) {
1112 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001113 return true;
1114 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001115
Richard Smithe24f5fc2011-11-17 22:56:20 +00001116 // We have a non-null base. These are generally known to be true, but if it's
1117 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001118 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001119 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001120 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001121}
1122
Richard Smith1aa0be82012-03-03 22:46:17 +00001123static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001124 switch (Val.getKind()) {
1125 case APValue::Uninitialized:
1126 return false;
1127 case APValue::Int:
1128 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001129 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001130 case APValue::Float:
1131 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001132 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001133 case APValue::ComplexInt:
1134 Result = Val.getComplexIntReal().getBoolValue() ||
1135 Val.getComplexIntImag().getBoolValue();
1136 return true;
1137 case APValue::ComplexFloat:
1138 Result = !Val.getComplexFloatReal().isZero() ||
1139 !Val.getComplexFloatImag().isZero();
1140 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001141 case APValue::LValue:
1142 return EvalPointerValueAsBool(Val, Result);
1143 case APValue::MemberPointer:
1144 Result = Val.getMemberPointerDecl();
1145 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001146 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001147 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001148 case APValue::Struct:
1149 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001150 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001151 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001152 }
1153
Richard Smithc49bd112011-10-28 17:51:58 +00001154 llvm_unreachable("unknown APValue kind");
1155}
1156
1157static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1158 EvalInfo &Info) {
1159 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001160 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001161 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001162 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001163 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001164}
1165
Richard Smithc1c5f272011-12-13 06:39:58 +00001166template<typename T>
1167static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1168 const T &SrcValue, QualType DestType) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001169 Info.Diag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001170 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001171 return false;
1172}
1173
1174static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1175 QualType SrcType, const APFloat &Value,
1176 QualType DestType, APSInt &Result) {
1177 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001178 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001179 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Richard Smithc1c5f272011-12-13 06:39:58 +00001181 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001182 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001183 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1184 & APFloat::opInvalidOp)
1185 return HandleOverflow(Info, E, Value, DestType);
1186 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001187}
1188
Richard Smithc1c5f272011-12-13 06:39:58 +00001189static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1190 QualType SrcType, QualType DestType,
1191 APFloat &Result) {
1192 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001193 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001194 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1195 APFloat::rmNearestTiesToEven, &ignored)
1196 & APFloat::opOverflow)
1197 return HandleOverflow(Info, E, Value, DestType);
1198 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001199}
1200
Richard Smithf72fccf2012-01-30 22:27:01 +00001201static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1202 QualType DestType, QualType SrcType,
1203 APSInt &Value) {
1204 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001205 APSInt Result = Value;
1206 // Figure out if this is a truncate, extend or noop cast.
1207 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001208 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001209 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001210 return Result;
1211}
1212
Richard Smithc1c5f272011-12-13 06:39:58 +00001213static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1214 QualType SrcType, const APSInt &Value,
1215 QualType DestType, APFloat &Result) {
1216 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1217 if (Result.convertFromAPInt(Value, Value.isSigned(),
1218 APFloat::rmNearestTiesToEven)
1219 & APFloat::opOverflow)
1220 return HandleOverflow(Info, E, Value, DestType);
1221 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001222}
1223
Eli Friedmane6a24e82011-12-22 03:51:45 +00001224static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1225 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001226 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001227 if (!Evaluate(SVal, Info, E))
1228 return false;
1229 if (SVal.isInt()) {
1230 Res = SVal.getInt();
1231 return true;
1232 }
1233 if (SVal.isFloat()) {
1234 Res = SVal.getFloat().bitcastToAPInt();
1235 return true;
1236 }
1237 if (SVal.isVector()) {
1238 QualType VecTy = E->getType();
1239 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1240 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1241 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1242 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1243 Res = llvm::APInt::getNullValue(VecSize);
1244 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1245 APValue &Elt = SVal.getVectorElt(i);
1246 llvm::APInt EltAsInt;
1247 if (Elt.isInt()) {
1248 EltAsInt = Elt.getInt();
1249 } else if (Elt.isFloat()) {
1250 EltAsInt = Elt.getFloat().bitcastToAPInt();
1251 } else {
1252 // Don't try to handle vectors of anything other than int or float
1253 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001254 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001255 return false;
1256 }
1257 unsigned BaseEltSize = EltAsInt.getBitWidth();
1258 if (BigEndian)
1259 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1260 else
1261 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1262 }
1263 return true;
1264 }
1265 // Give up if the input isn't an int, float, or vector. For example, we
1266 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001267 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001268 return false;
1269}
1270
Richard Smithb4e85ed2012-01-06 16:39:00 +00001271/// Cast an lvalue referring to a base subobject to a derived class, by
1272/// truncating the lvalue's path to the given length.
1273static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1274 const RecordDecl *TruncatedType,
1275 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001276 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001277
1278 // Check we actually point to a derived class object.
1279 if (TruncatedElements == D.Entries.size())
1280 return true;
1281 assert(TruncatedElements >= D.MostDerivedPathLength &&
1282 "not casting to a derived class");
1283 if (!Result.checkSubobject(Info, E, CSK_Derived))
1284 return false;
1285
1286 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001287 const RecordDecl *RD = TruncatedType;
1288 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCall8d59dee2012-05-01 00:38:49 +00001289 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001290 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1291 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001292 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001293 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001294 else
Richard Smith180f4792011-11-10 06:34:14 +00001295 Result.Offset -= Layout.getBaseClassOffset(Base);
1296 RD = Base;
1297 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001298 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001299 return true;
1300}
1301
John McCall8d59dee2012-05-01 00:38:49 +00001302static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001303 const CXXRecordDecl *Derived,
1304 const CXXRecordDecl *Base,
1305 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001306 if (!RL) {
1307 if (Derived->isInvalidDecl()) return false;
1308 RL = &Info.Ctx.getASTRecordLayout(Derived);
1309 }
1310
Richard Smith180f4792011-11-10 06:34:14 +00001311 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001312 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCall8d59dee2012-05-01 00:38:49 +00001313 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001314}
1315
Richard Smithb4e85ed2012-01-06 16:39:00 +00001316static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001317 const CXXRecordDecl *DerivedDecl,
1318 const CXXBaseSpecifier *Base) {
1319 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1320
John McCall8d59dee2012-05-01 00:38:49 +00001321 if (!Base->isVirtual())
1322 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001323
Richard Smithb4e85ed2012-01-06 16:39:00 +00001324 SubobjectDesignator &D = Obj.Designator;
1325 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001326 return false;
1327
Richard Smithb4e85ed2012-01-06 16:39:00 +00001328 // Extract most-derived object and corresponding type.
1329 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1330 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1331 return false;
1332
1333 // Find the virtual base class.
John McCall8d59dee2012-05-01 00:38:49 +00001334 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001335 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1336 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001337 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001338 return true;
1339}
1340
1341/// Update LVal to refer to the given field, which must be a member of the type
1342/// currently described by LVal.
John McCall8d59dee2012-05-01 00:38:49 +00001343static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001344 const FieldDecl *FD,
1345 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001346 if (!RL) {
1347 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001348 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCall8d59dee2012-05-01 00:38:49 +00001349 }
Richard Smith180f4792011-11-10 06:34:14 +00001350
1351 unsigned I = FD->getFieldIndex();
1352 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001353 LVal.addDecl(Info, E, FD);
John McCall8d59dee2012-05-01 00:38:49 +00001354 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001355}
1356
Richard Smithd9b02e72012-01-25 22:15:11 +00001357/// Update LVal to refer to the given indirect field.
John McCall8d59dee2012-05-01 00:38:49 +00001358static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smithd9b02e72012-01-25 22:15:11 +00001359 LValue &LVal,
1360 const IndirectFieldDecl *IFD) {
1361 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1362 CE = IFD->chain_end(); C != CE; ++C)
John McCall8d59dee2012-05-01 00:38:49 +00001363 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1364 return false;
1365 return true;
Richard Smithd9b02e72012-01-25 22:15:11 +00001366}
1367
Richard Smith180f4792011-11-10 06:34:14 +00001368/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001369static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1370 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001371 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1372 // extension.
1373 if (Type->isVoidType() || Type->isFunctionType()) {
1374 Size = CharUnits::One();
1375 return true;
1376 }
1377
1378 if (!Type->isConstantSizeType()) {
1379 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001380 // FIXME: Better diagnostic.
1381 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001382 return false;
1383 }
1384
1385 Size = Info.Ctx.getTypeSizeInChars(Type);
1386 return true;
1387}
1388
1389/// Update a pointer value to model pointer arithmetic.
1390/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001391/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001392/// \param LVal - The pointer value to be updated.
1393/// \param EltTy - The pointee type represented by LVal.
1394/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001395static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1396 LValue &LVal, QualType EltTy,
1397 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001398 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001399 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001400 return false;
1401
1402 // Compute the new offset in the appropriate width.
1403 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001404 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001405 return true;
1406}
1407
Richard Smith86024012012-02-18 22:04:06 +00001408/// Update an lvalue to refer to a component of a complex number.
1409/// \param Info - Information about the ongoing evaluation.
1410/// \param LVal - The lvalue to be updated.
1411/// \param EltTy - The complex number's component type.
1412/// \param Imag - False for the real component, true for the imaginary.
1413static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1414 LValue &LVal, QualType EltTy,
1415 bool Imag) {
1416 if (Imag) {
1417 CharUnits SizeOfComponent;
1418 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1419 return false;
1420 LVal.Offset += SizeOfComponent;
1421 }
1422 LVal.addComplex(Info, E, EltTy, Imag);
1423 return true;
1424}
1425
Richard Smith03f96112011-10-24 17:54:18 +00001426/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001427static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1428 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001429 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001430 // If this is a parameter to an active constexpr function call, perform
1431 // argument substitution.
1432 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001433 // Assume arguments of a potential constant expression are unknown
1434 // constant expressions.
1435 if (Info.CheckingPotentialConstantExpression)
1436 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001437 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001438 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001439 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001440 }
Richard Smith177dce72011-11-01 16:57:24 +00001441 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1442 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001443 }
Richard Smith03f96112011-10-24 17:54:18 +00001444
Richard Smith099e7f62011-12-19 06:19:21 +00001445 // Dig out the initializer, and use the declaration which it's attached to.
1446 const Expr *Init = VD->getAnyInitializer(VD);
1447 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001448 // If we're checking a potential constant expression, the variable could be
1449 // initialized later.
1450 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001451 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001452 return false;
1453 }
1454
Richard Smith180f4792011-11-10 06:34:14 +00001455 // If we're currently evaluating the initializer of this declaration, use that
1456 // in-flight value.
1457 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001458 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001459 return !Result.isUninit();
1460 }
1461
Richard Smith65ac5982011-11-01 21:06:14 +00001462 // Never evaluate the initializer of a weak variable. We can't be sure that
1463 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001464 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001465 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001466 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001467 }
Richard Smith65ac5982011-11-01 21:06:14 +00001468
Richard Smith099e7f62011-12-19 06:19:21 +00001469 // Check that we can fold the initializer. In C++, we will have already done
1470 // this in the cases where it matters for conformance.
1471 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1472 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001473 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001474 Notes.size() + 1) << VD;
1475 Info.Note(VD->getLocation(), diag::note_declared_at);
1476 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001477 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001478 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001479 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001480 Notes.size() + 1) << VD;
1481 Info.Note(VD->getLocation(), diag::note_declared_at);
1482 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001483 }
Richard Smith03f96112011-10-24 17:54:18 +00001484
Richard Smith1aa0be82012-03-03 22:46:17 +00001485 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001486 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001487}
1488
Richard Smithc49bd112011-10-28 17:51:58 +00001489static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001490 Qualifiers Quals = T.getQualifiers();
1491 return Quals.hasConst() && !Quals.hasVolatile();
1492}
1493
Richard Smith59efe262011-11-11 04:05:33 +00001494/// Get the base index of the given base class within an APValue representing
1495/// the given derived class.
1496static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1497 const CXXRecordDecl *Base) {
1498 Base = Base->getCanonicalDecl();
1499 unsigned Index = 0;
1500 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1501 E = Derived->bases_end(); I != E; ++I, ++Index) {
1502 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1503 return Index;
1504 }
1505
1506 llvm_unreachable("base class missing from derived class's bases list");
1507}
1508
Richard Smithfe587202012-04-15 02:50:59 +00001509/// Extract the value of a character from a string literal. CharType is used to
1510/// determine the expected signedness of the result -- a string literal used to
1511/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1512/// of the wrong signedness.
Richard Smithf3908f22012-02-17 03:35:37 +00001513static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smithfe587202012-04-15 02:50:59 +00001514 uint64_t Index, QualType CharType) {
Richard Smithf3908f22012-02-17 03:35:37 +00001515 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1516 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1517 assert(S && "unexpected string literal expression kind");
Richard Smithfe587202012-04-15 02:50:59 +00001518 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smithf3908f22012-02-17 03:35:37 +00001519
1520 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smithfe587202012-04-15 02:50:59 +00001521 CharType->isUnsignedIntegerType());
Richard Smithf3908f22012-02-17 03:35:37 +00001522 if (Index < S->getLength())
1523 Value = S->getCodeUnit(Index);
1524 return Value;
1525}
1526
Richard Smithcc5d4f62011-11-07 09:22:26 +00001527/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001528static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001529 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001530 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001531 if (Sub.Invalid)
1532 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001533 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001534 if (Sub.isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001535 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001536 (unsigned)diag::note_constexpr_read_past_end :
1537 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001538 return false;
1539 }
Richard Smithf64699e2011-11-11 08:28:03 +00001540 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001541 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001542 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1543 // This object might be initialized later.
1544 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001545
Richard Smith0069b842012-03-10 00:28:11 +00001546 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001547 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001548 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001549 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001550 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001551 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001552 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001553 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001554 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001555 // Note, it should not be possible to form a pointer with a valid
1556 // designator which points more than one past the end of the array.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001557 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001558 (unsigned)diag::note_constexpr_read_past_end :
1559 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001560 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001561 }
Richard Smithf3908f22012-02-17 03:35:37 +00001562 // An array object is represented as either an Array APValue or as an
1563 // LValue which refers to a string literal.
1564 if (O->isLValue()) {
1565 assert(I == N - 1 && "extracting subobject of character?");
1566 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001567 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithfe587202012-04-15 02:50:59 +00001568 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smithf3908f22012-02-17 03:35:37 +00001569 return true;
1570 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001571 O = &O->getArrayInitializedElt(Index);
1572 else
1573 O = &O->getArrayFiller();
1574 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001575 } else if (ObjType->isAnyComplexType()) {
1576 // Next subobject is a complex number.
1577 uint64_t Index = Sub.Entries[I].ArrayIndex;
1578 if (Index > 1) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001579 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Richard Smith86024012012-02-18 22:04:06 +00001580 (unsigned)diag::note_constexpr_read_past_end :
1581 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1582 return false;
1583 }
1584 assert(I == N - 1 && "extracting subobject of scalar?");
1585 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001586 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001587 : O->getComplexIntReal());
1588 } else {
1589 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001590 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001591 : O->getComplexFloatReal());
1592 }
1593 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001594 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001595 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001596 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001597 << Field;
1598 Info.Note(Field->getLocation(), diag::note_declared_at);
1599 return false;
1600 }
1601
Richard Smith180f4792011-11-10 06:34:14 +00001602 // Next subobject is a class, struct or union field.
1603 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1604 if (RD->isUnion()) {
1605 const FieldDecl *UnionField = O->getUnionField();
1606 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001607 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001608 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001609 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001610 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001611 }
Richard Smith180f4792011-11-10 06:34:14 +00001612 O = &O->getUnionValue();
1613 } else
1614 O = &O->getStructField(Field->getFieldIndex());
1615 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001616
1617 if (ObjType.isVolatileQualified()) {
1618 if (Info.getLangOpts().CPlusPlus) {
1619 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001620 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001621 << 2 << Field;
1622 Info.Note(Field->getLocation(), diag::note_declared_at);
1623 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001624 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001625 }
1626 return false;
1627 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001628 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001629 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001630 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1631 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1632 O = &O->getStructBase(getBaseIndex(Derived, Base));
1633 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001634 }
Richard Smith180f4792011-11-10 06:34:14 +00001635
Richard Smithf48fdb02011-12-09 22:58:01 +00001636 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001637 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001638 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001639 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001640 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001641 }
1642
Richard Smith0069b842012-03-10 00:28:11 +00001643 // This may look super-stupid, but it serves an important purpose: if we just
1644 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1645 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1646 // object, which is destroyed by Tmp's destructor.
1647 APValue Tmp;
1648 O->swap(Tmp);
1649 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001650 return true;
1651}
1652
Richard Smithf15fda02012-02-02 01:16:57 +00001653/// Find the position where two subobject designators diverge, or equivalently
1654/// the length of the common initial subsequence.
1655static unsigned FindDesignatorMismatch(QualType ObjType,
1656 const SubobjectDesignator &A,
1657 const SubobjectDesignator &B,
1658 bool &WasArrayIndex) {
1659 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1660 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001661 if (!ObjType.isNull() &&
1662 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001663 // Next subobject is an array element.
1664 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1665 WasArrayIndex = true;
1666 return I;
1667 }
Richard Smith86024012012-02-18 22:04:06 +00001668 if (ObjType->isAnyComplexType())
1669 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1670 else
1671 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001672 } else {
1673 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1674 WasArrayIndex = false;
1675 return I;
1676 }
1677 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1678 // Next subobject is a field.
1679 ObjType = FD->getType();
1680 else
1681 // Next subobject is a base class.
1682 ObjType = QualType();
1683 }
1684 }
1685 WasArrayIndex = false;
1686 return I;
1687}
1688
1689/// Determine whether the given subobject designators refer to elements of the
1690/// same array object.
1691static bool AreElementsOfSameArray(QualType ObjType,
1692 const SubobjectDesignator &A,
1693 const SubobjectDesignator &B) {
1694 if (A.Entries.size() != B.Entries.size())
1695 return false;
1696
1697 bool IsArray = A.MostDerivedArraySize != 0;
1698 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1699 // A is a subobject of the array element.
1700 return false;
1701
1702 // If A (and B) designates an array element, the last entry will be the array
1703 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1704 // of length 1' case, and the entire path must match.
1705 bool WasArrayIndex;
1706 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1707 return CommonLength >= A.Entries.size() - IsArray;
1708}
1709
Richard Smith180f4792011-11-10 06:34:14 +00001710/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1711/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1712/// for looking up the glvalue referred to by an entity of reference type.
1713///
1714/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001715/// \param Conv - The expression for which we are performing the conversion.
1716/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001717/// \param Type - The type we expect this conversion to produce, before
1718/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001719/// \param LVal - The glvalue on which we are attempting to perform this action.
1720/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001721static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1722 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001723 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001724 if (LVal.Designator.Invalid)
1725 // A diagnostic will have already been produced.
1726 return false;
1727
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001728 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001729
Richard Smithf48fdb02011-12-09 22:58:01 +00001730 if (!LVal.Base) {
1731 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001732 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001733 return false;
1734 }
1735
Richard Smith83587db2012-02-15 02:18:13 +00001736 CallStackFrame *Frame = 0;
1737 if (LVal.CallIndex) {
1738 Frame = Info.getCallFrame(LVal.CallIndex);
1739 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001740 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001741 NoteLValueLocation(Info, LVal.Base);
1742 return false;
1743 }
1744 }
1745
Richard Smith7098cbd2011-12-21 05:04:46 +00001746 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1747 // is not a constant expression (even if the object is non-volatile). We also
1748 // apply this rule to C++98, in order to conform to the expected 'volatile'
1749 // semantics.
1750 if (Type.isVolatileQualified()) {
1751 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001752 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001753 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001754 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001755 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001756 }
Richard Smithc49bd112011-10-28 17:51:58 +00001757
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001758 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001759 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1760 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001761 // expressions are constant expressions too. Inside constexpr functions,
1762 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001763 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001764 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregord2008e22012-04-06 22:40:38 +00001765 if (VD) {
1766 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1767 VD = VDef;
1768 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001769 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001770 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001771 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001772 }
1773
Richard Smith7098cbd2011-12-21 05:04:46 +00001774 // DR1313: If the object is volatile-qualified but the glvalue was not,
1775 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001776 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001777 if (VT.isVolatileQualified()) {
1778 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001779 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 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 Smithf48fdb02011-12-09 22:58:01 +00001783 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001784 return false;
1785 }
1786
1787 if (!isa<ParmVarDecl>(VD)) {
1788 if (VD->isConstexpr()) {
1789 // OK, we can read this variable.
1790 } else if (VT->isIntegralOrEnumerationType()) {
1791 if (!VT.isConstQualified()) {
1792 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001793 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001794 Info.Note(VD->getLocation(), diag::note_declared_at);
1795 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001796 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001797 }
1798 return false;
1799 }
1800 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1801 // We support folding of const floating-point types, in order to make
1802 // static const data members of such types (supported as an extension)
1803 // more useful.
1804 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001805 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001806 Info.Note(VD->getLocation(), diag::note_declared_at);
1807 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001808 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001809 }
1810 } else {
1811 // FIXME: Allow folding of values of any literal type in all languages.
1812 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001813 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001814 Info.Note(VD->getLocation(), diag::note_declared_at);
1815 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001816 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001817 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001818 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001819 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001820 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001821
Richard Smithf48fdb02011-12-09 22:58:01 +00001822 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001823 return false;
1824
Richard Smith47a1eed2011-10-29 20:57:55 +00001825 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001826 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001827
1828 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1829 // conversion. This happens when the declaration and the lvalue should be
1830 // considered synonymous, for instance when initializing an array of char
1831 // from a string literal. Continue as if the initializer lvalue was the
1832 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001833 assert(RVal.getLValueOffset().isZero() &&
1834 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001835 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001836
1837 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1838 Frame = Info.getCallFrame(CallIndex);
1839 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001840 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001841 NoteLValueLocation(Info, RVal.getLValueBase());
1842 return false;
1843 }
1844 } else {
1845 Frame = 0;
1846 }
Richard Smithc49bd112011-10-28 17:51:58 +00001847 }
1848
Richard Smith7098cbd2011-12-21 05:04:46 +00001849 // Volatile temporary objects cannot be read in constant expressions.
1850 if (Base->getType().isVolatileQualified()) {
1851 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001852 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001853 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1854 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001855 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001856 }
1857 return false;
1858 }
1859
Richard Smithcc5d4f62011-11-07 09:22:26 +00001860 if (Frame) {
1861 // If this is a temporary expression with a nontrivial initializer, grab the
1862 // value from the relevant stack frame.
1863 RVal = Frame->Temporaries[Base];
1864 } else if (const CompoundLiteralExpr *CLE
1865 = dyn_cast<CompoundLiteralExpr>(Base)) {
1866 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1867 // initializer until now for such expressions. Such an expression can't be
1868 // an ICE in C, so this only matters for fold.
1869 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1870 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1871 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001872 } else if (isa<StringLiteral>(Base)) {
1873 // We represent a string literal array as an lvalue pointing at the
1874 // corresponding expression, rather than building an array of chars.
1875 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001876 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001877 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001878 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001879 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001880 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001881
Richard Smithf48fdb02011-12-09 22:58:01 +00001882 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1883 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001884}
1885
Richard Smith59efe262011-11-11 04:05:33 +00001886/// Build an lvalue for the object argument of a member function call.
1887static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1888 LValue &This) {
1889 if (Object->getType()->isPointerType())
1890 return EvaluatePointer(Object, This, Info);
1891
1892 if (Object->isGLValue())
1893 return EvaluateLValue(Object, This, Info);
1894
Richard Smithe24f5fc2011-11-17 22:56:20 +00001895 if (Object->getType()->isLiteralType())
1896 return EvaluateTemporary(Object, This, Info);
1897
1898 return false;
1899}
1900
1901/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1902/// lvalue referring to the result.
1903///
1904/// \param Info - Information about the ongoing evaluation.
1905/// \param BO - The member pointer access operation.
1906/// \param LV - Filled in with a reference to the resulting object.
1907/// \param IncludeMember - Specifies whether the member itself is included in
1908/// the resulting LValue subobject designator. This is not possible when
1909/// creating a bound member function.
1910/// \return The field or method declaration to which the member pointer refers,
1911/// or 0 if evaluation fails.
1912static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1913 const BinaryOperator *BO,
1914 LValue &LV,
1915 bool IncludeMember = true) {
1916 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1917
Richard Smith745f5142012-01-27 01:14:48 +00001918 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1919 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001920 return 0;
1921
1922 MemberPtr MemPtr;
1923 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1924 return 0;
1925
1926 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1927 // member value, the behavior is undefined.
1928 if (!MemPtr.getDecl())
1929 return 0;
1930
Richard Smith745f5142012-01-27 01:14:48 +00001931 if (!EvalObjOK)
1932 return 0;
1933
Richard Smithe24f5fc2011-11-17 22:56:20 +00001934 if (MemPtr.isDerivedMember()) {
1935 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001936 // The end of the derived-to-base path for the base object must match the
1937 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001938 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001939 LV.Designator.Entries.size())
1940 return 0;
1941 unsigned PathLengthToMember =
1942 LV.Designator.Entries.size() - MemPtr.Path.size();
1943 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1944 const CXXRecordDecl *LVDecl = getAsBaseClass(
1945 LV.Designator.Entries[PathLengthToMember + I]);
1946 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1947 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1948 return 0;
1949 }
1950
1951 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001952 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1953 PathLengthToMember))
1954 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001955 } else if (!MemPtr.Path.empty()) {
1956 // Extend the LValue path with the member pointer's path.
1957 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1958 MemPtr.Path.size() + IncludeMember);
1959
1960 // Walk down to the appropriate base class.
1961 QualType LVType = BO->getLHS()->getType();
1962 if (const PointerType *PT = LVType->getAs<PointerType>())
1963 LVType = PT->getPointeeType();
1964 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1965 assert(RD && "member pointer access on non-class-type expression");
1966 // The first class in the path is that of the lvalue.
1967 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1968 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCall8d59dee2012-05-01 00:38:49 +00001969 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1970 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001971 RD = Base;
1972 }
1973 // Finally cast to the class containing the member.
John McCall8d59dee2012-05-01 00:38:49 +00001974 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1975 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001976 }
1977
1978 // Add the member. Note that we cannot build bound member functions here.
1979 if (IncludeMember) {
John McCall8d59dee2012-05-01 00:38:49 +00001980 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
1981 if (!HandleLValueMember(Info, BO, LV, FD))
1982 return 0;
1983 } else if (const IndirectFieldDecl *IFD =
1984 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
1985 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
1986 return 0;
1987 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00001988 llvm_unreachable("can't construct reference to bound member function");
John McCall8d59dee2012-05-01 00:38:49 +00001989 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001990 }
1991
1992 return MemPtr.getDecl();
1993}
1994
1995/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1996/// the provided lvalue, which currently refers to the base object.
1997static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1998 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001999 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002000 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002001 return false;
2002
Richard Smithb4e85ed2012-01-06 16:39:00 +00002003 QualType TargetQT = E->getType();
2004 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2005 TargetQT = PT->getPointeeType();
2006
2007 // Check this cast lands within the final derived-to-base subobject path.
2008 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002009 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002010 << D.MostDerivedType << TargetQT;
2011 return false;
2012 }
2013
Richard Smithe24f5fc2011-11-17 22:56:20 +00002014 // Check the type of the final cast. We don't need to check the path,
2015 // since a cast can only be formed if the path is unique.
2016 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002017 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2018 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002019 if (NewEntriesSize == D.MostDerivedPathLength)
2020 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2021 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002022 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002023 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002024 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002025 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002026 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002027 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002028
2029 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002030 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002031}
2032
Mike Stumpc4c90452009-10-27 22:09:17 +00002033namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002034enum EvalStmtResult {
2035 /// Evaluation failed.
2036 ESR_Failed,
2037 /// Hit a 'return' statement.
2038 ESR_Returned,
2039 /// Evaluation succeeded.
2040 ESR_Succeeded
2041};
2042}
2043
2044// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002045static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002046 const Stmt *S) {
2047 switch (S->getStmtClass()) {
2048 default:
2049 return ESR_Failed;
2050
2051 case Stmt::NullStmtClass:
2052 case Stmt::DeclStmtClass:
2053 return ESR_Succeeded;
2054
Richard Smithc1c5f272011-12-13 06:39:58 +00002055 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002056 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002057 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002058 return ESR_Failed;
2059 return ESR_Returned;
2060 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002061
2062 case Stmt::CompoundStmtClass: {
2063 const CompoundStmt *CS = cast<CompoundStmt>(S);
2064 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2065 BE = CS->body_end(); BI != BE; ++BI) {
2066 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2067 if (ESR != ESR_Succeeded)
2068 return ESR;
2069 }
2070 return ESR_Succeeded;
2071 }
2072 }
2073}
2074
Richard Smith61802452011-12-22 02:22:31 +00002075/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2076/// default constructor. If so, we'll fold it whether or not it's marked as
2077/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2078/// so we need special handling.
2079static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002080 const CXXConstructorDecl *CD,
2081 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002082 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2083 return false;
2084
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002085 // Value-initialization does not call a trivial default constructor, so such a
2086 // call is a core constant expression whether or not the constructor is
2087 // constexpr.
2088 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002089 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002090 // FIXME: If DiagDecl is an implicitly-declared special member function,
2091 // we should be much more explicit about why it's not constexpr.
2092 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2093 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2094 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002095 } else {
2096 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2097 }
2098 }
2099 return true;
2100}
2101
Richard Smithc1c5f272011-12-13 06:39:58 +00002102/// CheckConstexprFunction - Check that a function can be called in a constant
2103/// expression.
2104static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2105 const FunctionDecl *Declaration,
2106 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002107 // Potential constant expressions can contain calls to declared, but not yet
2108 // defined, constexpr functions.
2109 if (Info.CheckingPotentialConstantExpression && !Definition &&
2110 Declaration->isConstexpr())
2111 return false;
2112
Richard Smithc1c5f272011-12-13 06:39:58 +00002113 // Can we evaluate this function call?
2114 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2115 return true;
2116
2117 if (Info.getLangOpts().CPlusPlus0x) {
2118 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002119 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2120 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002121 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2122 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2123 << DiagDecl;
2124 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2125 } else {
2126 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2127 }
2128 return false;
2129}
2130
Richard Smith180f4792011-11-10 06:34:14 +00002131namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002132typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002133}
2134
2135/// EvaluateArgs - Evaluate the arguments to a function call.
2136static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2137 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002138 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002139 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002140 I != E; ++I) {
2141 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2142 // If we're checking for a potential constant expression, evaluate all
2143 // initializers even if some of them fail.
2144 if (!Info.keepEvaluatingAfterFailure())
2145 return false;
2146 Success = false;
2147 }
2148 }
2149 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002150}
2151
Richard Smithd0dccea2011-10-28 22:34:42 +00002152/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002153static bool HandleFunctionCall(SourceLocation CallLoc,
2154 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002155 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002156 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002157 ArgVector ArgValues(Args.size());
2158 if (!EvaluateArgs(Args, ArgValues, Info))
2159 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002160
Richard Smith745f5142012-01-27 01:14:48 +00002161 if (!Info.CheckCallLimit(CallLoc))
2162 return false;
2163
2164 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002165 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2166}
2167
Richard Smith180f4792011-11-10 06:34:14 +00002168/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002169static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002170 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002171 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002172 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002173 ArgVector ArgValues(Args.size());
2174 if (!EvaluateArgs(Args, ArgValues, Info))
2175 return false;
2176
Richard Smith745f5142012-01-27 01:14:48 +00002177 if (!Info.CheckCallLimit(CallLoc))
2178 return false;
2179
Richard Smith86c3ae42012-02-13 03:54:03 +00002180 const CXXRecordDecl *RD = Definition->getParent();
2181 if (RD->getNumVBases()) {
2182 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2183 return false;
2184 }
2185
Richard Smith745f5142012-01-27 01:14:48 +00002186 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002187
2188 // If it's a delegating constructor, just delegate.
2189 if (Definition->isDelegatingConstructor()) {
2190 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002191 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002192 }
2193
Richard Smith610a60c2012-01-10 04:32:03 +00002194 // For a trivial copy or move constructor, perform an APValue copy. This is
2195 // essential for unions, where the operations performed by the constructor
2196 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002197 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002198 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2199 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002200 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002201 RHS.setFrom(Info.Ctx, ArgValues[0]);
2202 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2203 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002204 }
2205
2206 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002207 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002208 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2209 std::distance(RD->field_begin(), RD->field_end()));
2210
John McCall8d59dee2012-05-01 00:38:49 +00002211 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00002212 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2213
Richard Smith745f5142012-01-27 01:14:48 +00002214 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002215 unsigned BasesSeen = 0;
2216#ifndef NDEBUG
2217 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2218#endif
2219 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2220 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002221 LValue Subobject = This;
2222 APValue *Value = &Result;
2223
2224 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002225 if ((*I)->isBaseInitializer()) {
2226 QualType BaseType((*I)->getBaseClass(), 0);
2227#ifndef NDEBUG
2228 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002229 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002230 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2231 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2232 "base class initializers not in expected order");
2233 ++BaseIt;
2234#endif
John McCall8d59dee2012-05-01 00:38:49 +00002235 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2236 BaseType->getAsCXXRecordDecl(), &Layout))
2237 return false;
Richard Smith745f5142012-01-27 01:14:48 +00002238 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002239 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCall8d59dee2012-05-01 00:38:49 +00002240 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2241 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002242 if (RD->isUnion()) {
2243 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002244 Value = &Result.getUnionValue();
2245 } else {
2246 Value = &Result.getStructField(FD->getFieldIndex());
2247 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002248 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002249 // Walk the indirect field decl's chain to find the object to initialize,
2250 // and make sure we've initialized every step along it.
2251 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2252 CE = IFD->chain_end();
2253 C != CE; ++C) {
2254 FieldDecl *FD = cast<FieldDecl>(*C);
2255 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2256 // Switch the union field if it differs. This happens if we had
2257 // preceding zero-initialization, and we're now initializing a union
2258 // subobject other than the first.
2259 // FIXME: In this case, the values of the other subobjects are
2260 // specified, since zero-initialization sets all padding bits to zero.
2261 if (Value->isUninit() ||
2262 (Value->isUnion() && Value->getUnionField() != FD)) {
2263 if (CD->isUnion())
2264 *Value = APValue(FD);
2265 else
2266 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2267 std::distance(CD->field_begin(), CD->field_end()));
2268 }
John McCall8d59dee2012-05-01 00:38:49 +00002269 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2270 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002271 if (CD->isUnion())
2272 Value = &Value->getUnionValue();
2273 else
2274 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002275 }
Richard Smith180f4792011-11-10 06:34:14 +00002276 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002277 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002278 }
Richard Smith745f5142012-01-27 01:14:48 +00002279
Richard Smith83587db2012-02-15 02:18:13 +00002280 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2281 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002282 ? CCEK_Constant : CCEK_MemberInit)) {
2283 // If we're checking for a potential constant expression, evaluate all
2284 // initializers even if some of them fail.
2285 if (!Info.keepEvaluatingAfterFailure())
2286 return false;
2287 Success = false;
2288 }
Richard Smith180f4792011-11-10 06:34:14 +00002289 }
2290
Richard Smith745f5142012-01-27 01:14:48 +00002291 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002292}
2293
Richard Smithd0dccea2011-10-28 22:34:42 +00002294namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002295class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002296 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002297 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002298public:
2299
Richard Smith1e12c592011-10-16 21:26:27 +00002300 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002301
2302 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002303 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002304 return true;
2305 }
2306
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002307 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2308 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002309 return Visit(E->getResultExpr());
2310 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002311 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002312 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002313 return true;
2314 return false;
2315 }
John McCallf85e1932011-06-15 23:02:42 +00002316 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002317 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002318 return true;
2319 return false;
2320 }
John McCallf85e1932011-06-15 23:02:42 +00002321
Mike Stumpc4c90452009-10-27 22:09:17 +00002322 // We don't want to evaluate BlockExprs multiple times, as they generate
2323 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002324 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2325 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2326 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002327 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002328 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2329 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2330 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2331 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2332 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2333 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002334 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002335 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002336 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002337 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002338 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002339 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2340 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2341 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2342 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002343 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002344 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2345 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2346 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2347 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2348 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002349 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002350 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002351 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002352 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002353 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002354
2355 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002356 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002357 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2358 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002359 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002360 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002361 return false;
2362 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002363
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002364 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002365};
2366
John McCall56ca35d2011-02-17 10:25:35 +00002367class OpaqueValueEvaluation {
2368 EvalInfo &info;
2369 OpaqueValueExpr *opaqueValue;
2370
2371public:
2372 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2373 Expr *value)
2374 : info(info), opaqueValue(opaqueValue) {
2375
2376 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002377 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002378 this->opaqueValue = 0;
2379 return;
2380 }
John McCall56ca35d2011-02-17 10:25:35 +00002381 }
2382
2383 bool hasError() const { return opaqueValue == 0; }
2384
2385 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002386 // FIXME: For a recursive constexpr call, an outer stack frame might have
2387 // been using this opaque value too, and will now have to re-evaluate the
2388 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002389 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2390 }
2391};
2392
Mike Stumpc4c90452009-10-27 22:09:17 +00002393} // end anonymous namespace
2394
Eli Friedman4efaa272008-11-12 09:44:48 +00002395//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002396// Generic Evaluation
2397//===----------------------------------------------------------------------===//
2398namespace {
2399
Richard Smithf48fdb02011-12-09 22:58:01 +00002400// FIXME: RetTy is always bool. Remove it.
2401template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002402class ExprEvaluatorBase
2403 : public ConstStmtVisitor<Derived, RetTy> {
2404private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002405 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002406 return static_cast<Derived*>(this)->Success(V, E);
2407 }
Richard Smith51201882011-12-30 21:15:51 +00002408 RetTy DerivedZeroInitialization(const Expr *E) {
2409 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002410 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002411
Richard Smith74e1ad92012-02-16 02:46:34 +00002412 // Check whether a conditional operator with a non-constant condition is a
2413 // potential constant expression. If neither arm is a potential constant
2414 // expression, then the conditional operator is not either.
2415 template<typename ConditionalOperator>
2416 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2417 assert(Info.CheckingPotentialConstantExpression);
2418
2419 // Speculatively evaluate both arms.
2420 {
2421 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2422 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2423
2424 StmtVisitorTy::Visit(E->getFalseExpr());
2425 if (Diag.empty())
2426 return;
2427
2428 Diag.clear();
2429 StmtVisitorTy::Visit(E->getTrueExpr());
2430 if (Diag.empty())
2431 return;
2432 }
2433
2434 Error(E, diag::note_constexpr_conditional_never_const);
2435 }
2436
2437
2438 template<typename ConditionalOperator>
2439 bool HandleConditionalOperator(const ConditionalOperator *E) {
2440 bool BoolResult;
2441 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2442 if (Info.CheckingPotentialConstantExpression)
2443 CheckPotentialConstantConditional(E);
2444 return false;
2445 }
2446
2447 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2448 return StmtVisitorTy::Visit(EvalExpr);
2449 }
2450
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002451protected:
2452 EvalInfo &Info;
2453 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2454 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2455
Richard Smithdd1f29b2011-12-12 09:28:41 +00002456 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002457 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002458 }
2459
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00002460 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2461
2462public:
2463 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2464
2465 EvalInfo &getEvalInfo() { return Info; }
2466
Richard Smithf48fdb02011-12-09 22:58:01 +00002467 /// Report an evaluation error. This should only be called when an error is
2468 /// first discovered. When propagating an error, just return false.
2469 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002470 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002471 return false;
2472 }
2473 bool Error(const Expr *E) {
2474 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2475 }
2476
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002477 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002478 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002479 }
2480 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002481 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002482 }
2483
2484 RetTy VisitParenExpr(const ParenExpr *E)
2485 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2486 RetTy VisitUnaryExtension(const UnaryOperator *E)
2487 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2488 RetTy VisitUnaryPlus(const UnaryOperator *E)
2489 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2490 RetTy VisitChooseExpr(const ChooseExpr *E)
2491 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2492 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2493 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002494 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2495 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002496 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2497 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002498 // We cannot create any objects for which cleanups are required, so there is
2499 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2500 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2501 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002502
Richard Smithc216a012011-12-12 12:46:16 +00002503 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2504 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2505 return static_cast<Derived*>(this)->VisitCastExpr(E);
2506 }
2507 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2508 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2509 return static_cast<Derived*>(this)->VisitCastExpr(E);
2510 }
2511
Richard Smithe24f5fc2011-11-17 22:56:20 +00002512 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2513 switch (E->getOpcode()) {
2514 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002515 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002516
2517 case BO_Comma:
2518 VisitIgnoredValue(E->getLHS());
2519 return StmtVisitorTy::Visit(E->getRHS());
2520
2521 case BO_PtrMemD:
2522 case BO_PtrMemI: {
2523 LValue Obj;
2524 if (!HandleMemberPointerAccess(Info, E, Obj))
2525 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002526 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002527 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002528 return false;
2529 return DerivedSuccess(Result, E);
2530 }
2531 }
2532 }
2533
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002534 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002535 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002536 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2537 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002538 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002539
Richard Smith74e1ad92012-02-16 02:46:34 +00002540 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002541 }
2542
2543 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002544 bool IsBcpCall = false;
2545 // If the condition (ignoring parens) is a __builtin_constant_p call,
2546 // the result is a constant expression if it can be folded without
2547 // side-effects. This is an important GNU extension. See GCC PR38377
2548 // for discussion.
2549 if (const CallExpr *CallCE =
2550 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2551 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2552 IsBcpCall = true;
2553
2554 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2555 // constant expression; we can't check whether it's potentially foldable.
2556 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2557 return false;
2558
2559 FoldConstant Fold(Info);
2560
Richard Smith74e1ad92012-02-16 02:46:34 +00002561 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002562 return false;
2563
2564 if (IsBcpCall)
2565 Fold.Fold(Info);
2566
2567 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002568 }
2569
2570 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002571 const APValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002572 if (!Value) {
2573 const Expr *Source = E->getSourceExpr();
2574 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002575 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002576 if (Source == E) { // sanity checking.
2577 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002578 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002579 }
2580 return StmtVisitorTy::Visit(Source);
2581 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002582 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002583 }
Richard Smithf10d9172011-10-11 21:43:33 +00002584
Richard Smithd0dccea2011-10-28 22:34:42 +00002585 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002586 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002587 QualType CalleeType = Callee->getType();
2588
Richard Smithd0dccea2011-10-28 22:34:42 +00002589 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002590 LValue *This = 0, ThisVal;
2591 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002592 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002593
Richard Smith59efe262011-11-11 04:05:33 +00002594 // Extract function decl and 'this' pointer from the callee.
2595 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002596 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002597 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2598 // Explicit bound member calls, such as x.f() or p->g();
2599 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002600 return false;
2601 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002602 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002603 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002604 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2605 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002606 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2607 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002608 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002609 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002610 return Error(Callee);
2611
2612 FD = dyn_cast<FunctionDecl>(Member);
2613 if (!FD)
2614 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002615 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002616 LValue Call;
2617 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002618 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002619
Richard Smithb4e85ed2012-01-06 16:39:00 +00002620 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002621 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002622 FD = dyn_cast_or_null<FunctionDecl>(
2623 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002624 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002625 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002626
2627 // Overloaded operator calls to member functions are represented as normal
2628 // calls with '*this' as the first argument.
2629 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2630 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002631 // FIXME: When selecting an implicit conversion for an overloaded
2632 // operator delete, we sometimes try to evaluate calls to conversion
2633 // operators without a 'this' parameter!
2634 if (Args.empty())
2635 return Error(E);
2636
Richard Smith59efe262011-11-11 04:05:33 +00002637 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2638 return false;
2639 This = &ThisVal;
2640 Args = Args.slice(1);
2641 }
2642
2643 // Don't call function pointers which have been cast to some other type.
2644 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002645 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002646 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002647 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002648
Richard Smithb04035a2012-02-01 02:39:43 +00002649 if (This && !This->checkSubobject(Info, E, CSK_This))
2650 return false;
2651
Richard Smith86c3ae42012-02-13 03:54:03 +00002652 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2653 // calls to such functions in constant expressions.
2654 if (This && !HasQualifier &&
2655 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2656 return Error(E, diag::note_constexpr_virtual_call);
2657
Richard Smithc1c5f272011-12-13 06:39:58 +00002658 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002659 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002660 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002661
Richard Smithc1c5f272011-12-13 06:39:58 +00002662 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002663 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2664 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002665 return false;
2666
Richard Smith83587db2012-02-15 02:18:13 +00002667 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002668 }
2669
Richard Smithc49bd112011-10-28 17:51:58 +00002670 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2671 return StmtVisitorTy::Visit(E->getInitializer());
2672 }
Richard Smithf10d9172011-10-11 21:43:33 +00002673 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002674 if (E->getNumInits() == 0)
2675 return DerivedZeroInitialization(E);
2676 if (E->getNumInits() == 1)
2677 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002678 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002679 }
2680 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002681 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002682 }
2683 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002684 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002685 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002686 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002687 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002688 }
Richard Smithf10d9172011-10-11 21:43:33 +00002689
Richard Smith180f4792011-11-10 06:34:14 +00002690 /// A member expression where the object is a prvalue is itself a prvalue.
2691 RetTy VisitMemberExpr(const MemberExpr *E) {
2692 assert(!E->isArrow() && "missing call to bound member function?");
2693
Richard Smith1aa0be82012-03-03 22:46:17 +00002694 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002695 if (!Evaluate(Val, Info, E->getBase()))
2696 return false;
2697
2698 QualType BaseTy = E->getBase()->getType();
2699
2700 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002701 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002702 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2703 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2704 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2705
Richard Smithb4e85ed2012-01-06 16:39:00 +00002706 SubobjectDesignator Designator(BaseTy);
2707 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002708
Richard Smithf48fdb02011-12-09 22:58:01 +00002709 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002710 DerivedSuccess(Val, E);
2711 }
2712
Richard Smithc49bd112011-10-28 17:51:58 +00002713 RetTy VisitCastExpr(const CastExpr *E) {
2714 switch (E->getCastKind()) {
2715 default:
2716 break;
2717
David Chisnall7a7ee302012-01-16 17:27:18 +00002718 case CK_AtomicToNonAtomic:
2719 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002720 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002721 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002722 return StmtVisitorTy::Visit(E->getSubExpr());
2723
2724 case CK_LValueToRValue: {
2725 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002726 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2727 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002728 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002729 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2730 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2731 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002732 return false;
2733 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002734 }
2735 }
2736
Richard Smithf48fdb02011-12-09 22:58:01 +00002737 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002738 }
2739
Richard Smith8327fad2011-10-24 18:44:57 +00002740 /// Visit a value which is evaluated, but whose value is ignored.
2741 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002742 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002743 if (!Evaluate(Scratch, Info, E))
2744 Info.EvalStatus.HasSideEffects = true;
2745 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002746};
2747
2748}
2749
2750//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002751// Common base class for lvalue and temporary evaluation.
2752//===----------------------------------------------------------------------===//
2753namespace {
2754template<class Derived>
2755class LValueExprEvaluatorBase
2756 : public ExprEvaluatorBase<Derived, bool> {
2757protected:
2758 LValue &Result;
2759 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2760 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2761
2762 bool Success(APValue::LValueBase B) {
2763 Result.set(B);
2764 return true;
2765 }
2766
2767public:
2768 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2769 ExprEvaluatorBaseTy(Info), Result(Result) {}
2770
Richard Smith1aa0be82012-03-03 22:46:17 +00002771 bool Success(const APValue &V, const Expr *E) {
2772 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002773 return true;
2774 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002775
Richard Smithe24f5fc2011-11-17 22:56:20 +00002776 bool VisitMemberExpr(const MemberExpr *E) {
2777 // Handle non-static data members.
2778 QualType BaseTy;
2779 if (E->isArrow()) {
2780 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2781 return false;
2782 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002783 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002784 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002785 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2786 return false;
2787 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002788 } else {
2789 if (!this->Visit(E->getBase()))
2790 return false;
2791 BaseTy = E->getBase()->getType();
2792 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002793
Richard Smithd9b02e72012-01-25 22:15:11 +00002794 const ValueDecl *MD = E->getMemberDecl();
2795 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2796 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2797 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2798 (void)BaseTy;
John McCall8d59dee2012-05-01 00:38:49 +00002799 if (!HandleLValueMember(this->Info, E, Result, FD))
2800 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002801 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCall8d59dee2012-05-01 00:38:49 +00002802 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2803 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002804 } else
2805 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002806
Richard Smithd9b02e72012-01-25 22:15:11 +00002807 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002808 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002809 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002810 RefValue))
2811 return false;
2812 return Success(RefValue, E);
2813 }
2814 return true;
2815 }
2816
2817 bool VisitBinaryOperator(const BinaryOperator *E) {
2818 switch (E->getOpcode()) {
2819 default:
2820 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2821
2822 case BO_PtrMemD:
2823 case BO_PtrMemI:
2824 return HandleMemberPointerAccess(this->Info, E, Result);
2825 }
2826 }
2827
2828 bool VisitCastExpr(const CastExpr *E) {
2829 switch (E->getCastKind()) {
2830 default:
2831 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2832
2833 case CK_DerivedToBase:
2834 case CK_UncheckedDerivedToBase: {
2835 if (!this->Visit(E->getSubExpr()))
2836 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002837
2838 // Now figure out the necessary offset to add to the base LV to get from
2839 // the derived class to the base class.
2840 QualType Type = E->getSubExpr()->getType();
2841
2842 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2843 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002844 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002845 *PathI))
2846 return false;
2847 Type = (*PathI)->getType();
2848 }
2849
2850 return true;
2851 }
2852 }
2853 }
2854};
2855}
2856
2857//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002858// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002859//
2860// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2861// function designators (in C), decl references to void objects (in C), and
2862// temporaries (if building with -Wno-address-of-temporary).
2863//
2864// LValue evaluation produces values comprising a base expression of one of the
2865// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002866// - Declarations
2867// * VarDecl
2868// * FunctionDecl
2869// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002870// * CompoundLiteralExpr in C
2871// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002872// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002873// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002874// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002875// * ObjCEncodeExpr
2876// * AddrLabelExpr
2877// * BlockExpr
2878// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002879// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002880// * Any Expr, with a CallIndex indicating the function in which the temporary
2881// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002882// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002883//===----------------------------------------------------------------------===//
2884namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002885class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002886 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002887public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002888 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2889 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002890
Richard Smithc49bd112011-10-28 17:51:58 +00002891 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2892
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002893 bool VisitDeclRefExpr(const DeclRefExpr *E);
2894 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002895 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002896 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2897 bool VisitMemberExpr(const MemberExpr *E);
2898 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2899 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002900 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichete275a182012-04-16 04:08:35 +00002901 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002902 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2903 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002904 bool VisitUnaryReal(const UnaryOperator *E);
2905 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002906
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002907 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002908 switch (E->getCastKind()) {
2909 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002910 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002911
Eli Friedmandb924222011-10-11 00:13:24 +00002912 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002913 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002914 if (!Visit(E->getSubExpr()))
2915 return false;
2916 Result.Designator.setInvalid();
2917 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002918
Richard Smithe24f5fc2011-11-17 22:56:20 +00002919 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002920 if (!Visit(E->getSubExpr()))
2921 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002922 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002923 }
2924 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002925};
2926} // end anonymous namespace
2927
Richard Smithc49bd112011-10-28 17:51:58 +00002928/// Evaluate an expression as an lvalue. This can be legitimately called on
2929/// expressions which are not glvalues, in a few cases:
2930/// * function designators in C,
2931/// * "extern void" objects,
2932/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002933static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002934 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2935 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2936 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002937 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002938}
2939
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002940bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002941 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2942 return Success(FD);
2943 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002944 return VisitVarDecl(E, VD);
2945 return Error(E);
2946}
Richard Smith436c8892011-10-24 23:14:33 +00002947
Richard Smithc49bd112011-10-28 17:51:58 +00002948bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002949 if (!VD->getType()->isReferenceType()) {
2950 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002951 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002952 return true;
2953 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002954 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002955 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002956
Richard Smith1aa0be82012-03-03 22:46:17 +00002957 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002958 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2959 return false;
2960 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002961}
2962
Richard Smithbd552ef2011-10-31 05:52:43 +00002963bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2964 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002965 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002966 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002967 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2968
Richard Smith83587db2012-02-15 02:18:13 +00002969 Result.set(E, Info.CurrentCall->Index);
2970 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2971 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002972 }
2973
2974 // Materialization of an lvalue temporary occurs when we need to force a copy
2975 // (for instance, if it's a bitfield).
2976 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2977 if (!Visit(E->GetTemporaryExpr()))
2978 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002979 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002980 Info.CurrentCall->Temporaries[E]))
2981 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002982 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002983 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002984}
2985
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002986bool
2987LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002988 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2989 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2990 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002991 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002992}
2993
Richard Smith47d21452011-12-27 12:18:28 +00002994bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2995 if (E->isTypeOperand())
2996 return Success(E);
2997 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2998 if (RD && RD->isPolymorphic()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002999 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith47d21452011-12-27 12:18:28 +00003000 << E->getExprOperand()->getType()
3001 << E->getExprOperand()->getSourceRange();
3002 return false;
3003 }
3004 return Success(E);
3005}
3006
Francois Pichete275a182012-04-16 04:08:35 +00003007bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
3008 return Success(E);
3009}
3010
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003011bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003012 // Handle static data members.
3013 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3014 VisitIgnoredValue(E->getBase());
3015 return VisitVarDecl(E, VD);
3016 }
3017
Richard Smithd0dccea2011-10-28 22:34:42 +00003018 // Handle static member functions.
3019 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3020 if (MD->isStatic()) {
3021 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003022 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00003023 }
3024 }
3025
Richard Smith180f4792011-11-10 06:34:14 +00003026 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00003027 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003028}
3029
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003030bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003031 // FIXME: Deal with vectors as array subscript bases.
3032 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003033 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003034
Anders Carlsson3068d112008-11-16 19:01:22 +00003035 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003036 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003037
Anders Carlsson3068d112008-11-16 19:01:22 +00003038 APSInt Index;
3039 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003040 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003041 int64_t IndexValue
3042 = Index.isSigned() ? Index.getSExtValue()
3043 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003044
Richard Smithb4e85ed2012-01-06 16:39:00 +00003045 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003046}
Eli Friedman4efaa272008-11-12 09:44:48 +00003047
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003048bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003049 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003050}
3051
Richard Smith86024012012-02-18 22:04:06 +00003052bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3053 if (!Visit(E->getSubExpr()))
3054 return false;
3055 // __real is a no-op on scalar lvalues.
3056 if (E->getSubExpr()->getType()->isAnyComplexType())
3057 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3058 return true;
3059}
3060
3061bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3062 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3063 "lvalue __imag__ on scalar?");
3064 if (!Visit(E->getSubExpr()))
3065 return false;
3066 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3067 return true;
3068}
3069
Eli Friedman4efaa272008-11-12 09:44:48 +00003070//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003071// Pointer Evaluation
3072//===----------------------------------------------------------------------===//
3073
Anders Carlssonc754aa62008-07-08 05:13:58 +00003074namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003075class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003076 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003077 LValue &Result;
3078
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003079 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003080 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003081 return true;
3082 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003083public:
Mike Stump1eb44332009-09-09 15:08:12 +00003084
John McCallefdb83e2010-05-07 21:00:08 +00003085 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003086 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003087
Richard Smith1aa0be82012-03-03 22:46:17 +00003088 bool Success(const APValue &V, const Expr *E) {
3089 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003090 return true;
3091 }
Richard Smith51201882011-12-30 21:15:51 +00003092 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003093 return Success((Expr*)0);
3094 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003095
John McCallefdb83e2010-05-07 21:00:08 +00003096 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003097 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003098 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003099 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003100 { return Success(E); }
Patrick Beardeb382ec2012-04-19 00:25:12 +00003101 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003102 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003103 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003104 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003105 bool VisitCallExpr(const CallExpr *E);
3106 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003107 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003108 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003109 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003110 }
Richard Smith180f4792011-11-10 06:34:14 +00003111 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3112 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003113 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003114 Result = *Info.CurrentCall->This;
3115 return true;
3116 }
John McCall56ca35d2011-02-17 10:25:35 +00003117
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003118 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003119};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003120} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003121
John McCallefdb83e2010-05-07 21:00:08 +00003122static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003123 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003124 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003125}
3126
John McCallefdb83e2010-05-07 21:00:08 +00003127bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003128 if (E->getOpcode() != BO_Add &&
3129 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003130 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003132 const Expr *PExp = E->getLHS();
3133 const Expr *IExp = E->getRHS();
3134 if (IExp->getType()->isPointerType())
3135 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003136
Richard Smith745f5142012-01-27 01:14:48 +00003137 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3138 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003139 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003140
John McCallefdb83e2010-05-07 21:00:08 +00003141 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003142 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003143 return false;
3144 int64_t AdditionalOffset
3145 = Offset.isSigned() ? Offset.getSExtValue()
3146 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003147 if (E->getOpcode() == BO_Sub)
3148 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003149
Richard Smith180f4792011-11-10 06:34:14 +00003150 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003151 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3152 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003153}
Eli Friedman4efaa272008-11-12 09:44:48 +00003154
John McCallefdb83e2010-05-07 21:00:08 +00003155bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3156 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003157}
Mike Stump1eb44332009-09-09 15:08:12 +00003158
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003159bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3160 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003161
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003162 switch (E->getCastKind()) {
3163 default:
3164 break;
3165
John McCall2de56d12010-08-25 11:45:40 +00003166 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003167 case CK_CPointerToObjCPointerCast:
3168 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003169 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003170 if (!Visit(SubExpr))
3171 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003172 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3173 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3174 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003175 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003176 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003177 if (SubExpr->getType()->isVoidPointerType())
3178 CCEDiag(E, diag::note_constexpr_invalid_cast)
3179 << 3 << SubExpr->getType();
3180 else
3181 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3182 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003183 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003184
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003185 case CK_DerivedToBase:
3186 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003187 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003188 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003189 if (!Result.Base && Result.Offset.isZero())
3190 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003191
Richard Smith180f4792011-11-10 06:34:14 +00003192 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003193 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003194 QualType Type =
3195 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003196
Richard Smith180f4792011-11-10 06:34:14 +00003197 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003198 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003199 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3200 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003201 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003202 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003203 }
3204
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003205 return true;
3206 }
3207
Richard Smithe24f5fc2011-11-17 22:56:20 +00003208 case CK_BaseToDerived:
3209 if (!Visit(E->getSubExpr()))
3210 return false;
3211 if (!Result.Base && Result.Offset.isZero())
3212 return true;
3213 return HandleBaseToDerivedCast(Info, E, Result);
3214
Richard Smith47a1eed2011-10-29 20:57:55 +00003215 case CK_NullToPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003216 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003217 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003218
John McCall2de56d12010-08-25 11:45:40 +00003219 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003220 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3221
Richard Smith1aa0be82012-03-03 22:46:17 +00003222 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003223 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003224 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003225
John McCallefdb83e2010-05-07 21:00:08 +00003226 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003227 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3228 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003229 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003230 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003231 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003232 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003233 return true;
3234 } else {
3235 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003236 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003237 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003238 }
3239 }
John McCall2de56d12010-08-25 11:45:40 +00003240 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003241 if (SubExpr->isGLValue()) {
3242 if (!EvaluateLValue(SubExpr, Result, Info))
3243 return false;
3244 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003245 Result.set(SubExpr, Info.CurrentCall->Index);
3246 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3247 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003248 return false;
3249 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003250 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003251 if (const ConstantArrayType *CAT
3252 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3253 Result.addArray(Info, E, CAT);
3254 else
3255 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003256 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003257
John McCall2de56d12010-08-25 11:45:40 +00003258 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003259 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003260 }
3261
Richard Smithc49bd112011-10-28 17:51:58 +00003262 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003263}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003264
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003265bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003266 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003267 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003268
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003269 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003270}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003271
3272//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003273// Member Pointer Evaluation
3274//===----------------------------------------------------------------------===//
3275
3276namespace {
3277class MemberPointerExprEvaluator
3278 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3279 MemberPtr &Result;
3280
3281 bool Success(const ValueDecl *D) {
3282 Result = MemberPtr(D);
3283 return true;
3284 }
3285public:
3286
3287 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3288 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3289
Richard Smith1aa0be82012-03-03 22:46:17 +00003290 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003291 Result.setFrom(V);
3292 return true;
3293 }
Richard Smith51201882011-12-30 21:15:51 +00003294 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003295 return Success((const ValueDecl*)0);
3296 }
3297
3298 bool VisitCastExpr(const CastExpr *E);
3299 bool VisitUnaryAddrOf(const UnaryOperator *E);
3300};
3301} // end anonymous namespace
3302
3303static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3304 EvalInfo &Info) {
3305 assert(E->isRValue() && E->getType()->isMemberPointerType());
3306 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3307}
3308
3309bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3310 switch (E->getCastKind()) {
3311 default:
3312 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3313
3314 case CK_NullToMemberPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003315 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003316 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003317
3318 case CK_BaseToDerivedMemberPointer: {
3319 if (!Visit(E->getSubExpr()))
3320 return false;
3321 if (E->path_empty())
3322 return true;
3323 // Base-to-derived member pointer casts store the path in derived-to-base
3324 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3325 // the wrong end of the derived->base arc, so stagger the path by one class.
3326 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3327 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3328 PathI != PathE; ++PathI) {
3329 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3330 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3331 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003332 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003333 }
3334 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3335 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003336 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003337 return true;
3338 }
3339
3340 case CK_DerivedToBaseMemberPointer:
3341 if (!Visit(E->getSubExpr()))
3342 return false;
3343 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3344 PathE = E->path_end(); PathI != PathE; ++PathI) {
3345 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3346 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3347 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003348 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003349 }
3350 return true;
3351 }
3352}
3353
3354bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3355 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3356 // member can be formed.
3357 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3358}
3359
3360//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003361// Record Evaluation
3362//===----------------------------------------------------------------------===//
3363
3364namespace {
3365 class RecordExprEvaluator
3366 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3367 const LValue &This;
3368 APValue &Result;
3369 public:
3370
3371 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3372 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3373
Richard Smith1aa0be82012-03-03 22:46:17 +00003374 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003375 Result = V;
3376 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003377 }
Richard Smith51201882011-12-30 21:15:51 +00003378 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003379
Richard Smith59efe262011-11-11 04:05:33 +00003380 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003381 bool VisitInitListExpr(const InitListExpr *E);
3382 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3383 };
3384}
3385
Richard Smith51201882011-12-30 21:15:51 +00003386/// Perform zero-initialization on an object of non-union class type.
3387/// C++11 [dcl.init]p5:
3388/// To zero-initialize an object or reference of type T means:
3389/// [...]
3390/// -- if T is a (possibly cv-qualified) non-union class type,
3391/// each non-static data member and each base-class subobject is
3392/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003393static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3394 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003395 const LValue &This, APValue &Result) {
3396 assert(!RD->isUnion() && "Expected non-union class type");
3397 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3398 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3399 std::distance(RD->field_begin(), RD->field_end()));
3400
John McCall8d59dee2012-05-01 00:38:49 +00003401 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003402 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3403
3404 if (CD) {
3405 unsigned Index = 0;
3406 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003407 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003408 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3409 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003410 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3411 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003412 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003413 Result.getStructBase(Index)))
3414 return false;
3415 }
3416 }
3417
Richard Smithb4e85ed2012-01-06 16:39:00 +00003418 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3419 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003420 // -- if T is a reference type, no initialization is performed.
David Blaikie262bc182012-04-30 02:36:29 +00003421 if (I->getType()->isReferenceType())
Richard Smith51201882011-12-30 21:15:51 +00003422 continue;
3423
3424 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003425 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003426 return false;
Richard Smith51201882011-12-30 21:15:51 +00003427
David Blaikie262bc182012-04-30 02:36:29 +00003428 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003429 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003430 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003431 return false;
3432 }
3433
3434 return true;
3435}
3436
3437bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3438 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003439 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003440 if (RD->isUnion()) {
3441 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3442 // object's first non-static named data member is zero-initialized
3443 RecordDecl::field_iterator I = RD->field_begin();
3444 if (I == RD->field_end()) {
3445 Result = APValue((const FieldDecl*)0);
3446 return true;
3447 }
3448
3449 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003450 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCall8d59dee2012-05-01 00:38:49 +00003451 return false;
David Blaikie581deb32012-06-06 20:45:41 +00003452 Result = APValue(*I);
David Blaikie262bc182012-04-30 02:36:29 +00003453 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003454 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003455 }
3456
Richard Smithce582fe2012-02-17 00:44:16 +00003457 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003458 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003459 return false;
3460 }
3461
Richard Smithb4e85ed2012-01-06 16:39:00 +00003462 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003463}
3464
Richard Smith59efe262011-11-11 04:05:33 +00003465bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3466 switch (E->getCastKind()) {
3467 default:
3468 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3469
3470 case CK_ConstructorConversion:
3471 return Visit(E->getSubExpr());
3472
3473 case CK_DerivedToBase:
3474 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003475 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003476 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003477 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003478 if (!DerivedObject.isStruct())
3479 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003480
3481 // Derived-to-base rvalue conversion: just slice off the derived part.
3482 APValue *Value = &DerivedObject;
3483 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3484 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3485 PathE = E->path_end(); PathI != PathE; ++PathI) {
3486 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3487 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3488 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3489 RD = Base;
3490 }
3491 Result = *Value;
3492 return true;
3493 }
3494 }
3495}
3496
Richard Smith180f4792011-11-10 06:34:14 +00003497bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003498 // Cannot constant-evaluate std::initializer_list inits.
3499 if (E->initializesStdInitializerList())
3500 return false;
3501
Richard Smith180f4792011-11-10 06:34:14 +00003502 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003503 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00003504 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3505
3506 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003507 const FieldDecl *Field = E->getInitializedFieldInUnion();
3508 Result = APValue(Field);
3509 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003510 return true;
Richard Smithec789162012-01-12 18:54:33 +00003511
3512 // If the initializer list for a union does not contain any elements, the
3513 // first element of the union is value-initialized.
3514 ImplicitValueInitExpr VIE(Field->getType());
3515 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3516
Richard Smith180f4792011-11-10 06:34:14 +00003517 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003518 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3519 return false;
Richard Smith83587db2012-02-15 02:18:13 +00003520 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003521 }
3522
3523 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3524 "initializer list for class with base classes");
3525 Result = APValue(APValue::UninitStruct(), 0,
3526 std::distance(RD->field_begin(), RD->field_end()));
3527 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003528 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003529 for (RecordDecl::field_iterator Field = RD->field_begin(),
3530 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3531 // Anonymous bit-fields are not considered members of the class for
3532 // purposes of aggregate initialization.
3533 if (Field->isUnnamedBitfield())
3534 continue;
3535
3536 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003537
Richard Smith745f5142012-01-27 01:14:48 +00003538 bool HaveInit = ElementNo < E->getNumInits();
3539
3540 // FIXME: Diagnostics here should point to the end of the initializer
3541 // list, not the start.
John McCall8d59dee2012-05-01 00:38:49 +00003542 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie581deb32012-06-06 20:45:41 +00003543 Subobject, *Field, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003544 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003545
3546 // Perform an implicit value-initialization for members beyond the end of
3547 // the initializer list.
3548 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3549
Richard Smith83587db2012-02-15 02:18:13 +00003550 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003551 Result.getStructField(Field->getFieldIndex()),
Richard Smith745f5142012-01-27 01:14:48 +00003552 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3553 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003554 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003555 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003556 }
3557 }
3558
Richard Smith745f5142012-01-27 01:14:48 +00003559 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003560}
3561
3562bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3563 const CXXConstructorDecl *FD = E->getConstructor();
John McCall1de9d7d2012-04-26 18:10:01 +00003564 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3565
Richard Smith51201882011-12-30 21:15:51 +00003566 bool ZeroInit = E->requiresZeroInitialization();
3567 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003568 // If we've already performed zero-initialization, we're already done.
3569 if (!Result.isUninit())
3570 return true;
3571
Richard Smith51201882011-12-30 21:15:51 +00003572 if (ZeroInit)
3573 return ZeroInitialization(E);
3574
Richard Smith61802452011-12-22 02:22:31 +00003575 const CXXRecordDecl *RD = FD->getParent();
3576 if (RD->isUnion())
3577 Result = APValue((FieldDecl*)0);
3578 else
3579 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3580 std::distance(RD->field_begin(), RD->field_end()));
3581 return true;
3582 }
3583
Richard Smith180f4792011-11-10 06:34:14 +00003584 const FunctionDecl *Definition = 0;
3585 FD->getBody(Definition);
3586
Richard Smithc1c5f272011-12-13 06:39:58 +00003587 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3588 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003589
Richard Smith610a60c2012-01-10 04:32:03 +00003590 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003591 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003592 if (const MaterializeTemporaryExpr *ME
3593 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3594 return Visit(ME->GetTemporaryExpr());
3595
Richard Smith51201882011-12-30 21:15:51 +00003596 if (ZeroInit && !ZeroInitialization(E))
3597 return false;
3598
Richard Smith180f4792011-11-10 06:34:14 +00003599 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003600 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003601 cast<CXXConstructorDecl>(Definition), Info,
3602 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003603}
3604
3605static bool EvaluateRecord(const Expr *E, const LValue &This,
3606 APValue &Result, EvalInfo &Info) {
3607 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003608 "can't evaluate expression as a record rvalue");
3609 return RecordExprEvaluator(Info, This, Result).Visit(E);
3610}
3611
3612//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003613// Temporary Evaluation
3614//
3615// Temporaries are represented in the AST as rvalues, but generally behave like
3616// lvalues. The full-object of which the temporary is a subobject is implicitly
3617// materialized so that a reference can bind to it.
3618//===----------------------------------------------------------------------===//
3619namespace {
3620class TemporaryExprEvaluator
3621 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3622public:
3623 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3624 LValueExprEvaluatorBaseTy(Info, Result) {}
3625
3626 /// Visit an expression which constructs the value of this temporary.
3627 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003628 Result.set(E, Info.CurrentCall->Index);
3629 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003630 }
3631
3632 bool VisitCastExpr(const CastExpr *E) {
3633 switch (E->getCastKind()) {
3634 default:
3635 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3636
3637 case CK_ConstructorConversion:
3638 return VisitConstructExpr(E->getSubExpr());
3639 }
3640 }
3641 bool VisitInitListExpr(const InitListExpr *E) {
3642 return VisitConstructExpr(E);
3643 }
3644 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3645 return VisitConstructExpr(E);
3646 }
3647 bool VisitCallExpr(const CallExpr *E) {
3648 return VisitConstructExpr(E);
3649 }
3650};
3651} // end anonymous namespace
3652
3653/// Evaluate an expression of record type as a temporary.
3654static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003655 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003656 return TemporaryExprEvaluator(Info, Result).Visit(E);
3657}
3658
3659//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003660// Vector Evaluation
3661//===----------------------------------------------------------------------===//
3662
3663namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003664 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003665 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3666 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003667 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003668
Richard Smith07fc6572011-10-22 21:10:00 +00003669 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3670 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003671
Richard Smith07fc6572011-10-22 21:10:00 +00003672 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3673 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3674 // FIXME: remove this APValue copy.
3675 Result = APValue(V.data(), V.size());
3676 return true;
3677 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003678 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003679 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003680 Result = V;
3681 return true;
3682 }
Richard Smith51201882011-12-30 21:15:51 +00003683 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003684
Richard Smith07fc6572011-10-22 21:10:00 +00003685 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003686 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003687 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003688 bool VisitInitListExpr(const InitListExpr *E);
3689 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003690 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003691 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003692 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003693 };
3694} // end anonymous namespace
3695
3696static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003697 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003698 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003699}
3700
Richard Smith07fc6572011-10-22 21:10:00 +00003701bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3702 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003703 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003704
Richard Smithd62ca372011-12-06 22:44:34 +00003705 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003706 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003707
Eli Friedman46a52322011-03-25 00:43:55 +00003708 switch (E->getCastKind()) {
3709 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003710 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003711 if (SETy->isIntegerType()) {
3712 APSInt IntResult;
3713 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003714 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003715 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003716 } else if (SETy->isRealFloatingType()) {
3717 APFloat F(0.0);
3718 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003719 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003720 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003721 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003722 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003723 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003724
3725 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003726 SmallVector<APValue, 4> Elts(NElts, Val);
3727 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003728 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003729 case CK_BitCast: {
3730 // Evaluate the operand into an APInt we can extract from.
3731 llvm::APInt SValInt;
3732 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3733 return false;
3734 // Extract the elements
3735 QualType EltTy = VTy->getElementType();
3736 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3737 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3738 SmallVector<APValue, 4> Elts;
3739 if (EltTy->isRealFloatingType()) {
3740 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3741 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3742 unsigned FloatEltSize = EltSize;
3743 if (&Sem == &APFloat::x87DoubleExtended)
3744 FloatEltSize = 80;
3745 for (unsigned i = 0; i < NElts; i++) {
3746 llvm::APInt Elt;
3747 if (BigEndian)
3748 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3749 else
3750 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3751 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3752 }
3753 } else if (EltTy->isIntegerType()) {
3754 for (unsigned i = 0; i < NElts; i++) {
3755 llvm::APInt Elt;
3756 if (BigEndian)
3757 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3758 else
3759 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3760 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3761 }
3762 } else {
3763 return Error(E);
3764 }
3765 return Success(Elts, E);
3766 }
Eli Friedman46a52322011-03-25 00:43:55 +00003767 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003768 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003769 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003770}
3771
Richard Smith07fc6572011-10-22 21:10:00 +00003772bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003773VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003774 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003775 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003776 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003777
Nate Begeman59b5da62009-01-18 03:20:47 +00003778 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003779 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003780
Eli Friedman3edd5a92012-01-03 23:24:20 +00003781 // The number of initializers can be less than the number of
3782 // vector elements. For OpenCL, this can be due to nested vector
3783 // initialization. For GCC compatibility, missing trailing elements
3784 // should be initialized with zeroes.
3785 unsigned CountInits = 0, CountElts = 0;
3786 while (CountElts < NumElements) {
3787 // Handle nested vector initialization.
3788 if (CountInits < NumInits
3789 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3790 APValue v;
3791 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3792 return Error(E);
3793 unsigned vlen = v.getVectorLength();
3794 for (unsigned j = 0; j < vlen; j++)
3795 Elements.push_back(v.getVectorElt(j));
3796 CountElts += vlen;
3797 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003798 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003799 if (CountInits < NumInits) {
3800 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003801 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003802 } else // trailing integer zero.
3803 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3804 Elements.push_back(APValue(sInt));
3805 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003806 } else {
3807 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003808 if (CountInits < NumInits) {
3809 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003810 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003811 } else // trailing float zero.
3812 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3813 Elements.push_back(APValue(f));
3814 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003815 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003816 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003817 }
Richard Smith07fc6572011-10-22 21:10:00 +00003818 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003819}
3820
Richard Smith07fc6572011-10-22 21:10:00 +00003821bool
Richard Smith51201882011-12-30 21:15:51 +00003822VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003823 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003824 QualType EltTy = VT->getElementType();
3825 APValue ZeroElement;
3826 if (EltTy->isIntegerType())
3827 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3828 else
3829 ZeroElement =
3830 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3831
Chris Lattner5f9e2722011-07-23 10:55:15 +00003832 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003833 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003834}
3835
Richard Smith07fc6572011-10-22 21:10:00 +00003836bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003837 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003838 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003839}
3840
Nate Begeman59b5da62009-01-18 03:20:47 +00003841//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003842// Array Evaluation
3843//===----------------------------------------------------------------------===//
3844
3845namespace {
3846 class ArrayExprEvaluator
3847 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003848 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003849 APValue &Result;
3850 public:
3851
Richard Smith180f4792011-11-10 06:34:14 +00003852 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3853 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003854
3855 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003856 assert((V.isArray() || V.isLValue()) &&
3857 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003858 Result = V;
3859 return true;
3860 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003861
Richard Smith51201882011-12-30 21:15:51 +00003862 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003863 const ConstantArrayType *CAT =
3864 Info.Ctx.getAsConstantArrayType(E->getType());
3865 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003866 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003867
3868 Result = APValue(APValue::UninitArray(), 0,
3869 CAT->getSize().getZExtValue());
3870 if (!Result.hasArrayFiller()) return true;
3871
Richard Smith51201882011-12-30 21:15:51 +00003872 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003873 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003874 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003875 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003876 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003877 }
3878
Richard Smithcc5d4f62011-11-07 09:22:26 +00003879 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003880 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003881 };
3882} // end anonymous namespace
3883
Richard Smith180f4792011-11-10 06:34:14 +00003884static bool EvaluateArray(const Expr *E, const LValue &This,
3885 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003886 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003887 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003888}
3889
3890bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3891 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3892 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003893 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003894
Richard Smith974c5f92011-12-22 01:07:19 +00003895 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3896 // an appropriately-typed string literal enclosed in braces.
Richard Smithfe587202012-04-15 02:50:59 +00003897 if (E->isStringLiteralInit()) {
Richard Smith974c5f92011-12-22 01:07:19 +00003898 LValue LV;
3899 if (!EvaluateLValue(E->getInit(0), LV, Info))
3900 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003901 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003902 LV.moveInto(Val);
3903 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003904 }
3905
Richard Smith745f5142012-01-27 01:14:48 +00003906 bool Success = true;
3907
Richard Smithcc5d4f62011-11-07 09:22:26 +00003908 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3909 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003910 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003911 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003912 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003913 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003914 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003915 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3916 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003917 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3918 CAT->getElementType(), 1)) {
3919 if (!Info.keepEvaluatingAfterFailure())
3920 return false;
3921 Success = false;
3922 }
Richard Smith180f4792011-11-10 06:34:14 +00003923 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003924
Richard Smith745f5142012-01-27 01:14:48 +00003925 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003926 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003927 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3928 // but sometimes does:
3929 // struct S { constexpr S() : p(&p) {} void *p; };
3930 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003931 return EvaluateInPlace(Result.getArrayFiller(), Info,
3932 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003933}
3934
Richard Smithe24f5fc2011-11-17 22:56:20 +00003935bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3936 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3937 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003938 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003939
Richard Smithec789162012-01-12 18:54:33 +00003940 bool HadZeroInit = !Result.isUninit();
3941 if (!HadZeroInit)
3942 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003943 if (!Result.hasArrayFiller())
3944 return true;
3945
3946 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) {
3954 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003955 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003956 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003957 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003958 }
3959
Richard Smith61802452011-12-22 02:22:31 +00003960 const CXXRecordDecl *RD = FD->getParent();
3961 if (RD->isUnion())
3962 Result.getArrayFiller() = APValue((FieldDecl*)0);
3963 else
3964 Result.getArrayFiller() =
3965 APValue(APValue::UninitStruct(), RD->getNumBases(),
3966 std::distance(RD->field_begin(), RD->field_end()));
3967 return true;
3968 }
3969
Richard Smithe24f5fc2011-11-17 22:56:20 +00003970 const FunctionDecl *Definition = 0;
3971 FD->getBody(Definition);
3972
Richard Smithc1c5f272011-12-13 06:39:58 +00003973 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3974 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003975
3976 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3977 // but sometimes does:
3978 // struct S { constexpr S() : p(&p) {} void *p; };
3979 // S s[10];
3980 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003981 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003982
Richard Smithec789162012-01-12 18:54:33 +00003983 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003984 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003985 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003986 return false;
3987 }
3988
Richard Smithe24f5fc2011-11-17 22:56:20 +00003989 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003990 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003991 cast<CXXConstructorDecl>(Definition),
3992 Info, Result.getArrayFiller());
3993}
3994
Richard Smithcc5d4f62011-11-07 09:22:26 +00003995//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003996// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003997//
3998// As a GNU extension, we support casting pointers to sufficiently-wide integer
3999// types and back in constant folding. Integer values are thus represented
4000// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004001//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004002
4003namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004004class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004005 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00004006 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00004007public:
Richard Smith1aa0be82012-03-03 22:46:17 +00004008 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004009 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004010
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004011 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004012 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004013 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004014 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004015 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004016 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004017 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004018 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004019 return true;
4020 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004021 bool Success(const llvm::APSInt &SI, const Expr *E) {
4022 return Success(SI, E, Result);
4023 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004024
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004025 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004026 assert(E->getType()->isIntegralOrEnumerationType() &&
4027 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004028 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004029 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004030 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00004031 Result.getInt().setIsUnsigned(
4032 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00004033 return true;
4034 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004035 bool Success(const llvm::APInt &I, const Expr *E) {
4036 return Success(I, E, Result);
4037 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00004038
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004039 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004040 assert(E->getType()->isIntegralOrEnumerationType() &&
4041 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004042 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00004043 return true;
4044 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004045 bool Success(uint64_t Value, const Expr *E) {
4046 return Success(Value, E, Result);
4047 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00004048
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004049 bool Success(CharUnits Size, const Expr *E) {
4050 return Success(Size.getQuantity(), E);
4051 }
4052
Richard Smith1aa0be82012-03-03 22:46:17 +00004053 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00004054 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00004055 Result = V;
4056 return true;
4057 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004058 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00004059 }
Mike Stump1eb44332009-09-09 15:08:12 +00004060
Richard Smith51201882011-12-30 21:15:51 +00004061 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00004062
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004063 //===--------------------------------------------------------------------===//
4064 // Visitor Methods
4065 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004066
Chris Lattner4c4867e2008-07-12 00:38:25 +00004067 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004068 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004069 }
4070 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004071 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004072 }
Eli Friedman04309752009-11-24 05:28:59 +00004073
4074 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4075 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004076 if (CheckReferencedDecl(E, E->getDecl()))
4077 return true;
4078
4079 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004080 }
4081 bool VisitMemberExpr(const MemberExpr *E) {
4082 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004083 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004084 return true;
4085 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004086
4087 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004088 }
4089
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004090 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004091 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004092 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004093 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004094
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004095 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004096 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004097
Anders Carlsson3068d112008-11-16 19:01:22 +00004098 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004099 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004100 }
Mike Stump1eb44332009-09-09 15:08:12 +00004101
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004102 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4103 return Success(E->getValue(), E);
4104 }
4105
Richard Smithf10d9172011-10-11 21:43:33 +00004106 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004107 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004108 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004109 }
4110
Sebastian Redl64b45f72009-01-05 20:52:13 +00004111 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004112 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004113 }
4114
Francois Pichet6ad6f282010-12-07 00:08:36 +00004115 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4116 return Success(E->getValue(), E);
4117 }
4118
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004119 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4120 return Success(E->getValue(), E);
4121 }
4122
John Wiegley21ff2e52011-04-28 00:16:57 +00004123 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4124 return Success(E->getValue(), E);
4125 }
4126
John Wiegley55262202011-04-25 06:54:41 +00004127 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4128 return Success(E->getValue(), E);
4129 }
4130
Eli Friedman722c7172009-02-28 03:59:05 +00004131 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004132 bool VisitUnaryImag(const UnaryOperator *E);
4133
Sebastian Redl295995c2010-09-10 20:55:47 +00004134 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004135 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004136
Chris Lattnerfcee0012008-07-11 21:24:13 +00004137private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004138 CharUnits GetAlignOfExpr(const Expr *E);
4139 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004140 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004141 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004142 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004143};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004144} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004145
Richard Smithc49bd112011-10-28 17:51:58 +00004146/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4147/// produce either the integer value or a pointer.
4148///
4149/// GCC has a heinous extension which folds casts between pointer types and
4150/// pointer-sized integral types. We support this by allowing the evaluation of
4151/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4152/// Some simple arithmetic on such values is supported (they are treated much
4153/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004154static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004155 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004156 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004157 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004158}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004159
Richard Smithf48fdb02011-12-09 22:58:01 +00004160static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004161 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004162 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004163 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004164 if (!Val.isInt()) {
4165 // FIXME: It would be better to produce the diagnostic for casting
4166 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004167 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004168 return false;
4169 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004170 Result = Val.getInt();
4171 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004172}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004173
Richard Smithf48fdb02011-12-09 22:58:01 +00004174/// Check whether the given declaration can be directly converted to an integral
4175/// rvalue. If not, no diagnostic is produced; there are other things we can
4176/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004177bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004178 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004179 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004180 // Check for signedness/width mismatches between E type and ECD value.
4181 bool SameSign = (ECD->getInitVal().isSigned()
4182 == E->getType()->isSignedIntegerOrEnumerationType());
4183 bool SameWidth = (ECD->getInitVal().getBitWidth()
4184 == Info.Ctx.getIntWidth(E->getType()));
4185 if (SameSign && SameWidth)
4186 return Success(ECD->getInitVal(), E);
4187 else {
4188 // Get rid of mismatch (otherwise Success assertions will fail)
4189 // by computing a new value matching the type of E.
4190 llvm::APSInt Val = ECD->getInitVal();
4191 if (!SameSign)
4192 Val.setIsSigned(!ECD->getInitVal().isSigned());
4193 if (!SameWidth)
4194 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4195 return Success(Val, E);
4196 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004197 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004198 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004199}
4200
Chris Lattnera4d55d82008-10-06 06:40:35 +00004201/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4202/// as GCC.
4203static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4204 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004205 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004206 enum gcc_type_class {
4207 no_type_class = -1,
4208 void_type_class, integer_type_class, char_type_class,
4209 enumeral_type_class, boolean_type_class,
4210 pointer_type_class, reference_type_class, offset_type_class,
4211 real_type_class, complex_type_class,
4212 function_type_class, method_type_class,
4213 record_type_class, union_type_class,
4214 array_type_class, string_type_class,
4215 lang_type_class
4216 };
Mike Stump1eb44332009-09-09 15:08:12 +00004217
4218 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004219 // ideal, however it is what gcc does.
4220 if (E->getNumArgs() == 0)
4221 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004222
Chris Lattnera4d55d82008-10-06 06:40:35 +00004223 QualType ArgTy = E->getArg(0)->getType();
4224 if (ArgTy->isVoidType())
4225 return void_type_class;
4226 else if (ArgTy->isEnumeralType())
4227 return enumeral_type_class;
4228 else if (ArgTy->isBooleanType())
4229 return boolean_type_class;
4230 else if (ArgTy->isCharType())
4231 return string_type_class; // gcc doesn't appear to use char_type_class
4232 else if (ArgTy->isIntegerType())
4233 return integer_type_class;
4234 else if (ArgTy->isPointerType())
4235 return pointer_type_class;
4236 else if (ArgTy->isReferenceType())
4237 return reference_type_class;
4238 else if (ArgTy->isRealType())
4239 return real_type_class;
4240 else if (ArgTy->isComplexType())
4241 return complex_type_class;
4242 else if (ArgTy->isFunctionType())
4243 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004244 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004245 return record_type_class;
4246 else if (ArgTy->isUnionType())
4247 return union_type_class;
4248 else if (ArgTy->isArrayType())
4249 return array_type_class;
4250 else if (ArgTy->isUnionType())
4251 return union_type_class;
4252 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004253 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004254}
4255
Richard Smith80d4b552011-12-28 19:48:30 +00004256/// EvaluateBuiltinConstantPForLValue - Determine the result of
4257/// __builtin_constant_p when applied to the given lvalue.
4258///
4259/// An lvalue is only "constant" if it is a pointer or reference to the first
4260/// character of a string literal.
4261template<typename LValue>
4262static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004263 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004264 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4265}
4266
4267/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4268/// GCC as we can manage.
4269static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4270 QualType ArgType = Arg->getType();
4271
4272 // __builtin_constant_p always has one operand. The rules which gcc follows
4273 // are not precisely documented, but are as follows:
4274 //
4275 // - If the operand is of integral, floating, complex or enumeration type,
4276 // and can be folded to a known value of that type, it returns 1.
4277 // - If the operand and can be folded to a pointer to the first character
4278 // of a string literal (or such a pointer cast to an integral type), it
4279 // returns 1.
4280 //
4281 // Otherwise, it returns 0.
4282 //
4283 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4284 // its support for this does not currently work.
4285 if (ArgType->isIntegralOrEnumerationType()) {
4286 Expr::EvalResult Result;
4287 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4288 return false;
4289
4290 APValue &V = Result.Val;
4291 if (V.getKind() == APValue::Int)
4292 return true;
4293
4294 return EvaluateBuiltinConstantPForLValue(V);
4295 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4296 return Arg->isEvaluatable(Ctx);
4297 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4298 LValue LV;
4299 Expr::EvalStatus Status;
4300 EvalInfo Info(Ctx, Status);
4301 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4302 : EvaluatePointer(Arg, LV, Info)) &&
4303 !Status.HasSideEffects)
4304 return EvaluateBuiltinConstantPForLValue(LV);
4305 }
4306
4307 // Anything else isn't considered to be sufficiently constant.
4308 return false;
4309}
4310
John McCall42c8f872010-05-10 23:27:23 +00004311/// Retrieves the "underlying object type" of the given expression,
4312/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004313QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4314 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4315 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004316 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004317 } else if (const Expr *E = B.get<const Expr*>()) {
4318 if (isa<CompoundLiteralExpr>(E))
4319 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004320 }
4321
4322 return QualType();
4323}
4324
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004325bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004326 LValue Base;
Richard Smithc6794852012-05-23 04:13:20 +00004327
4328 {
4329 // The operand of __builtin_object_size is never evaluated for side-effects.
4330 // If there are any, but we can determine the pointed-to object anyway, then
4331 // ignore the side-effects.
4332 SpeculativeEvaluationRAII SpeculativeEval(Info);
4333 if (!EvaluatePointer(E->getArg(0), Base, Info))
4334 return false;
4335 }
John McCall42c8f872010-05-10 23:27:23 +00004336
4337 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004338 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004339
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004340 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004341 if (T.isNull() ||
4342 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004343 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004344 T->isVariablyModifiedType() ||
4345 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004346 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004347
4348 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4349 CharUnits Offset = Base.getLValueOffset();
4350
4351 if (!Offset.isNegative() && Offset <= Size)
4352 Size -= Offset;
4353 else
4354 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004355 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004356}
4357
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004358bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith2c39d712012-04-13 00:45:38 +00004359 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004360 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004361 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004362
4363 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004364 if (TryEvaluateBuiltinObjectSize(E))
4365 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004366
Eric Christopherb2aaf512010-01-19 22:58:35 +00004367 // If evaluating the argument has side-effects we can't determine
Richard Smithc6794852012-05-23 04:13:20 +00004368 // the size of the object and lower it to unknown now. CodeGen relies on
4369 // us to handle all cases where the expression has side-effects.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004370 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004371 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004372 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004373 return Success(0, E);
4374 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004375
Richard Smithc6794852012-05-23 04:13:20 +00004376 // Expression had no side effects, but we couldn't statically determine the
4377 // size of the referenced object.
Richard Smithf48fdb02011-12-09 22:58:01 +00004378 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004379 }
4380
Chris Lattner019f4e82008-10-06 05:28:25 +00004381 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004382 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004383
Richard Smith80d4b552011-12-28 19:48:30 +00004384 case Builtin::BI__builtin_constant_p:
4385 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004386
Chris Lattner21fb98e2009-09-23 06:06:36 +00004387 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004388 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004389 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004390 return Success(Operand, E);
4391 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004392
4393 case Builtin::BI__builtin_expect:
4394 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004395
Douglas Gregor5726d402010-09-10 06:27:15 +00004396 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004397 // A call to strlen is not a constant expression.
4398 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004399 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004400 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4401 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004402 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004403 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004404 case Builtin::BI__builtin_strlen:
4405 // As an extension, we support strlen() and __builtin_strlen() as constant
4406 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004407 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004408 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4409 // The string literal may have embedded null characters. Find the first
4410 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004411 StringRef Str = S->getString();
4412 StringRef::size_type Pos = Str.find(0);
4413 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004414 Str = Str.substr(0, Pos);
4415
4416 return Success(Str.size(), E);
4417 }
4418
Richard Smithf48fdb02011-12-09 22:58:01 +00004419 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004420
Richard Smith2c39d712012-04-13 00:45:38 +00004421 case Builtin::BI__atomic_always_lock_free:
Richard Smithfafbf062012-04-11 17:55:32 +00004422 case Builtin::BI__atomic_is_lock_free:
4423 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedman454b57a2011-10-17 21:44:23 +00004424 APSInt SizeVal;
4425 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4426 return false;
4427
4428 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4429 // of two less than the maximum inline atomic width, we know it is
4430 // lock-free. If the size isn't a power of two, or greater than the
4431 // maximum alignment where we promote atomics, we know it is not lock-free
4432 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4433 // the answer can only be determined at runtime; for example, 16-byte
4434 // atomics have lock-free implementations on some, but not all,
4435 // x86-64 processors.
4436
4437 // Check power-of-two.
4438 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith2c39d712012-04-13 00:45:38 +00004439 if (Size.isPowerOfTwo()) {
4440 // Check against inlining width.
4441 unsigned InlineWidthBits =
4442 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4443 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4444 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4445 Size == CharUnits::One() ||
4446 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4447 Expr::NPC_NeverValueDependent))
4448 // OK, we will inline appropriately-aligned operations of this size,
4449 // and _Atomic(T) is appropriately-aligned.
4450 return Success(1, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004451
Richard Smith2c39d712012-04-13 00:45:38 +00004452 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4453 castAs<PointerType>()->getPointeeType();
4454 if (!PointeeType->isIncompleteType() &&
4455 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4456 // OK, we will inline operations on this object.
4457 return Success(1, E);
4458 }
4459 }
4460 }
Eli Friedman454b57a2011-10-17 21:44:23 +00004461
Richard Smith2c39d712012-04-13 00:45:38 +00004462 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4463 Success(0, E) : Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004464 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004465 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004466}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004467
Richard Smith625b8072011-10-31 01:37:14 +00004468static bool HasSameBase(const LValue &A, const LValue &B) {
4469 if (!A.getLValueBase())
4470 return !B.getLValueBase();
4471 if (!B.getLValueBase())
4472 return false;
4473
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004474 if (A.getLValueBase().getOpaqueValue() !=
4475 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004476 const Decl *ADecl = GetLValueBaseDecl(A);
4477 if (!ADecl)
4478 return false;
4479 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004480 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004481 return false;
4482 }
4483
4484 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004485 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004486}
4487
Richard Smith7b48a292012-02-01 05:53:12 +00004488/// Perform the given integer operation, which is known to need at most BitWidth
4489/// bits, and check for overflow in the original type (if that type was not an
4490/// unsigned type).
4491template<typename Operation>
4492static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4493 const APSInt &LHS, const APSInt &RHS,
4494 unsigned BitWidth, Operation Op) {
4495 if (LHS.isUnsigned())
4496 return Op(LHS, RHS);
4497
4498 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4499 APSInt Result = Value.trunc(LHS.getBitWidth());
4500 if (Result.extend(BitWidth) != Value)
4501 HandleOverflow(Info, E, Value, E->getType());
4502 return Result;
4503}
4504
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004505namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00004506
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004507/// \brief Data recursive integer evaluator of certain binary operators.
4508///
4509/// We use a data recursive algorithm for binary operators so that we are able
4510/// to handle extreme cases of chained binary operators without causing stack
4511/// overflow.
4512class DataRecursiveIntBinOpEvaluator {
4513 struct EvalResult {
4514 APValue Val;
4515 bool Failed;
4516
4517 EvalResult() : Failed(false) { }
4518
4519 void swap(EvalResult &RHS) {
4520 Val.swap(RHS.Val);
4521 Failed = RHS.Failed;
4522 RHS.Failed = false;
4523 }
4524 };
4525
4526 struct Job {
4527 const Expr *E;
4528 EvalResult LHSResult; // meaningful only for binary operator expression.
4529 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4530
4531 Job() : StoredInfo(0) { }
4532 void startSpeculativeEval(EvalInfo &Info) {
4533 OldEvalStatus = Info.EvalStatus;
4534 Info.EvalStatus.Diag = 0;
4535 StoredInfo = &Info;
4536 }
4537 ~Job() {
4538 if (StoredInfo) {
4539 StoredInfo->EvalStatus = OldEvalStatus;
4540 }
4541 }
4542 private:
4543 EvalInfo *StoredInfo; // non-null if status changed.
4544 Expr::EvalStatus OldEvalStatus;
4545 };
4546
4547 SmallVector<Job, 16> Queue;
4548
4549 IntExprEvaluator &IntEval;
4550 EvalInfo &Info;
4551 APValue &FinalResult;
4552
4553public:
4554 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4555 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4556
4557 /// \brief True if \param E is a binary operator that we are going to handle
4558 /// data recursively.
4559 /// We handle binary operators that are comma, logical, or that have operands
4560 /// with integral or enumeration type.
4561 static bool shouldEnqueue(const BinaryOperator *E) {
4562 return E->getOpcode() == BO_Comma ||
4563 E->isLogicalOp() ||
4564 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4565 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00004566 }
4567
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004568 bool Traverse(const BinaryOperator *E) {
4569 enqueue(E);
4570 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00004571 while (!Queue.empty())
4572 process(PrevResult);
4573
4574 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004575
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004576 FinalResult.swap(PrevResult.Val);
4577 return true;
4578 }
4579
4580private:
4581 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4582 return IntEval.Success(Value, E, Result);
4583 }
4584 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4585 return IntEval.Success(Value, E, Result);
4586 }
4587 bool Error(const Expr *E) {
4588 return IntEval.Error(E);
4589 }
4590 bool Error(const Expr *E, diag::kind D) {
4591 return IntEval.Error(E, D);
4592 }
4593
4594 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4595 return Info.CCEDiag(E, D);
4596 }
4597
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004598 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4599 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004600 bool &SuppressRHSDiags);
4601
4602 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4603 const BinaryOperator *E, APValue &Result);
4604
4605 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4606 Result.Failed = !Evaluate(Result.Val, Info, E);
4607 if (Result.Failed)
4608 Result.Val = APValue();
4609 }
4610
Richard Trieub7783052012-03-21 23:30:30 +00004611 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004612
4613 void enqueue(const Expr *E) {
4614 E = E->IgnoreParens();
4615 Queue.resize(Queue.size()+1);
4616 Queue.back().E = E;
4617 Queue.back().Kind = Job::AnyExprKind;
4618 }
4619};
4620
4621}
4622
4623bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004624 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004625 bool &SuppressRHSDiags) {
4626 if (E->getOpcode() == BO_Comma) {
4627 // Ignore LHS but note if we could not evaluate it.
4628 if (LHSResult.Failed)
4629 Info.EvalStatus.HasSideEffects = true;
4630 return true;
4631 }
4632
4633 if (E->isLogicalOp()) {
4634 bool lhsResult;
4635 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004636 // We were able to evaluate the LHS, see if we can get away with not
4637 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004638 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004639 Success(lhsResult, E, LHSResult.Val);
4640 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004641 }
4642 } else {
4643 // Since we weren't able to evaluate the left hand side, it
4644 // must have had side effects.
4645 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004646
4647 // We can't evaluate the LHS; however, sometimes the result
4648 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4649 // Don't ignore RHS and suppress diagnostics from this arm.
4650 SuppressRHSDiags = true;
4651 }
4652
4653 return true;
4654 }
4655
4656 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4657 E->getRHS()->getType()->isIntegralOrEnumerationType());
4658
4659 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004660 return false; // Ignore RHS;
4661
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004662 return true;
4663}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004664
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004665bool DataRecursiveIntBinOpEvaluator::
4666 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4667 const BinaryOperator *E, APValue &Result) {
4668 if (E->getOpcode() == BO_Comma) {
4669 if (RHSResult.Failed)
4670 return false;
4671 Result = RHSResult.Val;
4672 return true;
4673 }
4674
4675 if (E->isLogicalOp()) {
4676 bool lhsResult, rhsResult;
4677 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4678 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4679
4680 if (LHSIsOK) {
4681 if (RHSIsOK) {
4682 if (E->getOpcode() == BO_LOr)
4683 return Success(lhsResult || rhsResult, E, Result);
4684 else
4685 return Success(lhsResult && rhsResult, E, Result);
4686 }
4687 } else {
4688 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004689 // We can't evaluate the LHS; however, sometimes the result
4690 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4691 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004692 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004693 }
4694 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004695
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004696 return false;
4697 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004698
4699 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4700 E->getRHS()->getType()->isIntegralOrEnumerationType());
4701
4702 if (LHSResult.Failed || RHSResult.Failed)
4703 return false;
4704
4705 const APValue &LHSVal = LHSResult.Val;
4706 const APValue &RHSVal = RHSResult.Val;
4707
4708 // Handle cases like (unsigned long)&a + 4.
4709 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4710 Result = LHSVal;
4711 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4712 RHSVal.getInt().getZExtValue());
4713 if (E->getOpcode() == BO_Add)
4714 Result.getLValueOffset() += AdditionalOffset;
4715 else
4716 Result.getLValueOffset() -= AdditionalOffset;
4717 return true;
4718 }
4719
4720 // Handle cases like 4 + (unsigned long)&a
4721 if (E->getOpcode() == BO_Add &&
4722 RHSVal.isLValue() && LHSVal.isInt()) {
4723 Result = RHSVal;
4724 Result.getLValueOffset() += CharUnits::fromQuantity(
4725 LHSVal.getInt().getZExtValue());
4726 return true;
4727 }
4728
4729 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4730 // Handle (intptr_t)&&A - (intptr_t)&&B.
4731 if (!LHSVal.getLValueOffset().isZero() ||
4732 !RHSVal.getLValueOffset().isZero())
4733 return false;
4734 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4735 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4736 if (!LHSExpr || !RHSExpr)
4737 return false;
4738 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4739 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4740 if (!LHSAddrExpr || !RHSAddrExpr)
4741 return false;
4742 // Make sure both labels come from the same function.
4743 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4744 RHSAddrExpr->getLabel()->getDeclContext())
4745 return false;
4746 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4747 return true;
4748 }
4749
4750 // All the following cases expect both operands to be an integer
4751 if (!LHSVal.isInt() || !RHSVal.isInt())
4752 return Error(E);
4753
4754 const APSInt &LHS = LHSVal.getInt();
4755 APSInt RHS = RHSVal.getInt();
4756
4757 switch (E->getOpcode()) {
4758 default:
4759 return Error(E);
4760 case BO_Mul:
4761 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4762 LHS.getBitWidth() * 2,
4763 std::multiplies<APSInt>()), E,
4764 Result);
4765 case BO_Add:
4766 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4767 LHS.getBitWidth() + 1,
4768 std::plus<APSInt>()), E, Result);
4769 case BO_Sub:
4770 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4771 LHS.getBitWidth() + 1,
4772 std::minus<APSInt>()), E, Result);
4773 case BO_And: return Success(LHS & RHS, E, Result);
4774 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4775 case BO_Or: return Success(LHS | RHS, E, Result);
4776 case BO_Div:
4777 case BO_Rem:
4778 if (RHS == 0)
4779 return Error(E, diag::note_expr_divide_by_zero);
4780 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4781 // not actually undefined behavior in C++11 due to a language defect.
4782 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4783 LHS.isSigned() && LHS.isMinSignedValue())
4784 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4785 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4786 Result);
4787 case BO_Shl: {
4788 // During constant-folding, a negative shift is an opposite shift. Such
4789 // a shift is not a constant expression.
4790 if (RHS.isSigned() && RHS.isNegative()) {
4791 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4792 RHS = -RHS;
4793 goto shift_right;
4794 }
4795
4796 shift_left:
4797 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4798 // the shifted type.
4799 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4800 if (SA != RHS) {
4801 CCEDiag(E, diag::note_constexpr_large_shift)
4802 << RHS << E->getType() << LHS.getBitWidth();
4803 } else if (LHS.isSigned()) {
4804 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4805 // operand, and must not overflow the corresponding unsigned type.
4806 if (LHS.isNegative())
4807 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4808 else if (LHS.countLeadingZeros() < SA)
4809 CCEDiag(E, diag::note_constexpr_lshift_discards);
4810 }
4811
4812 return Success(LHS << SA, E, Result);
4813 }
4814 case BO_Shr: {
4815 // During constant-folding, a negative shift is an opposite shift. Such a
4816 // shift is not a constant expression.
4817 if (RHS.isSigned() && RHS.isNegative()) {
4818 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4819 RHS = -RHS;
4820 goto shift_left;
4821 }
4822
4823 shift_right:
4824 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4825 // shifted type.
4826 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4827 if (SA != RHS)
4828 CCEDiag(E, diag::note_constexpr_large_shift)
4829 << RHS << E->getType() << LHS.getBitWidth();
4830
4831 return Success(LHS >> SA, E, Result);
4832 }
4833
4834 case BO_LT: return Success(LHS < RHS, E, Result);
4835 case BO_GT: return Success(LHS > RHS, E, Result);
4836 case BO_LE: return Success(LHS <= RHS, E, Result);
4837 case BO_GE: return Success(LHS >= RHS, E, Result);
4838 case BO_EQ: return Success(LHS == RHS, E, Result);
4839 case BO_NE: return Success(LHS != RHS, E, Result);
4840 }
4841}
4842
Richard Trieub7783052012-03-21 23:30:30 +00004843void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004844 Job &job = Queue.back();
4845
4846 switch (job.Kind) {
4847 case Job::AnyExprKind: {
4848 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4849 if (shouldEnqueue(Bop)) {
4850 job.Kind = Job::BinOpKind;
4851 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00004852 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004853 }
4854 }
4855
4856 EvaluateExpr(job.E, Result);
4857 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004858 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004859 }
4860
4861 case Job::BinOpKind: {
4862 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004863 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004864 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004865 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004866 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004867 }
4868 if (SuppressRHSDiags)
4869 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004870 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004871 job.Kind = Job::BinOpVisitedLHSKind;
4872 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00004873 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004874 }
4875
4876 case Job::BinOpVisitedLHSKind: {
4877 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4878 EvalResult RHS;
4879 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00004880 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004881 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004882 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004883 }
4884 }
4885
4886 llvm_unreachable("Invalid Job::Kind!");
4887}
4888
4889bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4890 if (E->isAssignmentOp())
4891 return Error(E);
4892
4893 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4894 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004895
Anders Carlsson286f85e2008-11-16 07:17:21 +00004896 QualType LHSTy = E->getLHS()->getType();
4897 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004898
4899 if (LHSTy->isAnyComplexType()) {
4900 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004901 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004902
Richard Smith745f5142012-01-27 01:14:48 +00004903 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4904 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004905 return false;
4906
Richard Smith745f5142012-01-27 01:14:48 +00004907 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004908 return false;
4909
4910 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004911 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004912 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004913 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004914 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4915
John McCall2de56d12010-08-25 11:45:40 +00004916 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004917 return Success((CR_r == APFloat::cmpEqual &&
4918 CR_i == APFloat::cmpEqual), E);
4919 else {
John McCall2de56d12010-08-25 11:45:40 +00004920 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004921 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004922 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004923 CR_r == APFloat::cmpLessThan ||
4924 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004925 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004926 CR_i == APFloat::cmpLessThan ||
4927 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004928 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004929 } else {
John McCall2de56d12010-08-25 11:45:40 +00004930 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004931 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4932 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4933 else {
John McCall2de56d12010-08-25 11:45:40 +00004934 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004935 "Invalid compex comparison.");
4936 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4937 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4938 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004939 }
4940 }
Mike Stump1eb44332009-09-09 15:08:12 +00004941
Anders Carlsson286f85e2008-11-16 07:17:21 +00004942 if (LHSTy->isRealFloatingType() &&
4943 RHSTy->isRealFloatingType()) {
4944 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004945
Richard Smith745f5142012-01-27 01:14:48 +00004946 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4947 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004948 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004949
Richard Smith745f5142012-01-27 01:14:48 +00004950 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004951 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004952
Anders Carlsson286f85e2008-11-16 07:17:21 +00004953 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004954
Anders Carlsson286f85e2008-11-16 07:17:21 +00004955 switch (E->getOpcode()) {
4956 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004957 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004958 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004959 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004960 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004961 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004962 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004963 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004964 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004965 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004966 E);
John McCall2de56d12010-08-25 11:45:40 +00004967 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004968 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004969 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004970 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004971 || CR == APFloat::cmpLessThan
4972 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004973 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004974 }
Mike Stump1eb44332009-09-09 15:08:12 +00004975
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004976 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004977 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004978 LValue LHSValue, RHSValue;
4979
4980 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4981 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004982 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004983
Richard Smith745f5142012-01-27 01:14:48 +00004984 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004985 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004986
Richard Smith625b8072011-10-31 01:37:14 +00004987 // Reject differing bases from the normal codepath; we special-case
4988 // comparisons to null.
4989 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004990 if (E->getOpcode() == BO_Sub) {
4991 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004992 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4993 return false;
4994 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4995 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4996 if (!LHSExpr || !RHSExpr)
4997 return false;
4998 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4999 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5000 if (!LHSAddrExpr || !RHSAddrExpr)
5001 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00005002 // Make sure both labels come from the same function.
5003 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5004 RHSAddrExpr->getLabel()->getDeclContext())
5005 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00005006 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00005007 return true;
5008 }
Richard Smith9e36b532011-10-31 05:11:32 +00005009 // Inequalities and subtractions between unrelated pointers have
5010 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00005011 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00005012 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00005013 // A constant address may compare equal to the address of a symbol.
5014 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00005015 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00005016 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5017 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00005018 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00005019 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00005020 // distinct addresses. In clang, the result of such a comparison is
5021 // unspecified, so it is not a constant expression. However, we do know
5022 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00005023 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5024 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00005025 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00005026 // We can't tell whether weak symbols will end up pointing to the same
5027 // object.
5028 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00005029 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00005030 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00005031 // (Note that clang defaults to -fmerge-all-constants, which can
5032 // lead to inconsistent results for comparisons involving the address
5033 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00005034 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00005035 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005036
Richard Smith15efc4d2012-02-01 08:10:20 +00005037 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5038 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5039
Richard Smithf15fda02012-02-02 01:16:57 +00005040 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5041 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5042
John McCall2de56d12010-08-25 11:45:40 +00005043 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00005044 // C++11 [expr.add]p6:
5045 // Unless both pointers point to elements of the same array object, or
5046 // one past the last element of the array object, the behavior is
5047 // undefined.
5048 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5049 !AreElementsOfSameArray(getType(LHSValue.Base),
5050 LHSDesignator, RHSDesignator))
5051 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5052
Chris Lattner4992bdd2010-04-20 17:13:14 +00005053 QualType Type = E->getLHS()->getType();
5054 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00005055
Richard Smith180f4792011-11-10 06:34:14 +00005056 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00005057 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00005058 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00005059
Richard Smith15efc4d2012-02-01 08:10:20 +00005060 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5061 // and produce incorrect results when it overflows. Such behavior
5062 // appears to be non-conforming, but is common, so perhaps we should
5063 // assume the standard intended for such cases to be undefined behavior
5064 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00005065
Richard Smith15efc4d2012-02-01 08:10:20 +00005066 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5067 // overflow in the final conversion to ptrdiff_t.
5068 APSInt LHS(
5069 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5070 APSInt RHS(
5071 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5072 APSInt ElemSize(
5073 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5074 APSInt TrueResult = (LHS - RHS) / ElemSize;
5075 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5076
5077 if (Result.extend(65) != TrueResult)
5078 HandleOverflow(Info, E, TrueResult, E->getType());
5079 return Success(Result, E);
5080 }
Richard Smith82f28582012-01-31 06:41:30 +00005081
5082 // C++11 [expr.rel]p3:
5083 // Pointers to void (after pointer conversions) can be compared, with a
5084 // result defined as follows: If both pointers represent the same
5085 // address or are both the null pointer value, the result is true if the
5086 // operator is <= or >= and false otherwise; otherwise the result is
5087 // unspecified.
5088 // We interpret this as applying to pointers to *cv* void.
5089 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00005090 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00005091 CCEDiag(E, diag::note_constexpr_void_comparison);
5092
Richard Smithf15fda02012-02-02 01:16:57 +00005093 // C++11 [expr.rel]p2:
5094 // - If two pointers point to non-static data members of the same object,
5095 // or to subobjects or array elements fo such members, recursively, the
5096 // pointer to the later declared member compares greater provided the
5097 // two members have the same access control and provided their class is
5098 // not a union.
5099 // [...]
5100 // - Otherwise pointer comparisons are unspecified.
5101 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5102 E->isRelationalOp()) {
5103 bool WasArrayIndex;
5104 unsigned Mismatch =
5105 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5106 RHSDesignator, WasArrayIndex);
5107 // At the point where the designators diverge, the comparison has a
5108 // specified value if:
5109 // - we are comparing array indices
5110 // - we are comparing fields of a union, or fields with the same access
5111 // Otherwise, the result is unspecified and thus the comparison is not a
5112 // constant expression.
5113 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5114 Mismatch < RHSDesignator.Entries.size()) {
5115 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5116 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5117 if (!LF && !RF)
5118 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5119 else if (!LF)
5120 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5121 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5122 << RF->getParent() << RF;
5123 else if (!RF)
5124 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5125 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5126 << LF->getParent() << LF;
5127 else if (!LF->getParent()->isUnion() &&
5128 LF->getAccess() != RF->getAccess())
5129 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5130 << LF << LF->getAccess() << RF << RF->getAccess()
5131 << LF->getParent();
5132 }
5133 }
5134
Eli Friedmana3169882012-04-16 04:30:08 +00005135 // The comparison here must be unsigned, and performed with the same
5136 // width as the pointer.
Eli Friedmana3169882012-04-16 04:30:08 +00005137 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5138 uint64_t CompareLHS = LHSOffset.getQuantity();
5139 uint64_t CompareRHS = RHSOffset.getQuantity();
5140 assert(PtrSize <= 64 && "Unexpected pointer width");
5141 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5142 CompareLHS &= Mask;
5143 CompareRHS &= Mask;
5144
Eli Friedman28503762012-04-16 19:23:57 +00005145 // If there is a base and this is a relational operator, we can only
5146 // compare pointers within the object in question; otherwise, the result
5147 // depends on where the object is located in memory.
5148 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5149 QualType BaseTy = getType(LHSValue.Base);
5150 if (BaseTy->isIncompleteType())
5151 return Error(E);
5152 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5153 uint64_t OffsetLimit = Size.getQuantity();
5154 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5155 return Error(E);
5156 }
5157
Richard Smith625b8072011-10-31 01:37:14 +00005158 switch (E->getOpcode()) {
5159 default: llvm_unreachable("missing comparison operator");
Eli Friedmana3169882012-04-16 04:30:08 +00005160 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5161 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5162 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5163 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5164 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5165 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00005166 }
Anders Carlsson3068d112008-11-16 19:01:22 +00005167 }
5168 }
Richard Smithb02e4622012-02-01 01:42:44 +00005169
5170 if (LHSTy->isMemberPointerType()) {
5171 assert(E->isEqualityOp() && "unexpected member pointer operation");
5172 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5173
5174 MemberPtr LHSValue, RHSValue;
5175
5176 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5177 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5178 return false;
5179
5180 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5181 return false;
5182
5183 // C++11 [expr.eq]p2:
5184 // If both operands are null, they compare equal. Otherwise if only one is
5185 // null, they compare unequal.
5186 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5187 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5188 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5189 }
5190
5191 // Otherwise if either is a pointer to a virtual member function, the
5192 // result is unspecified.
5193 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5194 if (MD->isVirtual())
5195 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5196 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5197 if (MD->isVirtual())
5198 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5199
5200 // Otherwise they compare equal if and only if they would refer to the
5201 // same member of the same most derived object or the same subobject if
5202 // they were dereferenced with a hypothetical object of the associated
5203 // class type.
5204 bool Equal = LHSValue == RHSValue;
5205 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5206 }
5207
Richard Smith26f2cac2012-02-14 22:35:28 +00005208 if (LHSTy->isNullPtrType()) {
5209 assert(E->isComparisonOp() && "unexpected nullptr operation");
5210 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5211 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5212 // are compared, the result is true of the operator is <=, >= or ==, and
5213 // false otherwise.
5214 BinaryOperator::Opcode Opcode = E->getOpcode();
5215 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5216 }
5217
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005218 assert((!LHSTy->isIntegralOrEnumerationType() ||
5219 !RHSTy->isIntegralOrEnumerationType()) &&
5220 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5221 // We can't continue from here for non-integral types.
5222 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005223}
5224
Ken Dyck8b752f12010-01-27 17:10:57 +00005225CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005226 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5227 // result shall be the alignment of the referenced type."
5228 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5229 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005230
5231 // __alignof is defined to return the preferred alignment.
5232 return Info.Ctx.toCharUnitsFromBits(
5233 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005234}
5235
Ken Dyck8b752f12010-01-27 17:10:57 +00005236CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005237 E = E->IgnoreParens();
5238
5239 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005240 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005241 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005242 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5243 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005244
Chris Lattneraf707ab2009-01-24 21:53:27 +00005245 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005246 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5247 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005248
Chris Lattnere9feb472009-01-24 21:09:06 +00005249 return GetAlignOfType(E->getType());
5250}
5251
5252
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005253/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5254/// a result as the expression's type.
5255bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5256 const UnaryExprOrTypeTraitExpr *E) {
5257 switch(E->getKind()) {
5258 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005259 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005260 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005261 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005262 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005263 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005264
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005265 case UETT_VecStep: {
5266 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005267
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005268 if (Ty->isVectorType()) {
5269 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005270
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005271 // The vec_step built-in functions that take a 3-component
5272 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5273 if (n == 3)
5274 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005275
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005276 return Success(n, E);
5277 } else
5278 return Success(1, E);
5279 }
5280
5281 case UETT_SizeOf: {
5282 QualType SrcTy = E->getTypeOfArgument();
5283 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5284 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005285 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5286 SrcTy = Ref->getPointeeType();
5287
Richard Smith180f4792011-11-10 06:34:14 +00005288 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005289 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005290 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005291 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005292 }
5293 }
5294
5295 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005296}
5297
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005298bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005299 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005300 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005301 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005302 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005303 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005304 for (unsigned i = 0; i != n; ++i) {
5305 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5306 switch (ON.getKind()) {
5307 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005308 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005309 APSInt IdxResult;
5310 if (!EvaluateInteger(Idx, IdxResult, Info))
5311 return false;
5312 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5313 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005314 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005315 CurrentType = AT->getElementType();
5316 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5317 Result += IdxResult.getSExtValue() * ElementSize;
5318 break;
5319 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005320
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005321 case OffsetOfExpr::OffsetOfNode::Field: {
5322 FieldDecl *MemberDecl = ON.getField();
5323 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005324 if (!RT)
5325 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005326 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005327 if (RD->isInvalidDecl()) return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005328 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005329 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005330 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005331 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005332 CurrentType = MemberDecl->getType().getNonReferenceType();
5333 break;
5334 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005335
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005336 case OffsetOfExpr::OffsetOfNode::Identifier:
5337 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005338
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005339 case OffsetOfExpr::OffsetOfNode::Base: {
5340 CXXBaseSpecifier *BaseSpec = ON.getBase();
5341 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005342 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005343
5344 // Find the layout of the class whose base we are looking into.
5345 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005346 if (!RT)
5347 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005348 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005349 if (RD->isInvalidDecl()) return false;
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005350 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5351
5352 // Find the base class itself.
5353 CurrentType = BaseSpec->getType();
5354 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5355 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005356 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005357
5358 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005359 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005360 break;
5361 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005362 }
5363 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005364 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005365}
5366
Chris Lattnerb542afe2008-07-11 19:10:17 +00005367bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005368 switch (E->getOpcode()) {
5369 default:
5370 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5371 // See C99 6.6p3.
5372 return Error(E);
5373 case UO_Extension:
5374 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5375 // If so, we could clear the diagnostic ID.
5376 return Visit(E->getSubExpr());
5377 case UO_Plus:
5378 // The result is just the value.
5379 return Visit(E->getSubExpr());
5380 case UO_Minus: {
5381 if (!Visit(E->getSubExpr()))
5382 return false;
5383 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005384 const APSInt &Value = Result.getInt();
5385 if (Value.isSigned() && Value.isMinSignedValue())
5386 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5387 E->getType());
5388 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005389 }
5390 case UO_Not: {
5391 if (!Visit(E->getSubExpr()))
5392 return false;
5393 if (!Result.isInt()) return Error(E);
5394 return Success(~Result.getInt(), E);
5395 }
5396 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005397 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005398 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005399 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005400 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005401 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005402 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005403}
Mike Stump1eb44332009-09-09 15:08:12 +00005404
Chris Lattner732b2232008-07-12 01:15:53 +00005405/// HandleCast - This is used to evaluate implicit or explicit casts where the
5406/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005407bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5408 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005409 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005410 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005411
Eli Friedman46a52322011-03-25 00:43:55 +00005412 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005413 case CK_BaseToDerived:
5414 case CK_DerivedToBase:
5415 case CK_UncheckedDerivedToBase:
5416 case CK_Dynamic:
5417 case CK_ToUnion:
5418 case CK_ArrayToPointerDecay:
5419 case CK_FunctionToPointerDecay:
5420 case CK_NullToPointer:
5421 case CK_NullToMemberPointer:
5422 case CK_BaseToDerivedMemberPointer:
5423 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005424 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005425 case CK_ConstructorConversion:
5426 case CK_IntegralToPointer:
5427 case CK_ToVoid:
5428 case CK_VectorSplat:
5429 case CK_IntegralToFloating:
5430 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005431 case CK_CPointerToObjCPointerCast:
5432 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005433 case CK_AnyPointerToBlockPointerCast:
5434 case CK_ObjCObjectLValueCast:
5435 case CK_FloatingRealToComplex:
5436 case CK_FloatingComplexToReal:
5437 case CK_FloatingComplexCast:
5438 case CK_FloatingComplexToIntegralComplex:
5439 case CK_IntegralRealToComplex:
5440 case CK_IntegralComplexCast:
5441 case CK_IntegralComplexToFloatingComplex:
5442 llvm_unreachable("invalid cast kind for integral value");
5443
Eli Friedmane50c2972011-03-25 19:07:11 +00005444 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005445 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005446 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005447 case CK_ARCProduceObject:
5448 case CK_ARCConsumeObject:
5449 case CK_ARCReclaimReturnedObject:
5450 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005451 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005452 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005453
Richard Smith7d580a42012-01-17 21:17:26 +00005454 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005455 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005456 case CK_AtomicToNonAtomic:
5457 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005458 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005459 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005460
5461 case CK_MemberPointerToBoolean:
5462 case CK_PointerToBoolean:
5463 case CK_IntegralToBoolean:
5464 case CK_FloatingToBoolean:
5465 case CK_FloatingComplexToBoolean:
5466 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005467 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005468 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005469 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005470 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005471 }
5472
Eli Friedman46a52322011-03-25 00:43:55 +00005473 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005474 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005475 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005476
Eli Friedmanbe265702009-02-20 01:15:07 +00005477 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005478 // Allow casts of address-of-label differences if they are no-ops
5479 // or narrowing. (The narrowing case isn't actually guaranteed to
5480 // be constant-evaluatable except in some narrow cases which are hard
5481 // to detect here. We let it through on the assumption the user knows
5482 // what they are doing.)
5483 if (Result.isAddrLabelDiff())
5484 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005485 // Only allow casts of lvalues if they are lossless.
5486 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5487 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005488
Richard Smithf72fccf2012-01-30 22:27:01 +00005489 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5490 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005491 }
Mike Stump1eb44332009-09-09 15:08:12 +00005492
Eli Friedman46a52322011-03-25 00:43:55 +00005493 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005494 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5495
John McCallefdb83e2010-05-07 21:00:08 +00005496 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005497 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005498 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005499
Daniel Dunbardd211642009-02-19 22:24:01 +00005500 if (LV.getLValueBase()) {
5501 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005502 // FIXME: Allow a larger integer size than the pointer size, and allow
5503 // narrowing back down to pointer width in subsequent integral casts.
5504 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005505 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005506 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005507
Richard Smithb755a9d2011-11-16 07:18:12 +00005508 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005509 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005510 return true;
5511 }
5512
Ken Dycka7305832010-01-15 12:37:54 +00005513 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5514 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005515 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005516 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005517
Eli Friedman46a52322011-03-25 00:43:55 +00005518 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005519 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005520 if (!EvaluateComplex(SubExpr, C, Info))
5521 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005522 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005523 }
Eli Friedman2217c872009-02-22 11:46:18 +00005524
Eli Friedman46a52322011-03-25 00:43:55 +00005525 case CK_FloatingToIntegral: {
5526 APFloat F(0.0);
5527 if (!EvaluateFloat(SubExpr, F, Info))
5528 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005529
Richard Smithc1c5f272011-12-13 06:39:58 +00005530 APSInt Value;
5531 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5532 return false;
5533 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005534 }
5535 }
Mike Stump1eb44332009-09-09 15:08:12 +00005536
Eli Friedman46a52322011-03-25 00:43:55 +00005537 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005538}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005539
Eli Friedman722c7172009-02-28 03:59:05 +00005540bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5541 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005542 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005543 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5544 return false;
5545 if (!LV.isComplexInt())
5546 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005547 return Success(LV.getComplexIntReal(), E);
5548 }
5549
5550 return Visit(E->getSubExpr());
5551}
5552
Eli Friedman664a1042009-02-27 04:45:43 +00005553bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005554 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005555 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005556 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5557 return false;
5558 if (!LV.isComplexInt())
5559 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005560 return Success(LV.getComplexIntImag(), E);
5561 }
5562
Richard Smith8327fad2011-10-24 18:44:57 +00005563 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005564 return Success(0, E);
5565}
5566
Douglas Gregoree8aff02011-01-04 17:33:58 +00005567bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5568 return Success(E->getPackLength(), E);
5569}
5570
Sebastian Redl295995c2010-09-10 20:55:47 +00005571bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5572 return Success(E->getValue(), E);
5573}
5574
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005575//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005576// Float Evaluation
5577//===----------------------------------------------------------------------===//
5578
5579namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005580class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005581 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005582 APFloat &Result;
5583public:
5584 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005585 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005586
Richard Smith1aa0be82012-03-03 22:46:17 +00005587 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005588 Result = V.getFloat();
5589 return true;
5590 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005591
Richard Smith51201882011-12-30 21:15:51 +00005592 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005593 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5594 return true;
5595 }
5596
Chris Lattner019f4e82008-10-06 05:28:25 +00005597 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005598
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005599 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005600 bool VisitBinaryOperator(const BinaryOperator *E);
5601 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005602 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005603
John McCallabd3a852010-05-07 22:08:54 +00005604 bool VisitUnaryReal(const UnaryOperator *E);
5605 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005606
Richard Smith51201882011-12-30 21:15:51 +00005607 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005608};
5609} // end anonymous namespace
5610
5611static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005612 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005613 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005614}
5615
Jay Foad4ba2a172011-01-12 09:06:06 +00005616static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005617 QualType ResultTy,
5618 const Expr *Arg,
5619 bool SNaN,
5620 llvm::APFloat &Result) {
5621 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5622 if (!S) return false;
5623
5624 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5625
5626 llvm::APInt fill;
5627
5628 // Treat empty strings as if they were zero.
5629 if (S->getString().empty())
5630 fill = llvm::APInt(32, 0);
5631 else if (S->getString().getAsInteger(0, fill))
5632 return false;
5633
5634 if (SNaN)
5635 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5636 else
5637 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5638 return true;
5639}
5640
Chris Lattner019f4e82008-10-06 05:28:25 +00005641bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005642 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005643 default:
5644 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5645
Chris Lattner019f4e82008-10-06 05:28:25 +00005646 case Builtin::BI__builtin_huge_val:
5647 case Builtin::BI__builtin_huge_valf:
5648 case Builtin::BI__builtin_huge_vall:
5649 case Builtin::BI__builtin_inf:
5650 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005651 case Builtin::BI__builtin_infl: {
5652 const llvm::fltSemantics &Sem =
5653 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005654 Result = llvm::APFloat::getInf(Sem);
5655 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005656 }
Mike Stump1eb44332009-09-09 15:08:12 +00005657
John McCalldb7b72a2010-02-28 13:00:19 +00005658 case Builtin::BI__builtin_nans:
5659 case Builtin::BI__builtin_nansf:
5660 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005661 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5662 true, Result))
5663 return Error(E);
5664 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005665
Chris Lattner9e621712008-10-06 06:31:58 +00005666 case Builtin::BI__builtin_nan:
5667 case Builtin::BI__builtin_nanf:
5668 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005669 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005670 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005671 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5672 false, Result))
5673 return Error(E);
5674 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005675
5676 case Builtin::BI__builtin_fabs:
5677 case Builtin::BI__builtin_fabsf:
5678 case Builtin::BI__builtin_fabsl:
5679 if (!EvaluateFloat(E->getArg(0), Result, Info))
5680 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005681
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005682 if (Result.isNegative())
5683 Result.changeSign();
5684 return true;
5685
Mike Stump1eb44332009-09-09 15:08:12 +00005686 case Builtin::BI__builtin_copysign:
5687 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005688 case Builtin::BI__builtin_copysignl: {
5689 APFloat RHS(0.);
5690 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5691 !EvaluateFloat(E->getArg(1), RHS, Info))
5692 return false;
5693 Result.copySign(RHS);
5694 return true;
5695 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005696 }
5697}
5698
John McCallabd3a852010-05-07 22:08:54 +00005699bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005700 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5701 ComplexValue CV;
5702 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5703 return false;
5704 Result = CV.FloatReal;
5705 return true;
5706 }
5707
5708 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005709}
5710
5711bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005712 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5713 ComplexValue CV;
5714 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5715 return false;
5716 Result = CV.FloatImag;
5717 return true;
5718 }
5719
Richard Smith8327fad2011-10-24 18:44:57 +00005720 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005721 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5722 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005723 return true;
5724}
5725
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005726bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005727 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005728 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005729 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005730 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005731 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005732 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5733 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005734 Result.changeSign();
5735 return true;
5736 }
5737}
Chris Lattner019f4e82008-10-06 05:28:25 +00005738
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005739bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005740 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5741 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005742
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005743 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005744 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5745 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005746 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005747 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005748 return false;
5749
5750 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005751 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005752 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005753 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005754 break;
John McCall2de56d12010-08-25 11:45:40 +00005755 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005756 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005757 break;
John McCall2de56d12010-08-25 11:45:40 +00005758 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005759 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005760 break;
John McCall2de56d12010-08-25 11:45:40 +00005761 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005762 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005763 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005764 }
Richard Smith7b48a292012-02-01 05:53:12 +00005765
5766 if (Result.isInfinity() || Result.isNaN())
5767 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5768 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005769}
5770
5771bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5772 Result = E->getValue();
5773 return true;
5774}
5775
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005776bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5777 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005778
Eli Friedman2a523ee2011-03-25 00:54:52 +00005779 switch (E->getCastKind()) {
5780 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005781 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005782
5783 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005784 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005785 return EvaluateInteger(SubExpr, IntResult, Info) &&
5786 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5787 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005788 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005789
5790 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005791 if (!Visit(SubExpr))
5792 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005793 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5794 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005795 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005796
Eli Friedman2a523ee2011-03-25 00:54:52 +00005797 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005798 ComplexValue V;
5799 if (!EvaluateComplex(SubExpr, V, Info))
5800 return false;
5801 Result = V.getComplexFloatReal();
5802 return true;
5803 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005804 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005805}
5806
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005807//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005808// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005809//===----------------------------------------------------------------------===//
5810
5811namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005812class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005813 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005814 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005815
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005816public:
John McCallf4cf1a12010-05-07 17:22:02 +00005817 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005818 : ExprEvaluatorBaseTy(info), Result(Result) {}
5819
Richard Smith1aa0be82012-03-03 22:46:17 +00005820 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005821 Result.setFrom(V);
5822 return true;
5823 }
Mike Stump1eb44332009-09-09 15:08:12 +00005824
Eli Friedman7ead5c72012-01-10 04:58:17 +00005825 bool ZeroInitialization(const Expr *E);
5826
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005827 //===--------------------------------------------------------------------===//
5828 // Visitor Methods
5829 //===--------------------------------------------------------------------===//
5830
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005831 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005832 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005833 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005834 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005835 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005836};
5837} // end anonymous namespace
5838
John McCallf4cf1a12010-05-07 17:22:02 +00005839static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5840 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005841 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005842 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005843}
5844
Eli Friedman7ead5c72012-01-10 04:58:17 +00005845bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005846 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005847 if (ElemTy->isRealFloatingType()) {
5848 Result.makeComplexFloat();
5849 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5850 Result.FloatReal = Zero;
5851 Result.FloatImag = Zero;
5852 } else {
5853 Result.makeComplexInt();
5854 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5855 Result.IntReal = Zero;
5856 Result.IntImag = Zero;
5857 }
5858 return true;
5859}
5860
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005861bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5862 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005863
5864 if (SubExpr->getType()->isRealFloatingType()) {
5865 Result.makeComplexFloat();
5866 APFloat &Imag = Result.FloatImag;
5867 if (!EvaluateFloat(SubExpr, Imag, Info))
5868 return false;
5869
5870 Result.FloatReal = APFloat(Imag.getSemantics());
5871 return true;
5872 } else {
5873 assert(SubExpr->getType()->isIntegerType() &&
5874 "Unexpected imaginary literal.");
5875
5876 Result.makeComplexInt();
5877 APSInt &Imag = Result.IntImag;
5878 if (!EvaluateInteger(SubExpr, Imag, Info))
5879 return false;
5880
5881 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5882 return true;
5883 }
5884}
5885
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005886bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005887
John McCall8786da72010-12-14 17:51:41 +00005888 switch (E->getCastKind()) {
5889 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005890 case CK_BaseToDerived:
5891 case CK_DerivedToBase:
5892 case CK_UncheckedDerivedToBase:
5893 case CK_Dynamic:
5894 case CK_ToUnion:
5895 case CK_ArrayToPointerDecay:
5896 case CK_FunctionToPointerDecay:
5897 case CK_NullToPointer:
5898 case CK_NullToMemberPointer:
5899 case CK_BaseToDerivedMemberPointer:
5900 case CK_DerivedToBaseMemberPointer:
5901 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005902 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005903 case CK_ConstructorConversion:
5904 case CK_IntegralToPointer:
5905 case CK_PointerToIntegral:
5906 case CK_PointerToBoolean:
5907 case CK_ToVoid:
5908 case CK_VectorSplat:
5909 case CK_IntegralCast:
5910 case CK_IntegralToBoolean:
5911 case CK_IntegralToFloating:
5912 case CK_FloatingToIntegral:
5913 case CK_FloatingToBoolean:
5914 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005915 case CK_CPointerToObjCPointerCast:
5916 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005917 case CK_AnyPointerToBlockPointerCast:
5918 case CK_ObjCObjectLValueCast:
5919 case CK_FloatingComplexToReal:
5920 case CK_FloatingComplexToBoolean:
5921 case CK_IntegralComplexToReal:
5922 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005923 case CK_ARCProduceObject:
5924 case CK_ARCConsumeObject:
5925 case CK_ARCReclaimReturnedObject:
5926 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005927 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005928 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005929
John McCall8786da72010-12-14 17:51:41 +00005930 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005931 case CK_AtomicToNonAtomic:
5932 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005933 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005934 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005935
5936 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005937 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005938 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005939 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005940
5941 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005942 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005943 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005944 return false;
5945
John McCall8786da72010-12-14 17:51:41 +00005946 Result.makeComplexFloat();
5947 Result.FloatImag = APFloat(Real.getSemantics());
5948 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005949 }
5950
John McCall8786da72010-12-14 17:51:41 +00005951 case CK_FloatingComplexCast: {
5952 if (!Visit(E->getSubExpr()))
5953 return false;
5954
5955 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5956 QualType From
5957 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5958
Richard Smithc1c5f272011-12-13 06:39:58 +00005959 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5960 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005961 }
5962
5963 case CK_FloatingComplexToIntegralComplex: {
5964 if (!Visit(E->getSubExpr()))
5965 return false;
5966
5967 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5968 QualType From
5969 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5970 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005971 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5972 To, Result.IntReal) &&
5973 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5974 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005975 }
5976
5977 case CK_IntegralRealToComplex: {
5978 APSInt &Real = Result.IntReal;
5979 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5980 return false;
5981
5982 Result.makeComplexInt();
5983 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5984 return true;
5985 }
5986
5987 case CK_IntegralComplexCast: {
5988 if (!Visit(E->getSubExpr()))
5989 return false;
5990
5991 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5992 QualType From
5993 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5994
Richard Smithf72fccf2012-01-30 22:27:01 +00005995 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5996 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005997 return true;
5998 }
5999
6000 case CK_IntegralComplexToFloatingComplex: {
6001 if (!Visit(E->getSubExpr()))
6002 return false;
6003
6004 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6005 QualType From
6006 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6007 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00006008 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
6009 To, Result.FloatReal) &&
6010 HandleIntToFloatCast(Info, E, From, Result.IntImag,
6011 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00006012 }
6013 }
6014
6015 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00006016}
6017
John McCallf4cf1a12010-05-07 17:22:02 +00006018bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006019 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00006020 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6021
Richard Smith745f5142012-01-27 01:14:48 +00006022 bool LHSOK = Visit(E->getLHS());
6023 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00006024 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006025
John McCallf4cf1a12010-05-07 17:22:02 +00006026 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00006027 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00006028 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006029
Daniel Dunbar3f279872009-01-29 01:32:56 +00006030 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6031 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006032 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00006033 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00006034 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006035 if (Result.isComplexFloat()) {
6036 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6037 APFloat::rmNearestTiesToEven);
6038 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6039 APFloat::rmNearestTiesToEven);
6040 } else {
6041 Result.getComplexIntReal() += RHS.getComplexIntReal();
6042 Result.getComplexIntImag() += RHS.getComplexIntImag();
6043 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00006044 break;
John McCall2de56d12010-08-25 11:45:40 +00006045 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006046 if (Result.isComplexFloat()) {
6047 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6048 APFloat::rmNearestTiesToEven);
6049 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6050 APFloat::rmNearestTiesToEven);
6051 } else {
6052 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6053 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6054 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00006055 break;
John McCall2de56d12010-08-25 11:45:40 +00006056 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00006057 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00006058 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00006059 APFloat &LHS_r = LHS.getComplexFloatReal();
6060 APFloat &LHS_i = LHS.getComplexFloatImag();
6061 APFloat &RHS_r = RHS.getComplexFloatReal();
6062 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00006063
Daniel Dunbar3f279872009-01-29 01:32:56 +00006064 APFloat Tmp = LHS_r;
6065 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6066 Result.getComplexFloatReal() = Tmp;
6067 Tmp = LHS_i;
6068 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6069 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6070
6071 Tmp = LHS_r;
6072 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6073 Result.getComplexFloatImag() = Tmp;
6074 Tmp = LHS_i;
6075 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6076 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6077 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00006078 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00006079 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006080 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6081 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00006082 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006083 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6084 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6085 }
6086 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006087 case BO_Div:
6088 if (Result.isComplexFloat()) {
6089 ComplexValue LHS = Result;
6090 APFloat &LHS_r = LHS.getComplexFloatReal();
6091 APFloat &LHS_i = LHS.getComplexFloatImag();
6092 APFloat &RHS_r = RHS.getComplexFloatReal();
6093 APFloat &RHS_i = RHS.getComplexFloatImag();
6094 APFloat &Res_r = Result.getComplexFloatReal();
6095 APFloat &Res_i = Result.getComplexFloatImag();
6096
6097 APFloat Den = RHS_r;
6098 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6099 APFloat Tmp = RHS_i;
6100 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6101 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6102
6103 Res_r = LHS_r;
6104 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6105 Tmp = LHS_i;
6106 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6107 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6108 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6109
6110 Res_i = LHS_i;
6111 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6112 Tmp = LHS_r;
6113 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6114 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6115 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6116 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00006117 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6118 return Error(E, diag::note_expr_divide_by_zero);
6119
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006120 ComplexValue LHS = Result;
6121 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6122 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6123 Result.getComplexIntReal() =
6124 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6125 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6126 Result.getComplexIntImag() =
6127 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6128 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6129 }
6130 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006131 }
6132
John McCallf4cf1a12010-05-07 17:22:02 +00006133 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006134}
6135
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006136bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6137 // Get the operand value into 'Result'.
6138 if (!Visit(E->getSubExpr()))
6139 return false;
6140
6141 switch (E->getOpcode()) {
6142 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00006143 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006144 case UO_Extension:
6145 return true;
6146 case UO_Plus:
6147 // The result is always just the subexpr.
6148 return true;
6149 case UO_Minus:
6150 if (Result.isComplexFloat()) {
6151 Result.getComplexFloatReal().changeSign();
6152 Result.getComplexFloatImag().changeSign();
6153 }
6154 else {
6155 Result.getComplexIntReal() = -Result.getComplexIntReal();
6156 Result.getComplexIntImag() = -Result.getComplexIntImag();
6157 }
6158 return true;
6159 case UO_Not:
6160 if (Result.isComplexFloat())
6161 Result.getComplexFloatImag().changeSign();
6162 else
6163 Result.getComplexIntImag() = -Result.getComplexIntImag();
6164 return true;
6165 }
6166}
6167
Eli Friedman7ead5c72012-01-10 04:58:17 +00006168bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6169 if (E->getNumInits() == 2) {
6170 if (E->getType()->isComplexType()) {
6171 Result.makeComplexFloat();
6172 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6173 return false;
6174 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6175 return false;
6176 } else {
6177 Result.makeComplexInt();
6178 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6179 return false;
6180 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6181 return false;
6182 }
6183 return true;
6184 }
6185 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6186}
6187
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00006188//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00006189// Void expression evaluation, primarily for a cast to void on the LHS of a
6190// comma operator
6191//===----------------------------------------------------------------------===//
6192
6193namespace {
6194class VoidExprEvaluator
6195 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6196public:
6197 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6198
Richard Smith1aa0be82012-03-03 22:46:17 +00006199 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00006200
6201 bool VisitCastExpr(const CastExpr *E) {
6202 switch (E->getCastKind()) {
6203 default:
6204 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6205 case CK_ToVoid:
6206 VisitIgnoredValue(E->getSubExpr());
6207 return true;
6208 }
6209 }
6210};
6211} // end anonymous namespace
6212
6213static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6214 assert(E->isRValue() && E->getType()->isVoidType());
6215 return VoidExprEvaluator(Info).Visit(E);
6216}
6217
6218//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006219// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006220//===----------------------------------------------------------------------===//
6221
Richard Smith1aa0be82012-03-03 22:46:17 +00006222static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006223 // In C, function designators are not lvalues, but we evaluate them as if they
6224 // are.
6225 if (E->isGLValue() || E->getType()->isFunctionType()) {
6226 LValue LV;
6227 if (!EvaluateLValue(E, LV, Info))
6228 return false;
6229 LV.moveInto(Result);
6230 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006231 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006232 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006233 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006234 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006235 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006236 } else if (E->getType()->hasPointerRepresentation()) {
6237 LValue LV;
6238 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006239 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006240 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006241 } else if (E->getType()->isRealFloatingType()) {
6242 llvm::APFloat F(0.0);
6243 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006244 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006245 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006246 } else if (E->getType()->isAnyComplexType()) {
6247 ComplexValue C;
6248 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006249 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006250 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006251 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006252 MemberPtr P;
6253 if (!EvaluateMemberPointer(E, P, Info))
6254 return false;
6255 P.moveInto(Result);
6256 return true;
Richard Smith51201882011-12-30 21:15:51 +00006257 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006258 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006259 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006260 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006261 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006262 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006263 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006264 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006265 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006266 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6267 return false;
6268 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006269 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00006270 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006271 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00006272 << E->getType();
6273 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00006274 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00006275 if (!EvaluateVoid(E, Info))
6276 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006277 } else if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006278 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006279 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006280 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006281 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006282 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006283 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006284
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006285 return true;
6286}
6287
Richard Smith83587db2012-02-15 02:18:13 +00006288/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6289/// cases, the in-place evaluation is essential, since later initializers for
6290/// an object can indirectly refer to subobjects which were initialized earlier.
6291static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6292 const Expr *E, CheckConstantExpressionKind CCEK,
6293 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006294 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006295 return false;
6296
6297 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006298 // Evaluate arrays and record types in-place, so that later initializers can
6299 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006300 if (E->getType()->isArrayType())
6301 return EvaluateArray(E, This, Result, Info);
6302 else if (E->getType()->isRecordType())
6303 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006304 }
6305
6306 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006307 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006308}
6309
Richard Smithf48fdb02011-12-09 22:58:01 +00006310/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6311/// lvalue-to-rvalue cast if it is an lvalue.
6312static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006313 if (!CheckLiteralType(Info, E))
6314 return false;
6315
Richard Smith1aa0be82012-03-03 22:46:17 +00006316 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006317 return false;
6318
6319 if (E->isGLValue()) {
6320 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006321 LV.setFrom(Info.Ctx, Result);
6322 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006323 return false;
6324 }
6325
Richard Smith1aa0be82012-03-03 22:46:17 +00006326 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006327 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006328}
Richard Smithc49bd112011-10-28 17:51:58 +00006329
Richard Smith51f47082011-10-29 00:50:52 +00006330/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006331/// any crazy technique (that has nothing to do with language standards) that
6332/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006333/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6334/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006335bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006336 // Fast-path evaluations of integer literals, since we sometimes see files
6337 // containing vast quantities of these.
6338 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6339 Result.Val = APValue(APSInt(L->getValue(),
6340 L->getType()->isUnsignedIntegerType()));
6341 return true;
6342 }
6343
Richard Smith2d6a5672012-01-14 04:30:29 +00006344 // FIXME: Evaluating values of large array and record types can cause
6345 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006346 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006347 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006348 return false;
6349
Richard Smithf48fdb02011-12-09 22:58:01 +00006350 EvalInfo Info(Ctx, Result);
6351 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006352}
6353
Jay Foad4ba2a172011-01-12 09:06:06 +00006354bool Expr::EvaluateAsBooleanCondition(bool &Result,
6355 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006356 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006357 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006358 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006359}
6360
Richard Smith80d4b552011-12-28 19:48:30 +00006361bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6362 SideEffectsKind AllowSideEffects) const {
6363 if (!getType()->isIntegralOrEnumerationType())
6364 return false;
6365
Richard Smithc49bd112011-10-28 17:51:58 +00006366 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006367 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6368 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006369 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006370
Richard Smithc49bd112011-10-28 17:51:58 +00006371 Result = ExprResult.Val.getInt();
6372 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006373}
6374
Jay Foad4ba2a172011-01-12 09:06:06 +00006375bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006376 EvalInfo Info(Ctx, Result);
6377
John McCallefdb83e2010-05-07 21:00:08 +00006378 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006379 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6380 !CheckLValueConstantExpression(Info, getExprLoc(),
6381 Ctx.getLValueReferenceType(getType()), LV))
6382 return false;
6383
Richard Smith1aa0be82012-03-03 22:46:17 +00006384 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006385 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006386}
6387
Richard Smith099e7f62011-12-19 06:19:21 +00006388bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6389 const VarDecl *VD,
6390 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006391 // FIXME: Evaluating initializers for large array and record types can cause
6392 // performance problems. Only do so in C++11 for now.
6393 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006394 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith2d6a5672012-01-14 04:30:29 +00006395 return false;
6396
Richard Smith099e7f62011-12-19 06:19:21 +00006397 Expr::EvalStatus EStatus;
6398 EStatus.Diag = &Notes;
6399
6400 EvalInfo InitInfo(Ctx, EStatus);
6401 InitInfo.setEvaluatingDecl(VD, Value);
6402
6403 LValue LVal;
6404 LVal.set(VD);
6405
Richard Smith51201882011-12-30 21:15:51 +00006406 // C++11 [basic.start.init]p2:
6407 // Variables with static storage duration or thread storage duration shall be
6408 // zero-initialized before any other initialization takes place.
6409 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006410 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006411 !VD->getType()->isReferenceType()) {
6412 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006413 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6414 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006415 return false;
6416 }
6417
Richard Smith83587db2012-02-15 02:18:13 +00006418 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6419 /*AllowNonLiteralTypes=*/true) ||
6420 EStatus.HasSideEffects)
6421 return false;
6422
6423 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6424 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006425}
6426
Richard Smith51f47082011-10-29 00:50:52 +00006427/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6428/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006429bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006430 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006431 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006432}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006433
Jay Foad4ba2a172011-01-12 09:06:06 +00006434bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006435 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006436}
6437
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006438APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006439 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006440 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006441 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006442 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006443 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006444
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006445 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006446}
John McCalld905f5a2010-05-07 05:32:02 +00006447
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006448 bool Expr::EvalResult::isGlobalLValue() const {
6449 assert(Val.isLValue());
6450 return IsGlobalLValue(Val.getLValueBase());
6451 }
6452
6453
John McCalld905f5a2010-05-07 05:32:02 +00006454/// isIntegerConstantExpr - this recursive routine will test if an expression is
6455/// an integer constant expression.
6456
6457/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6458/// comma, etc
6459///
6460/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6461/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6462/// cast+dereference.
6463
6464// CheckICE - This function does the fundamental ICE checking: the returned
6465// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6466// Note that to reduce code duplication, this helper does no evaluation
6467// itself; the caller checks whether the expression is evaluatable, and
6468// in the rare cases where CheckICE actually cares about the evaluated
6469// value, it calls into Evalute.
6470//
6471// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006472// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006473// 1: This expression is not an ICE, but if it isn't evaluated, it's
6474// a legal subexpression for an ICE. This return value is used to handle
6475// the comma operator in C99 mode.
6476// 2: This expression is not an ICE, and is not a legal subexpression for one.
6477
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006478namespace {
6479
John McCalld905f5a2010-05-07 05:32:02 +00006480struct ICEDiag {
6481 unsigned Val;
6482 SourceLocation Loc;
6483
6484 public:
6485 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6486 ICEDiag() : Val(0) {}
6487};
6488
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006489}
6490
6491static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006492
6493static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6494 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006495 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006496 !EVResult.Val.isInt()) {
6497 return ICEDiag(2, E->getLocStart());
6498 }
6499 return NoDiag();
6500}
6501
6502static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6503 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006504 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006505 return ICEDiag(2, E->getLocStart());
6506 }
6507
6508 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006509#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006510#define STMT(Node, Base) case Expr::Node##Class:
6511#define EXPR(Node, Base)
6512#include "clang/AST/StmtNodes.inc"
6513 case Expr::PredefinedExprClass:
6514 case Expr::FloatingLiteralClass:
6515 case Expr::ImaginaryLiteralClass:
6516 case Expr::StringLiteralClass:
6517 case Expr::ArraySubscriptExprClass:
6518 case Expr::MemberExprClass:
6519 case Expr::CompoundAssignOperatorClass:
6520 case Expr::CompoundLiteralExprClass:
6521 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006522 case Expr::DesignatedInitExprClass:
6523 case Expr::ImplicitValueInitExprClass:
6524 case Expr::ParenListExprClass:
6525 case Expr::VAArgExprClass:
6526 case Expr::AddrLabelExprClass:
6527 case Expr::StmtExprClass:
6528 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006529 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006530 case Expr::CXXDynamicCastExprClass:
6531 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006532 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006533 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006534 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006535 case Expr::CXXThisExprClass:
6536 case Expr::CXXThrowExprClass:
6537 case Expr::CXXNewExprClass:
6538 case Expr::CXXDeleteExprClass:
6539 case Expr::CXXPseudoDestructorExprClass:
6540 case Expr::UnresolvedLookupExprClass:
6541 case Expr::DependentScopeDeclRefExprClass:
6542 case Expr::CXXConstructExprClass:
6543 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006544 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006545 case Expr::CXXTemporaryObjectExprClass:
6546 case Expr::CXXUnresolvedConstructExprClass:
6547 case Expr::CXXDependentScopeMemberExprClass:
6548 case Expr::UnresolvedMemberExprClass:
6549 case Expr::ObjCStringLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +00006550 case Expr::ObjCBoxedExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006551 case Expr::ObjCArrayLiteralClass:
6552 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006553 case Expr::ObjCEncodeExprClass:
6554 case Expr::ObjCMessageExprClass:
6555 case Expr::ObjCSelectorExprClass:
6556 case Expr::ObjCProtocolExprClass:
6557 case Expr::ObjCIvarRefExprClass:
6558 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006559 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006560 case Expr::ObjCIsaExprClass:
6561 case Expr::ShuffleVectorExprClass:
6562 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006563 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006564 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006565 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006566 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006567 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006568 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006569 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006570 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006571 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006572 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006573 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006574 return ICEDiag(2, E->getLocStart());
6575
Douglas Gregoree8aff02011-01-04 17:33:58 +00006576 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006577 case Expr::GNUNullExprClass:
6578 // GCC considers the GNU __null value to be an integral constant expression.
6579 return NoDiag();
6580
John McCall91a57552011-07-15 05:09:51 +00006581 case Expr::SubstNonTypeTemplateParmExprClass:
6582 return
6583 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6584
John McCalld905f5a2010-05-07 05:32:02 +00006585 case Expr::ParenExprClass:
6586 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006587 case Expr::GenericSelectionExprClass:
6588 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006589 case Expr::IntegerLiteralClass:
6590 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006591 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006592 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006593 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006594 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006595 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006596 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006597 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006598 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006599 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006600 return NoDiag();
6601 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006602 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006603 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6604 // constant expressions, but they can never be ICEs because an ICE cannot
6605 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006606 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006607 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006608 return CheckEvalInICE(E, Ctx);
6609 return ICEDiag(2, E->getLocStart());
6610 }
Richard Smith359c89d2012-02-24 22:12:32 +00006611 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006612 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6613 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006614 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006615 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006616 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006617 // Parameter variables are never constants. Without this check,
6618 // getAnyInitializer() can find a default argument, which leads
6619 // to chaos.
6620 if (isa<ParmVarDecl>(D))
6621 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6622
6623 // C++ 7.1.5.1p2
6624 // A variable of non-volatile const-qualified integral or enumeration
6625 // type initialized by an ICE can be used in ICEs.
6626 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006627 if (!Dcl->getType()->isIntegralOrEnumerationType())
6628 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6629
Richard Smith099e7f62011-12-19 06:19:21 +00006630 const VarDecl *VD;
6631 // Look for a declaration of this variable that has an initializer, and
6632 // check whether it is an ICE.
6633 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6634 return NoDiag();
6635 else
6636 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006637 }
6638 }
6639 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006640 }
John McCalld905f5a2010-05-07 05:32:02 +00006641 case Expr::UnaryOperatorClass: {
6642 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6643 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006644 case UO_PostInc:
6645 case UO_PostDec:
6646 case UO_PreInc:
6647 case UO_PreDec:
6648 case UO_AddrOf:
6649 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006650 // C99 6.6/3 allows increment and decrement within unevaluated
6651 // subexpressions of constant expressions, but they can never be ICEs
6652 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006653 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006654 case UO_Extension:
6655 case UO_LNot:
6656 case UO_Plus:
6657 case UO_Minus:
6658 case UO_Not:
6659 case UO_Real:
6660 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006661 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006662 }
6663
6664 // OffsetOf falls through here.
6665 }
6666 case Expr::OffsetOfExprClass: {
6667 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006668 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006669 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006670 // compliance: we should warn earlier for offsetof expressions with
6671 // array subscripts that aren't ICEs, and if the array subscripts
6672 // are ICEs, the value of the offsetof must be an integer constant.
6673 return CheckEvalInICE(E, Ctx);
6674 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006675 case Expr::UnaryExprOrTypeTraitExprClass: {
6676 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6677 if ((Exp->getKind() == UETT_SizeOf) &&
6678 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006679 return ICEDiag(2, E->getLocStart());
6680 return NoDiag();
6681 }
6682 case Expr::BinaryOperatorClass: {
6683 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6684 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006685 case BO_PtrMemD:
6686 case BO_PtrMemI:
6687 case BO_Assign:
6688 case BO_MulAssign:
6689 case BO_DivAssign:
6690 case BO_RemAssign:
6691 case BO_AddAssign:
6692 case BO_SubAssign:
6693 case BO_ShlAssign:
6694 case BO_ShrAssign:
6695 case BO_AndAssign:
6696 case BO_XorAssign:
6697 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006698 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6699 // constant expressions, but they can never be ICEs because an ICE cannot
6700 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006701 return ICEDiag(2, E->getLocStart());
6702
John McCall2de56d12010-08-25 11:45:40 +00006703 case BO_Mul:
6704 case BO_Div:
6705 case BO_Rem:
6706 case BO_Add:
6707 case BO_Sub:
6708 case BO_Shl:
6709 case BO_Shr:
6710 case BO_LT:
6711 case BO_GT:
6712 case BO_LE:
6713 case BO_GE:
6714 case BO_EQ:
6715 case BO_NE:
6716 case BO_And:
6717 case BO_Xor:
6718 case BO_Or:
6719 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006720 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6721 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006722 if (Exp->getOpcode() == BO_Div ||
6723 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006724 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006725 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006726 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006727 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006728 if (REval == 0)
6729 return ICEDiag(1, E->getLocStart());
6730 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006731 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006732 if (LEval.isMinSignedValue())
6733 return ICEDiag(1, E->getLocStart());
6734 }
6735 }
6736 }
John McCall2de56d12010-08-25 11:45:40 +00006737 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006738 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006739 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6740 // if it isn't evaluated.
6741 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6742 return ICEDiag(1, E->getLocStart());
6743 } else {
6744 // In both C89 and C++, commas in ICEs are illegal.
6745 return ICEDiag(2, E->getLocStart());
6746 }
6747 }
6748 if (LHSResult.Val >= RHSResult.Val)
6749 return LHSResult;
6750 return RHSResult;
6751 }
John McCall2de56d12010-08-25 11:45:40 +00006752 case BO_LAnd:
6753 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006754 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6755 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6756 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6757 // Rare case where the RHS has a comma "side-effect"; we need
6758 // to actually check the condition to see whether the side
6759 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006760 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006761 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006762 return RHSResult;
6763 return NoDiag();
6764 }
6765
6766 if (LHSResult.Val >= RHSResult.Val)
6767 return LHSResult;
6768 return RHSResult;
6769 }
6770 }
6771 }
6772 case Expr::ImplicitCastExprClass:
6773 case Expr::CStyleCastExprClass:
6774 case Expr::CXXFunctionalCastExprClass:
6775 case Expr::CXXStaticCastExprClass:
6776 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006777 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006778 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006779 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006780 if (isa<ExplicitCastExpr>(E)) {
6781 if (const FloatingLiteral *FL
6782 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6783 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6784 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6785 APSInt IgnoredVal(DestWidth, !DestSigned);
6786 bool Ignored;
6787 // If the value does not fit in the destination type, the behavior is
6788 // undefined, so we are not required to treat it as a constant
6789 // expression.
6790 if (FL->getValue().convertToInteger(IgnoredVal,
6791 llvm::APFloat::rmTowardZero,
6792 &Ignored) & APFloat::opInvalidOp)
6793 return ICEDiag(2, E->getLocStart());
6794 return NoDiag();
6795 }
6796 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006797 switch (cast<CastExpr>(E)->getCastKind()) {
6798 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006799 case CK_AtomicToNonAtomic:
6800 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006801 case CK_NoOp:
6802 case CK_IntegralToBoolean:
6803 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006804 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006805 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006806 return ICEDiag(2, E->getLocStart());
6807 }
John McCalld905f5a2010-05-07 05:32:02 +00006808 }
John McCall56ca35d2011-02-17 10:25:35 +00006809 case Expr::BinaryConditionalOperatorClass: {
6810 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6811 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6812 if (CommonResult.Val == 2) return CommonResult;
6813 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6814 if (FalseResult.Val == 2) return FalseResult;
6815 if (CommonResult.Val == 1) return CommonResult;
6816 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006817 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006818 return FalseResult;
6819 }
John McCalld905f5a2010-05-07 05:32:02 +00006820 case Expr::ConditionalOperatorClass: {
6821 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6822 // If the condition (ignoring parens) is a __builtin_constant_p call,
6823 // then only the true side is actually considered in an integer constant
6824 // expression, and it is fully evaluated. This is an important GNU
6825 // extension. See GCC PR38377 for discussion.
6826 if (const CallExpr *CallCE
6827 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006828 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6829 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006830 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006831 if (CondResult.Val == 2)
6832 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006833
Richard Smithf48fdb02011-12-09 22:58:01 +00006834 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6835 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006836
John McCalld905f5a2010-05-07 05:32:02 +00006837 if (TrueResult.Val == 2)
6838 return TrueResult;
6839 if (FalseResult.Val == 2)
6840 return FalseResult;
6841 if (CondResult.Val == 1)
6842 return CondResult;
6843 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6844 return NoDiag();
6845 // Rare case where the diagnostics depend on which side is evaluated
6846 // Note that if we get here, CondResult is 0, and at least one of
6847 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006848 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006849 return FalseResult;
6850 }
6851 return TrueResult;
6852 }
6853 case Expr::CXXDefaultArgExprClass:
6854 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6855 case Expr::ChooseExprClass: {
6856 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6857 }
6858 }
6859
David Blaikie30263482012-01-20 21:50:17 +00006860 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006861}
6862
Richard Smithf48fdb02011-12-09 22:58:01 +00006863/// Evaluate an expression as a C++11 integral constant expression.
6864static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6865 const Expr *E,
6866 llvm::APSInt *Value,
6867 SourceLocation *Loc) {
6868 if (!E->getType()->isIntegralOrEnumerationType()) {
6869 if (Loc) *Loc = E->getExprLoc();
6870 return false;
6871 }
6872
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006873 APValue Result;
6874 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006875 return false;
6876
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006877 assert(Result.isInt() && "pointer cast to int is not an ICE");
6878 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006879 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006880}
6881
Richard Smithdd1f29b2011-12-12 09:28:41 +00006882bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006883 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006884 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6885
John McCalld905f5a2010-05-07 05:32:02 +00006886 ICEDiag d = CheckICE(this, Ctx);
6887 if (d.Val != 0) {
6888 if (Loc) *Loc = d.Loc;
6889 return false;
6890 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006891 return true;
6892}
6893
6894bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6895 SourceLocation *Loc, bool isEvaluated) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006896 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006897 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6898
6899 if (!isIntegerConstantExpr(Ctx, Loc))
6900 return false;
6901 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006902 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006903 return true;
6904}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006905
Richard Smith70488e22012-02-14 21:38:30 +00006906bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6907 return CheckICE(this, Ctx).Val == 0;
6908}
6909
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006910bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6911 SourceLocation *Loc) const {
6912 // We support this checking in C++98 mode in order to diagnose compatibility
6913 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006914 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006915
Richard Smith70488e22012-02-14 21:38:30 +00006916 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006917 Expr::EvalStatus Status;
6918 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6919 Status.Diag = &Diags;
6920 EvalInfo Info(Ctx, Status);
6921
6922 APValue Scratch;
6923 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6924
6925 if (!Diags.empty()) {
6926 IsConstExpr = false;
6927 if (Loc) *Loc = Diags[0].first;
6928 } else if (!IsConstExpr) {
6929 // FIXME: This shouldn't happen.
6930 if (Loc) *Loc = getExprLoc();
6931 }
6932
6933 return IsConstExpr;
6934}
Richard Smith745f5142012-01-27 01:14:48 +00006935
6936bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6937 llvm::SmallVectorImpl<
6938 PartialDiagnosticAt> &Diags) {
6939 // FIXME: It would be useful to check constexpr function templates, but at the
6940 // moment the constant expression evaluator cannot cope with the non-rigorous
6941 // ASTs which we build for dependent expressions.
6942 if (FD->isDependentContext())
6943 return true;
6944
6945 Expr::EvalStatus Status;
6946 Status.Diag = &Diags;
6947
6948 EvalInfo Info(FD->getASTContext(), Status);
6949 Info.CheckingPotentialConstantExpression = true;
6950
6951 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6952 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6953
6954 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6955 // is a temporary being used as the 'this' pointer.
6956 LValue This;
6957 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006958 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006959
Richard Smith745f5142012-01-27 01:14:48 +00006960 ArrayRef<const Expr*> Args;
6961
6962 SourceLocation Loc = FD->getLocation();
6963
Richard Smith1aa0be82012-03-03 22:46:17 +00006964 APValue Scratch;
6965 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006966 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006967 else
Richard Smith745f5142012-01-27 01:14:48 +00006968 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6969 Args, FD->getBody(), Info, Scratch);
6970
6971 return Diags.empty();
6972}