blob: 01c9fe7cd846ae3dda5f49fa0c458cf6b2f8e07f [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith745f5142012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlssonc44eec62008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000038#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000039#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000040#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000041#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000042#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000047#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000048#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000049
Anders Carlssonc44eec62008-07-03 04:20:39 +000050using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000051using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000052using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000053
Richard Smith83587db2012-02-15 02:18:13 +000054static bool IsGlobalLValue(APValue::LValueBase B);
55
John McCallf4cf1a12010-05-07 17:22:02 +000056namespace {
Richard Smith180f4792011-11-10 06:34:14 +000057 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000058 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000059 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000060
Richard Smith83587db2012-02-15 02:18:13 +000061 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +000062 if (!B) return QualType();
63 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
64 return D->getType();
65 return B.get<const Expr*>()->getType();
66 }
67
Richard Smith180f4792011-11-10 06:34:14 +000068 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000069 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000070 static
Richard Smithf15fda02012-02-02 01:16:57 +000071 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000072 APValue::BaseOrMemberType Value;
73 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000074 return Value;
75 }
76
77 /// Get an LValue path entry, which is known to not be an array index, as a
78 /// field declaration.
Richard Smith83587db2012-02-15 02:18:13 +000079 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000080 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000081 }
82 /// Get an LValue path entry, which is known to not be an array index, as a
83 /// base class declaration.
Richard Smith83587db2012-02-15 02:18:13 +000084 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000085 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000086 }
87 /// Determine whether this LValue path entry for a base class names a virtual
88 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +000089 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000090 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +000091 }
92
Richard Smithb4e85ed2012-01-06 16:39:00 +000093 /// Find the path length and type of the most-derived subobject in the given
94 /// path, and find the size of the containing array, if any.
95 static
96 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
97 ArrayRef<APValue::LValuePathEntry> Path,
98 uint64_t &ArraySize, QualType &Type) {
99 unsigned MostDerivedLength = 0;
100 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000101 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000102 if (Type->isArrayType()) {
103 const ConstantArrayType *CAT =
104 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
105 Type = CAT->getElementType();
106 ArraySize = CAT->getSize().getZExtValue();
107 MostDerivedLength = I + 1;
Richard Smith86024012012-02-18 22:04:06 +0000108 } else if (Type->isAnyComplexType()) {
109 const ComplexType *CT = Type->castAs<ComplexType>();
110 Type = CT->getElementType();
111 ArraySize = 2;
112 MostDerivedLength = I + 1;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000113 } else if (const FieldDecl *FD = getAsField(Path[I])) {
114 Type = FD->getType();
115 ArraySize = 0;
116 MostDerivedLength = I + 1;
117 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000118 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000119 ArraySize = 0;
120 }
Richard Smith9a17a682011-11-07 05:07:52 +0000121 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000122 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000123 }
124
Richard Smithb4e85ed2012-01-06 16:39:00 +0000125 // The order of this enum is important for diagnostics.
126 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000127 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith86024012012-02-18 22:04:06 +0000128 CSK_This, CSK_Real, CSK_Imag
Richard Smithb4e85ed2012-01-06 16:39:00 +0000129 };
130
Richard Smith0a3bdb62011-11-04 02:25:55 +0000131 /// A path from a glvalue to a subobject of that glvalue.
132 struct SubobjectDesignator {
133 /// True if the subobject was named in a manner not supported by C++11. Such
134 /// lvalues can still be folded, but they are not core constant expressions
135 /// and we cannot perform lvalue-to-rvalue conversions on them.
136 bool Invalid : 1;
137
Richard Smithb4e85ed2012-01-06 16:39:00 +0000138 /// Is this a pointer one past the end of an object?
139 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000140
Richard Smithb4e85ed2012-01-06 16:39:00 +0000141 /// The length of the path to the most-derived object of which this is a
142 /// subobject.
143 unsigned MostDerivedPathLength : 30;
144
145 /// The size of the array of which the most-derived object is an element, or
146 /// 0 if the most-derived object is not an array element.
147 uint64_t MostDerivedArraySize;
148
149 /// The type of the most derived object referred to by this address.
150 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000151
Richard Smith9a17a682011-11-07 05:07:52 +0000152 typedef APValue::LValuePathEntry PathEntry;
153
Richard Smith0a3bdb62011-11-04 02:25:55 +0000154 /// The entries on the path from the glvalue to the designated subobject.
155 SmallVector<PathEntry, 8> Entries;
156
Richard Smithb4e85ed2012-01-06 16:39:00 +0000157 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000158
Richard Smithb4e85ed2012-01-06 16:39:00 +0000159 explicit SubobjectDesignator(QualType T)
160 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
161 MostDerivedArraySize(0), MostDerivedType(T) {}
162
163 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
164 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
165 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000166 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000167 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000168 ArrayRef<PathEntry> VEntries = V.getLValuePath();
169 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
170 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000171 MostDerivedPathLength =
172 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
173 V.getLValuePath(), MostDerivedArraySize,
174 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000175 }
176 }
177
Richard Smith0a3bdb62011-11-04 02:25:55 +0000178 void setInvalid() {
179 Invalid = true;
180 Entries.clear();
181 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000182
183 /// Determine whether this is a one-past-the-end pointer.
184 bool isOnePastTheEnd() const {
185 if (IsOnePastTheEnd)
186 return true;
187 if (MostDerivedArraySize &&
188 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
189 return true;
190 return false;
191 }
192
193 /// Check that this refers to a valid subobject.
194 bool isValidSubobject() const {
195 if (Invalid)
196 return false;
197 return !isOnePastTheEnd();
198 }
199 /// Check that this refers to a valid subobject, and if not, produce a
200 /// relevant diagnostic and set the designator as invalid.
201 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
202
203 /// Update this designator to refer to the first element within this array.
204 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000205 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000206 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000207 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000208
209 // This is a most-derived object.
210 MostDerivedType = CAT->getElementType();
211 MostDerivedArraySize = CAT->getSize().getZExtValue();
212 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000213 }
214 /// Update this designator to refer to the given base or member of this
215 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000216 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000217 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000218 APValue::BaseOrMemberType Value(D, Virtual);
219 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000220 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000221
222 // If this isn't a base class, it's a new most-derived object.
223 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
224 MostDerivedType = FD->getType();
225 MostDerivedArraySize = 0;
226 MostDerivedPathLength = Entries.size();
227 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000228 }
Richard Smith86024012012-02-18 22:04:06 +0000229 /// Update this designator to refer to the given complex component.
230 void addComplexUnchecked(QualType EltTy, bool Imag) {
231 PathEntry Entry;
232 Entry.ArrayIndex = Imag;
233 Entries.push_back(Entry);
234
235 // This is technically a most-derived object, though in practice this
236 // is unlikely to matter.
237 MostDerivedType = EltTy;
238 MostDerivedArraySize = 2;
239 MostDerivedPathLength = Entries.size();
240 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000241 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000242 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000243 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000244 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000245 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000246 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000247 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
248 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
249 setInvalid();
250 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000251 return;
252 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000253 // [expr.add]p4: For the purposes of these operators, a pointer to a
254 // nonarray object behaves the same as a pointer to the first element of
255 // an array of length one with the type of the object as its element type.
256 if (IsOnePastTheEnd && N == (uint64_t)-1)
257 IsOnePastTheEnd = false;
258 else if (!IsOnePastTheEnd && N == 1)
259 IsOnePastTheEnd = true;
260 else if (N != 0) {
261 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000262 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000263 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000264 }
265 };
266
Richard Smithd0dccea2011-10-28 22:34:42 +0000267 /// A stack frame in the constexpr call stack.
268 struct CallStackFrame {
269 EvalInfo &Info;
270
271 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000272 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000273
Richard Smith08d6e032011-12-16 19:06:07 +0000274 /// CallLoc - The location of the call expression for this call.
275 SourceLocation CallLoc;
276
277 /// Callee - The function which was called.
278 const FunctionDecl *Callee;
279
Richard Smith83587db2012-02-15 02:18:13 +0000280 /// Index - The call index of this call.
281 unsigned Index;
282
Richard Smith180f4792011-11-10 06:34:14 +0000283 /// This - The binding for the this pointer in this call, if any.
284 const LValue *This;
285
Richard Smithd0dccea2011-10-28 22:34:42 +0000286 /// ParmBindings - Parameter bindings for this function call, indexed by
287 /// parameters' function scope indices.
Richard Smith1aa0be82012-03-03 22:46:17 +0000288 const APValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000289
Richard Smith1aa0be82012-03-03 22:46:17 +0000290 typedef llvm::DenseMap<const Expr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000291 typedef MapTy::const_iterator temp_iterator;
292 /// Temporaries - Temporary lvalues materialized within this stack frame.
293 MapTy Temporaries;
294
Richard Smith08d6e032011-12-16 19:06:07 +0000295 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
296 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000297 const APValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000298 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000299 };
300
Richard Smithdd1f29b2011-12-12 09:28:41 +0000301 /// A partial diagnostic which we might know in advance that we are not going
302 /// to emit.
303 class OptionalDiagnostic {
304 PartialDiagnostic *Diag;
305
306 public:
307 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
308
309 template<typename T>
310 OptionalDiagnostic &operator<<(const T &v) {
311 if (Diag)
312 *Diag << v;
313 return *this;
314 }
Richard Smith789f9b62012-01-31 04:08:20 +0000315
316 OptionalDiagnostic &operator<<(const APSInt &I) {
317 if (Diag) {
318 llvm::SmallVector<char, 32> Buffer;
319 I.toString(Buffer);
320 *Diag << StringRef(Buffer.data(), Buffer.size());
321 }
322 return *this;
323 }
324
325 OptionalDiagnostic &operator<<(const APFloat &F) {
326 if (Diag) {
327 llvm::SmallVector<char, 32> Buffer;
328 F.toString(Buffer);
329 *Diag << StringRef(Buffer.data(), Buffer.size());
330 }
331 return *this;
332 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000333 };
334
Richard Smith83587db2012-02-15 02:18:13 +0000335 /// EvalInfo - This is a private struct used by the evaluator to capture
336 /// information about a subexpression as it is folded. It retains information
337 /// about the AST context, but also maintains information about the folded
338 /// expression.
339 ///
340 /// If an expression could be evaluated, it is still possible it is not a C
341 /// "integer constant expression" or constant expression. If not, this struct
342 /// captures information about how and why not.
343 ///
344 /// One bit of information passed *into* the request for constant folding
345 /// indicates whether the subexpression is "evaluated" or not according to C
346 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
347 /// evaluate the expression regardless of what the RHS is, but C only allows
348 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000349 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000350 ASTContext &Ctx;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000351
Richard Smithbd552ef2011-10-31 05:52:43 +0000352 /// EvalStatus - Contains information about the evaluation.
353 Expr::EvalStatus &EvalStatus;
354
355 /// CurrentCall - The top of the constexpr call stack.
356 CallStackFrame *CurrentCall;
357
Richard Smithbd552ef2011-10-31 05:52:43 +0000358 /// CallStackDepth - The number of calls in the call stack right now.
359 unsigned CallStackDepth;
360
Richard Smith83587db2012-02-15 02:18:13 +0000361 /// NextCallIndex - The next call index to assign.
362 unsigned NextCallIndex;
363
Richard Smith1aa0be82012-03-03 22:46:17 +0000364 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000365 /// OpaqueValues - Values used as the common expression in a
366 /// BinaryConditionalOperator.
367 MapTy OpaqueValues;
368
369 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000370 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000371 CallStackFrame BottomFrame;
372
Richard Smith180f4792011-11-10 06:34:14 +0000373 /// EvaluatingDecl - This is the declaration whose initializer is being
374 /// evaluated, if any.
375 const VarDecl *EvaluatingDecl;
376
377 /// EvaluatingDeclValue - This is the value being constructed for the
378 /// declaration whose initializer is being evaluated, if any.
379 APValue *EvaluatingDeclValue;
380
Richard Smithc1c5f272011-12-13 06:39:58 +0000381 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
382 /// notes attached to it will also be stored, otherwise they will not be.
383 bool HasActiveDiagnostic;
384
Richard Smith745f5142012-01-27 01:14:48 +0000385 /// CheckingPotentialConstantExpression - Are we checking whether the
386 /// expression is a potential constant expression? If so, some diagnostics
387 /// are suppressed.
388 bool CheckingPotentialConstantExpression;
389
Richard Smithbd552ef2011-10-31 05:52:43 +0000390 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000391 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000392 CallStackDepth(0), NextCallIndex(1),
393 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000394 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Argyrios Kyrtzidis649dfbc2012-03-15 18:07:13 +0000395 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000396
Richard Smith1aa0be82012-03-03 22:46:17 +0000397 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
Richard Smithbd552ef2011-10-31 05:52:43 +0000398 MapTy::const_iterator i = OpaqueValues.find(e);
399 if (i == OpaqueValues.end()) return 0;
400 return &i->second;
401 }
402
Richard Smith180f4792011-11-10 06:34:14 +0000403 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
404 EvaluatingDecl = VD;
405 EvaluatingDeclValue = &Value;
406 }
407
David Blaikie4e4d0842012-03-11 07:00:24 +0000408 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000409
Richard Smithc1c5f272011-12-13 06:39:58 +0000410 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000411 // Don't perform any constexpr calls (other than the call we're checking)
412 // when checking a potential constant expression.
413 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
414 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000415 if (NextCallIndex == 0) {
416 // NextCallIndex has wrapped around.
417 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
418 return false;
419 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000420 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
421 return true;
422 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
423 << getLangOpts().ConstexprCallDepth;
424 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000425 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000426
Richard Smith83587db2012-02-15 02:18:13 +0000427 CallStackFrame *getCallFrame(unsigned CallIndex) {
428 assert(CallIndex && "no call index in getCallFrame");
429 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
430 // be null in this loop.
431 CallStackFrame *Frame = CurrentCall;
432 while (Frame->Index > CallIndex)
433 Frame = Frame->Caller;
434 return (Frame->Index == CallIndex) ? Frame : 0;
435 }
436
Richard Smithc1c5f272011-12-13 06:39:58 +0000437 private:
438 /// Add a diagnostic to the diagnostics list.
439 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
440 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
441 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
442 return EvalStatus.Diag->back().second;
443 }
444
Richard Smith08d6e032011-12-16 19:06:07 +0000445 /// Add notes containing a call stack to the current point of evaluation.
446 void addCallStack(unsigned Limit);
447
Richard Smithc1c5f272011-12-13 06:39:58 +0000448 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000449 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000450 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
451 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000452 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000453 // If we have a prior diagnostic, it will be noting that the expression
454 // isn't a constant expression. This diagnostic is more important.
455 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000456 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000457 unsigned CallStackNotes = CallStackDepth - 1;
458 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
459 if (Limit)
460 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000461 if (CheckingPotentialConstantExpression)
462 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000463
Richard Smithc1c5f272011-12-13 06:39:58 +0000464 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000465 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000466 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
467 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000468 if (!CheckingPotentialConstantExpression)
469 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000470 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000471 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000472 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000473 return OptionalDiagnostic();
474 }
475
Richard Smith5cfc7d82012-03-15 04:53:45 +0000476 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
477 = diag::note_invalid_subexpr_in_const_expr,
478 unsigned ExtraNotes = 0) {
479 if (EvalStatus.Diag)
480 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
481 HasActiveDiagnostic = false;
482 return OptionalDiagnostic();
483 }
484
Richard Smithdd1f29b2011-12-12 09:28:41 +0000485 /// Diagnose that the evaluation does not produce a C++11 core constant
486 /// expression.
Richard Smith5cfc7d82012-03-15 04:53:45 +0000487 template<typename LocArg>
488 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000489 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000490 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000491 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000492 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
493 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000494 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000495 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000496 return Diag(Loc, DiagId, ExtraNotes);
497 }
498
499 /// Add a note to a prior diagnostic.
500 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
501 if (!HasActiveDiagnostic)
502 return OptionalDiagnostic();
503 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000504 }
Richard Smith099e7f62011-12-19 06:19:21 +0000505
506 /// Add a stack of notes to a prior diagnostic.
507 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
508 if (HasActiveDiagnostic) {
509 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
510 Diags.begin(), Diags.end());
511 }
512 }
Richard Smith745f5142012-01-27 01:14:48 +0000513
514 /// Should we continue evaluation as much as possible after encountering a
515 /// construct which can't be folded?
516 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000517 return CheckingPotentialConstantExpression &&
518 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000519 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000520 };
Richard Smithf15fda02012-02-02 01:16:57 +0000521
522 /// Object used to treat all foldable expressions as constant expressions.
523 struct FoldConstant {
524 bool Enabled;
525
526 explicit FoldConstant(EvalInfo &Info)
527 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
528 !Info.EvalStatus.HasSideEffects) {
529 }
530 // Treat the value we've computed since this object was created as constant.
531 void Fold(EvalInfo &Info) {
532 if (Enabled && !Info.EvalStatus.Diag->empty() &&
533 !Info.EvalStatus.HasSideEffects)
534 Info.EvalStatus.Diag->clear();
535 }
536 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000537
538 /// RAII object used to suppress diagnostics and side-effects from a
539 /// speculative evaluation.
540 class SpeculativeEvaluationRAII {
541 EvalInfo &Info;
542 Expr::EvalStatus Old;
543
544 public:
545 SpeculativeEvaluationRAII(EvalInfo &Info,
546 llvm::SmallVectorImpl<PartialDiagnosticAt>
547 *NewDiag = 0)
548 : Info(Info), Old(Info.EvalStatus) {
549 Info.EvalStatus.Diag = NewDiag;
550 }
551 ~SpeculativeEvaluationRAII() {
552 Info.EvalStatus = Old;
553 }
554 };
Richard Smith08d6e032011-12-16 19:06:07 +0000555}
Richard Smithbd552ef2011-10-31 05:52:43 +0000556
Richard Smithb4e85ed2012-01-06 16:39:00 +0000557bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
558 CheckSubobjectKind CSK) {
559 if (Invalid)
560 return false;
561 if (isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000562 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000563 << CSK;
564 setInvalid();
565 return false;
566 }
567 return true;
568}
569
570void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
571 const Expr *E, uint64_t N) {
572 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000573 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000574 << static_cast<int>(N) << /*array*/ 0
575 << static_cast<unsigned>(MostDerivedArraySize);
576 else
Richard Smith5cfc7d82012-03-15 04:53:45 +0000577 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000578 << static_cast<int>(N) << /*non-array*/ 1;
579 setInvalid();
580}
581
Richard Smith08d6e032011-12-16 19:06:07 +0000582CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
583 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000584 const APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000585 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000586 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000587 Info.CurrentCall = this;
588 ++Info.CallStackDepth;
589}
590
591CallStackFrame::~CallStackFrame() {
592 assert(Info.CurrentCall == this && "calls retired out of order");
593 --Info.CallStackDepth;
594 Info.CurrentCall = Caller;
595}
596
597/// Produce a string describing the given constexpr call.
598static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
599 unsigned ArgIndex = 0;
600 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000601 !isa<CXXConstructorDecl>(Frame->Callee) &&
602 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000603
604 if (!IsMemberCall)
605 Out << *Frame->Callee << '(';
606
607 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
608 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000609 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000610 Out << ", ";
611
612 const ParmVarDecl *Param = *I;
Richard Smith1aa0be82012-03-03 22:46:17 +0000613 const APValue &Arg = Frame->Arguments[ArgIndex];
614 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smith08d6e032011-12-16 19:06:07 +0000615
616 if (ArgIndex == 0 && IsMemberCall)
617 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000618 }
619
Richard Smith08d6e032011-12-16 19:06:07 +0000620 Out << ')';
621}
622
623void EvalInfo::addCallStack(unsigned Limit) {
624 // Determine which calls to skip, if any.
625 unsigned ActiveCalls = CallStackDepth - 1;
626 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
627 if (Limit && Limit < ActiveCalls) {
628 SkipStart = Limit / 2 + Limit % 2;
629 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000630 }
631
Richard Smith08d6e032011-12-16 19:06:07 +0000632 // Walk the call stack and add the diagnostics.
633 unsigned CallIdx = 0;
634 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
635 Frame = Frame->Caller, ++CallIdx) {
636 // Skip this call?
637 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
638 if (CallIdx == SkipStart) {
639 // Note that we're skipping calls.
640 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
641 << unsigned(ActiveCalls - Limit);
642 }
643 continue;
644 }
645
646 llvm::SmallVector<char, 128> Buffer;
647 llvm::raw_svector_ostream Out(Buffer);
648 describeCall(Frame, Out);
649 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
650 }
651}
652
653namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000654 struct ComplexValue {
655 private:
656 bool IsInt;
657
658 public:
659 APSInt IntReal, IntImag;
660 APFloat FloatReal, FloatImag;
661
662 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
663
664 void makeComplexFloat() { IsInt = false; }
665 bool isComplexFloat() const { return !IsInt; }
666 APFloat &getComplexFloatReal() { return FloatReal; }
667 APFloat &getComplexFloatImag() { return FloatImag; }
668
669 void makeComplexInt() { IsInt = true; }
670 bool isComplexInt() const { return IsInt; }
671 APSInt &getComplexIntReal() { return IntReal; }
672 APSInt &getComplexIntImag() { return IntImag; }
673
Richard Smith1aa0be82012-03-03 22:46:17 +0000674 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000675 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000676 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000677 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000678 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000679 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000680 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000681 assert(v.isComplexFloat() || v.isComplexInt());
682 if (v.isComplexFloat()) {
683 makeComplexFloat();
684 FloatReal = v.getComplexFloatReal();
685 FloatImag = v.getComplexFloatImag();
686 } else {
687 makeComplexInt();
688 IntReal = v.getComplexIntReal();
689 IntImag = v.getComplexIntImag();
690 }
691 }
John McCallf4cf1a12010-05-07 17:22:02 +0000692 };
John McCallefdb83e2010-05-07 21:00:08 +0000693
694 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000695 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000696 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000697 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000698 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000699
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000700 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000701 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000702 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000703 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000704 SubobjectDesignator &getLValueDesignator() { return Designator; }
705 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000706
Richard Smith1aa0be82012-03-03 22:46:17 +0000707 void moveInto(APValue &V) const {
708 if (Designator.Invalid)
709 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
710 else
711 V = APValue(Base, Offset, Designator.Entries,
712 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000713 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000714 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000715 assert(V.isLValue());
716 Base = V.getLValueBase();
717 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000718 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000719 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000720 }
721
Richard Smith83587db2012-02-15 02:18:13 +0000722 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000723 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000724 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000725 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000726 Designator = SubobjectDesignator(getType(B));
727 }
728
729 // Check that this LValue is not based on a null pointer. If it is, produce
730 // a diagnostic and mark the designator as invalid.
731 bool checkNullPointer(EvalInfo &Info, const Expr *E,
732 CheckSubobjectKind CSK) {
733 if (Designator.Invalid)
734 return false;
735 if (!Base) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000736 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000737 << CSK;
738 Designator.setInvalid();
739 return false;
740 }
741 return true;
742 }
743
744 // Check this LValue refers to an object. If not, set the designator to be
745 // invalid and emit a diagnostic.
746 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000747 // Outside C++11, do not build a designator referring to a subobject of
748 // any object: we won't use such a designator for anything.
749 if (!Info.getLangOpts().CPlusPlus0x)
750 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000751 return checkNullPointer(Info, E, CSK) &&
752 Designator.checkSubobject(Info, E, CSK);
753 }
754
755 void addDecl(EvalInfo &Info, const Expr *E,
756 const Decl *D, bool Virtual = false) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000757 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
758 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000759 }
760 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000761 if (checkSubobject(Info, E, CSK_ArrayToPointer))
762 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000763 }
Richard Smith86024012012-02-18 22:04:06 +0000764 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000765 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
766 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000767 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000768 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000769 if (checkNullPointer(Info, E, CSK_ArrayIndex))
770 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000771 }
John McCallefdb83e2010-05-07 21:00:08 +0000772 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000773
774 struct MemberPtr {
775 MemberPtr() {}
776 explicit MemberPtr(const ValueDecl *Decl) :
777 DeclAndIsDerivedMember(Decl, false), Path() {}
778
779 /// The member or (direct or indirect) field referred to by this member
780 /// pointer, or 0 if this is a null member pointer.
781 const ValueDecl *getDecl() const {
782 return DeclAndIsDerivedMember.getPointer();
783 }
784 /// Is this actually a member of some type derived from the relevant class?
785 bool isDerivedMember() const {
786 return DeclAndIsDerivedMember.getInt();
787 }
788 /// Get the class which the declaration actually lives in.
789 const CXXRecordDecl *getContainingRecord() const {
790 return cast<CXXRecordDecl>(
791 DeclAndIsDerivedMember.getPointer()->getDeclContext());
792 }
793
Richard Smith1aa0be82012-03-03 22:46:17 +0000794 void moveInto(APValue &V) const {
795 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000796 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000797 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000798 assert(V.isMemberPointer());
799 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
800 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
801 Path.clear();
802 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
803 Path.insert(Path.end(), P.begin(), P.end());
804 }
805
806 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
807 /// whether the member is a member of some class derived from the class type
808 /// of the member pointer.
809 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
810 /// Path - The path of base/derived classes from the member declaration's
811 /// class (exclusive) to the class type of the member pointer (inclusive).
812 SmallVector<const CXXRecordDecl*, 4> Path;
813
814 /// Perform a cast towards the class of the Decl (either up or down the
815 /// hierarchy).
816 bool castBack(const CXXRecordDecl *Class) {
817 assert(!Path.empty());
818 const CXXRecordDecl *Expected;
819 if (Path.size() >= 2)
820 Expected = Path[Path.size() - 2];
821 else
822 Expected = getContainingRecord();
823 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
824 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
825 // if B does not contain the original member and is not a base or
826 // derived class of the class containing the original member, the result
827 // of the cast is undefined.
828 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
829 // (D::*). We consider that to be a language defect.
830 return false;
831 }
832 Path.pop_back();
833 return true;
834 }
835 /// Perform a base-to-derived member pointer cast.
836 bool castToDerived(const CXXRecordDecl *Derived) {
837 if (!getDecl())
838 return true;
839 if (!isDerivedMember()) {
840 Path.push_back(Derived);
841 return true;
842 }
843 if (!castBack(Derived))
844 return false;
845 if (Path.empty())
846 DeclAndIsDerivedMember.setInt(false);
847 return true;
848 }
849 /// Perform a derived-to-base member pointer cast.
850 bool castToBase(const CXXRecordDecl *Base) {
851 if (!getDecl())
852 return true;
853 if (Path.empty())
854 DeclAndIsDerivedMember.setInt(true);
855 if (isDerivedMember()) {
856 Path.push_back(Base);
857 return true;
858 }
859 return castBack(Base);
860 }
861 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000862
Richard Smithb02e4622012-02-01 01:42:44 +0000863 /// Compare two member pointers, which are assumed to be of the same type.
864 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
865 if (!LHS.getDecl() || !RHS.getDecl())
866 return !LHS.getDecl() && !RHS.getDecl();
867 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
868 return false;
869 return LHS.Path == RHS.Path;
870 }
871
Richard Smithc1c5f272011-12-13 06:39:58 +0000872 /// Kinds of constant expression checking, for diagnostics.
873 enum CheckConstantExpressionKind {
874 CCEK_Constant, ///< A normal constant.
875 CCEK_ReturnValue, ///< A constexpr function return value.
876 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
877 };
John McCallf4cf1a12010-05-07 17:22:02 +0000878}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000879
Richard Smith1aa0be82012-03-03 22:46:17 +0000880static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000881static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
882 const LValue &This, const Expr *E,
883 CheckConstantExpressionKind CCEK = CCEK_Constant,
884 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000885static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
886static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000887static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
888 EvalInfo &Info);
889static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000890static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000891static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000892 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000893static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000894static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000895
896//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000897// Misc utilities
898//===----------------------------------------------------------------------===//
899
Richard Smith180f4792011-11-10 06:34:14 +0000900/// Should this call expression be treated as a string literal?
901static bool IsStringLiteralCall(const CallExpr *E) {
902 unsigned Builtin = E->isBuiltinCall();
903 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
904 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
905}
906
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000907static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000908 // C++11 [expr.const]p3 An address constant expression is a prvalue core
909 // constant expression of pointer type that evaluates to...
910
911 // ... a null pointer value, or a prvalue core constant expression of type
912 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000913 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000914
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000915 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
916 // ... the address of an object with static storage duration,
917 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
918 return VD->hasGlobalStorage();
919 // ... the address of a function,
920 return isa<FunctionDecl>(D);
921 }
922
923 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000924 switch (E->getStmtClass()) {
925 default:
926 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000927 case Expr::CompoundLiteralExprClass: {
928 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
929 return CLE->isFileScope() && CLE->isLValue();
930 }
Richard Smith180f4792011-11-10 06:34:14 +0000931 // A string literal has static storage duration.
932 case Expr::StringLiteralClass:
933 case Expr::PredefinedExprClass:
934 case Expr::ObjCStringLiteralClass:
935 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000936 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000937 return true;
938 case Expr::CallExprClass:
939 return IsStringLiteralCall(cast<CallExpr>(E));
940 // For GCC compatibility, &&label has static storage duration.
941 case Expr::AddrLabelExprClass:
942 return true;
943 // A Block literal expression may be used as the initialization value for
944 // Block variables at global or local static scope.
945 case Expr::BlockExprClass:
946 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000947 case Expr::ImplicitValueInitExprClass:
948 // FIXME:
949 // We can never form an lvalue with an implicit value initialization as its
950 // base through expression evaluation, so these only appear in one case: the
951 // implicit variable declaration we invent when checking whether a constexpr
952 // constructor can produce a constant expression. We must assume that such
953 // an expression might be a global lvalue.
954 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000955 }
John McCall42c8f872010-05-10 23:27:23 +0000956}
957
Richard Smith83587db2012-02-15 02:18:13 +0000958static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
959 assert(Base && "no location for a null lvalue");
960 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
961 if (VD)
962 Info.Note(VD->getLocation(), diag::note_declared_at);
963 else
964 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
965 diag::note_constexpr_temporary_here);
966}
967
Richard Smith9a17a682011-11-07 05:07:52 +0000968/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000969/// value for an address or reference constant expression. Return true if we
970/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000971static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
972 QualType Type, const LValue &LVal) {
973 bool IsReferenceType = Type->isReferenceType();
974
Richard Smithc1c5f272011-12-13 06:39:58 +0000975 APValue::LValueBase Base = LVal.getLValueBase();
976 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
977
Richard Smithb78ae972012-02-18 04:58:18 +0000978 // Check that the object is a global. Note that the fake 'this' object we
979 // manufacture when checking potential constant expressions is conservatively
980 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000981 if (!IsGlobalLValue(Base)) {
982 if (Info.getLangOpts().CPlusPlus0x) {
983 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000984 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
985 << IsReferenceType << !Designator.Entries.empty()
986 << !!VD << VD;
987 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000988 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000989 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000990 }
Richard Smith61e61622012-01-12 06:08:57 +0000991 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000992 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000993 }
Richard Smith83587db2012-02-15 02:18:13 +0000994 assert((Info.CheckingPotentialConstantExpression ||
995 LVal.getLValueCallIndex() == 0) &&
996 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +0000997
998 // Allow address constant expressions to be past-the-end pointers. This is
999 // an extension: the standard requires them to point to an object.
1000 if (!IsReferenceType)
1001 return true;
1002
1003 // A reference constant expression must refer to an object.
1004 if (!Base) {
1005 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001006 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001007 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001008 }
1009
Richard Smithc1c5f272011-12-13 06:39:58 +00001010 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001011 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001012 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001013 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001014 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001015 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001016 }
1017
Richard Smith9a17a682011-11-07 05:07:52 +00001018 return true;
1019}
1020
Richard Smith51201882011-12-30 21:15:51 +00001021/// Check that this core constant expression is of literal type, and if not,
1022/// produce an appropriate diagnostic.
1023static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1024 if (!E->isRValue() || E->getType()->isLiteralType())
1025 return true;
1026
1027 // Prvalue constant expressions must be of literal types.
1028 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001029 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001030 << E->getType();
1031 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001032 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001033 return false;
1034}
1035
Richard Smith47a1eed2011-10-29 20:57:55 +00001036/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001037/// constant expression. If not, report an appropriate diagnostic. Does not
1038/// check that the expression is of literal type.
1039static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1040 QualType Type, const APValue &Value) {
1041 // Core issue 1454: For a literal constant expression of array or class type,
1042 // each subobject of its value shall have been initialized by a constant
1043 // expression.
1044 if (Value.isArray()) {
1045 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1046 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1047 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1048 Value.getArrayInitializedElt(I)))
1049 return false;
1050 }
1051 if (!Value.hasArrayFiller())
1052 return true;
1053 return CheckConstantExpression(Info, DiagLoc, EltTy,
1054 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001055 }
Richard Smith83587db2012-02-15 02:18:13 +00001056 if (Value.isUnion() && Value.getUnionField()) {
1057 return CheckConstantExpression(Info, DiagLoc,
1058 Value.getUnionField()->getType(),
1059 Value.getUnionValue());
1060 }
1061 if (Value.isStruct()) {
1062 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1063 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1064 unsigned BaseIndex = 0;
1065 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1066 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1067 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1068 Value.getStructBase(BaseIndex)))
1069 return false;
1070 }
1071 }
1072 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1073 I != E; ++I) {
1074 if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
1075 Value.getStructField((*I)->getFieldIndex())))
1076 return false;
1077 }
1078 }
1079
1080 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001081 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001082 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001083 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1084 }
1085
1086 // Everything else is fine.
1087 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001088}
1089
Richard Smith9e36b532011-10-31 05:11:32 +00001090const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001091 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001092}
1093
1094static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001095 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001096}
1097
Richard Smith65ac5982011-11-01 21:06:14 +00001098static bool IsWeakLValue(const LValue &Value) {
1099 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001100 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001101}
1102
Richard Smith1aa0be82012-03-03 22:46:17 +00001103static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001104 // A null base expression indicates a null pointer. These are always
1105 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001106 if (!Value.getLValueBase()) {
1107 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001108 return true;
1109 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001110
Richard Smithe24f5fc2011-11-17 22:56:20 +00001111 // We have a non-null base. These are generally known to be true, but if it's
1112 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001113 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001114 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001115 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001116}
1117
Richard Smith1aa0be82012-03-03 22:46:17 +00001118static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001119 switch (Val.getKind()) {
1120 case APValue::Uninitialized:
1121 return false;
1122 case APValue::Int:
1123 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001124 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001125 case APValue::Float:
1126 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001127 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001128 case APValue::ComplexInt:
1129 Result = Val.getComplexIntReal().getBoolValue() ||
1130 Val.getComplexIntImag().getBoolValue();
1131 return true;
1132 case APValue::ComplexFloat:
1133 Result = !Val.getComplexFloatReal().isZero() ||
1134 !Val.getComplexFloatImag().isZero();
1135 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001136 case APValue::LValue:
1137 return EvalPointerValueAsBool(Val, Result);
1138 case APValue::MemberPointer:
1139 Result = Val.getMemberPointerDecl();
1140 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001141 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001142 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001143 case APValue::Struct:
1144 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001145 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001146 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001147 }
1148
Richard Smithc49bd112011-10-28 17:51:58 +00001149 llvm_unreachable("unknown APValue kind");
1150}
1151
1152static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1153 EvalInfo &Info) {
1154 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001155 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001156 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001157 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001158 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001159}
1160
Richard Smithc1c5f272011-12-13 06:39:58 +00001161template<typename T>
1162static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1163 const T &SrcValue, QualType DestType) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001164 Info.Diag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001165 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001166 return false;
1167}
1168
1169static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1170 QualType SrcType, const APFloat &Value,
1171 QualType DestType, APSInt &Result) {
1172 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001173 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001174 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Richard Smithc1c5f272011-12-13 06:39:58 +00001176 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001177 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001178 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1179 & APFloat::opInvalidOp)
1180 return HandleOverflow(Info, E, Value, DestType);
1181 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001182}
1183
Richard Smithc1c5f272011-12-13 06:39:58 +00001184static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1185 QualType SrcType, QualType DestType,
1186 APFloat &Result) {
1187 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001188 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001189 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1190 APFloat::rmNearestTiesToEven, &ignored)
1191 & APFloat::opOverflow)
1192 return HandleOverflow(Info, E, Value, DestType);
1193 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001194}
1195
Richard Smithf72fccf2012-01-30 22:27:01 +00001196static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1197 QualType DestType, QualType SrcType,
1198 APSInt &Value) {
1199 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001200 APSInt Result = Value;
1201 // Figure out if this is a truncate, extend or noop cast.
1202 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001203 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001204 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001205 return Result;
1206}
1207
Richard Smithc1c5f272011-12-13 06:39:58 +00001208static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1209 QualType SrcType, const APSInt &Value,
1210 QualType DestType, APFloat &Result) {
1211 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1212 if (Result.convertFromAPInt(Value, Value.isSigned(),
1213 APFloat::rmNearestTiesToEven)
1214 & APFloat::opOverflow)
1215 return HandleOverflow(Info, E, Value, DestType);
1216 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001217}
1218
Eli Friedmane6a24e82011-12-22 03:51:45 +00001219static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1220 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001221 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001222 if (!Evaluate(SVal, Info, E))
1223 return false;
1224 if (SVal.isInt()) {
1225 Res = SVal.getInt();
1226 return true;
1227 }
1228 if (SVal.isFloat()) {
1229 Res = SVal.getFloat().bitcastToAPInt();
1230 return true;
1231 }
1232 if (SVal.isVector()) {
1233 QualType VecTy = E->getType();
1234 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1235 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1236 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1237 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1238 Res = llvm::APInt::getNullValue(VecSize);
1239 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1240 APValue &Elt = SVal.getVectorElt(i);
1241 llvm::APInt EltAsInt;
1242 if (Elt.isInt()) {
1243 EltAsInt = Elt.getInt();
1244 } else if (Elt.isFloat()) {
1245 EltAsInt = Elt.getFloat().bitcastToAPInt();
1246 } else {
1247 // Don't try to handle vectors of anything other than int or float
1248 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001249 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001250 return false;
1251 }
1252 unsigned BaseEltSize = EltAsInt.getBitWidth();
1253 if (BigEndian)
1254 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1255 else
1256 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1257 }
1258 return true;
1259 }
1260 // Give up if the input isn't an int, float, or vector. For example, we
1261 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001262 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001263 return false;
1264}
1265
Richard Smithb4e85ed2012-01-06 16:39:00 +00001266/// Cast an lvalue referring to a base subobject to a derived class, by
1267/// truncating the lvalue's path to the given length.
1268static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1269 const RecordDecl *TruncatedType,
1270 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001271 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001272
1273 // Check we actually point to a derived class object.
1274 if (TruncatedElements == D.Entries.size())
1275 return true;
1276 assert(TruncatedElements >= D.MostDerivedPathLength &&
1277 "not casting to a derived class");
1278 if (!Result.checkSubobject(Info, E, CSK_Derived))
1279 return false;
1280
1281 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001282 const RecordDecl *RD = TruncatedType;
1283 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001284 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1285 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001286 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001287 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001288 else
Richard Smith180f4792011-11-10 06:34:14 +00001289 Result.Offset -= Layout.getBaseClassOffset(Base);
1290 RD = Base;
1291 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001292 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001293 return true;
1294}
1295
Richard Smithb4e85ed2012-01-06 16:39:00 +00001296static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001297 const CXXRecordDecl *Derived,
1298 const CXXRecordDecl *Base,
1299 const ASTRecordLayout *RL = 0) {
1300 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1301 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001302 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001303}
1304
Richard Smithb4e85ed2012-01-06 16:39:00 +00001305static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001306 const CXXRecordDecl *DerivedDecl,
1307 const CXXBaseSpecifier *Base) {
1308 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1309
1310 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001311 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001312 return true;
1313 }
1314
Richard Smithb4e85ed2012-01-06 16:39:00 +00001315 SubobjectDesignator &D = Obj.Designator;
1316 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001317 return false;
1318
Richard Smithb4e85ed2012-01-06 16:39:00 +00001319 // Extract most-derived object and corresponding type.
1320 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1321 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1322 return false;
1323
1324 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001325 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1326 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001327 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001328 return true;
1329}
1330
1331/// Update LVal to refer to the given field, which must be a member of the type
1332/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001333static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001334 const FieldDecl *FD,
1335 const ASTRecordLayout *RL = 0) {
1336 if (!RL)
1337 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1338
1339 unsigned I = FD->getFieldIndex();
1340 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001341 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001342}
1343
Richard Smithd9b02e72012-01-25 22:15:11 +00001344/// Update LVal to refer to the given indirect field.
1345static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1346 LValue &LVal,
1347 const IndirectFieldDecl *IFD) {
1348 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1349 CE = IFD->chain_end(); C != CE; ++C)
1350 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1351}
1352
Richard Smith180f4792011-11-10 06:34:14 +00001353/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001354static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1355 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001356 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1357 // extension.
1358 if (Type->isVoidType() || Type->isFunctionType()) {
1359 Size = CharUnits::One();
1360 return true;
1361 }
1362
1363 if (!Type->isConstantSizeType()) {
1364 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001365 // FIXME: Better diagnostic.
1366 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001367 return false;
1368 }
1369
1370 Size = Info.Ctx.getTypeSizeInChars(Type);
1371 return true;
1372}
1373
1374/// Update a pointer value to model pointer arithmetic.
1375/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001376/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001377/// \param LVal - The pointer value to be updated.
1378/// \param EltTy - The pointee type represented by LVal.
1379/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001380static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1381 LValue &LVal, QualType EltTy,
1382 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001383 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001384 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001385 return false;
1386
1387 // Compute the new offset in the appropriate width.
1388 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001389 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001390 return true;
1391}
1392
Richard Smith86024012012-02-18 22:04:06 +00001393/// Update an lvalue to refer to a component of a complex number.
1394/// \param Info - Information about the ongoing evaluation.
1395/// \param LVal - The lvalue to be updated.
1396/// \param EltTy - The complex number's component type.
1397/// \param Imag - False for the real component, true for the imaginary.
1398static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1399 LValue &LVal, QualType EltTy,
1400 bool Imag) {
1401 if (Imag) {
1402 CharUnits SizeOfComponent;
1403 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1404 return false;
1405 LVal.Offset += SizeOfComponent;
1406 }
1407 LVal.addComplex(Info, E, EltTy, Imag);
1408 return true;
1409}
1410
Richard Smith03f96112011-10-24 17:54:18 +00001411/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001412static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1413 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001414 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001415 // If this is a parameter to an active constexpr function call, perform
1416 // argument substitution.
1417 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001418 // Assume arguments of a potential constant expression are unknown
1419 // constant expressions.
1420 if (Info.CheckingPotentialConstantExpression)
1421 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001422 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001423 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001424 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001425 }
Richard Smith177dce72011-11-01 16:57:24 +00001426 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1427 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001428 }
Richard Smith03f96112011-10-24 17:54:18 +00001429
Richard Smith099e7f62011-12-19 06:19:21 +00001430 // Dig out the initializer, and use the declaration which it's attached to.
1431 const Expr *Init = VD->getAnyInitializer(VD);
1432 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001433 // If we're checking a potential constant expression, the variable could be
1434 // initialized later.
1435 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001436 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001437 return false;
1438 }
1439
Richard Smith180f4792011-11-10 06:34:14 +00001440 // If we're currently evaluating the initializer of this declaration, use that
1441 // in-flight value.
1442 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001443 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001444 return !Result.isUninit();
1445 }
1446
Richard Smith65ac5982011-11-01 21:06:14 +00001447 // Never evaluate the initializer of a weak variable. We can't be sure that
1448 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001449 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001450 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001451 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001452 }
Richard Smith65ac5982011-11-01 21:06:14 +00001453
Richard Smith099e7f62011-12-19 06:19:21 +00001454 // Check that we can fold the initializer. In C++, we will have already done
1455 // this in the cases where it matters for conformance.
1456 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1457 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001458 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001459 Notes.size() + 1) << VD;
1460 Info.Note(VD->getLocation(), diag::note_declared_at);
1461 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001462 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001463 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001464 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001465 Notes.size() + 1) << VD;
1466 Info.Note(VD->getLocation(), diag::note_declared_at);
1467 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001468 }
Richard Smith03f96112011-10-24 17:54:18 +00001469
Richard Smith1aa0be82012-03-03 22:46:17 +00001470 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001471 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001472}
1473
Richard Smithc49bd112011-10-28 17:51:58 +00001474static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001475 Qualifiers Quals = T.getQualifiers();
1476 return Quals.hasConst() && !Quals.hasVolatile();
1477}
1478
Richard Smith59efe262011-11-11 04:05:33 +00001479/// Get the base index of the given base class within an APValue representing
1480/// the given derived class.
1481static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1482 const CXXRecordDecl *Base) {
1483 Base = Base->getCanonicalDecl();
1484 unsigned Index = 0;
1485 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1486 E = Derived->bases_end(); I != E; ++I, ++Index) {
1487 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1488 return Index;
1489 }
1490
1491 llvm_unreachable("base class missing from derived class's bases list");
1492}
1493
Richard Smithf3908f22012-02-17 03:35:37 +00001494/// Extract the value of a character from a string literal.
1495static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1496 uint64_t Index) {
1497 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1498 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1499 assert(S && "unexpected string literal expression kind");
1500
1501 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1502 Lit->getType()->getArrayElementTypeNoTypeQual()->isUnsignedIntegerType());
1503 if (Index < S->getLength())
1504 Value = S->getCodeUnit(Index);
1505 return Value;
1506}
1507
Richard Smithcc5d4f62011-11-07 09:22:26 +00001508/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001509static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001510 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001511 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001512 if (Sub.Invalid)
1513 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001514 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001515 if (Sub.isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001516 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001517 (unsigned)diag::note_constexpr_read_past_end :
1518 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001519 return false;
1520 }
Richard Smithf64699e2011-11-11 08:28:03 +00001521 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001522 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001523 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1524 // This object might be initialized later.
1525 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001526
Richard Smith0069b842012-03-10 00:28:11 +00001527 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001528 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001529 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001530 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001531 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001532 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001533 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001534 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001535 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001536 // Note, it should not be possible to form a pointer with a valid
1537 // designator which points more than one past the end of the array.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001538 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001539 (unsigned)diag::note_constexpr_read_past_end :
1540 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001541 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001542 }
Richard Smithf3908f22012-02-17 03:35:37 +00001543 // An array object is represented as either an Array APValue or as an
1544 // LValue which refers to a string literal.
1545 if (O->isLValue()) {
1546 assert(I == N - 1 && "extracting subobject of character?");
1547 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001548 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithf3908f22012-02-17 03:35:37 +00001549 Info, O->getLValueBase().get<const Expr*>(), Index));
1550 return true;
1551 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001552 O = &O->getArrayInitializedElt(Index);
1553 else
1554 O = &O->getArrayFiller();
1555 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001556 } else if (ObjType->isAnyComplexType()) {
1557 // Next subobject is a complex number.
1558 uint64_t Index = Sub.Entries[I].ArrayIndex;
1559 if (Index > 1) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001560 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Richard Smith86024012012-02-18 22:04:06 +00001561 (unsigned)diag::note_constexpr_read_past_end :
1562 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1563 return false;
1564 }
1565 assert(I == N - 1 && "extracting subobject of scalar?");
1566 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001567 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001568 : O->getComplexIntReal());
1569 } else {
1570 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001571 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001572 : O->getComplexFloatReal());
1573 }
1574 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001575 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001576 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001577 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001578 << Field;
1579 Info.Note(Field->getLocation(), diag::note_declared_at);
1580 return false;
1581 }
1582
Richard Smith180f4792011-11-10 06:34:14 +00001583 // Next subobject is a class, struct or union field.
1584 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1585 if (RD->isUnion()) {
1586 const FieldDecl *UnionField = O->getUnionField();
1587 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001588 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001589 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001590 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001591 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001592 }
Richard Smith180f4792011-11-10 06:34:14 +00001593 O = &O->getUnionValue();
1594 } else
1595 O = &O->getStructField(Field->getFieldIndex());
1596 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001597
1598 if (ObjType.isVolatileQualified()) {
1599 if (Info.getLangOpts().CPlusPlus) {
1600 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001601 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001602 << 2 << Field;
1603 Info.Note(Field->getLocation(), diag::note_declared_at);
1604 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001605 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001606 }
1607 return false;
1608 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001609 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001610 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001611 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1612 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1613 O = &O->getStructBase(getBaseIndex(Derived, Base));
1614 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001615 }
Richard Smith180f4792011-11-10 06:34:14 +00001616
Richard Smithf48fdb02011-12-09 22:58:01 +00001617 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001618 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001619 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001620 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001621 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001622 }
1623
Richard Smith0069b842012-03-10 00:28:11 +00001624 // This may look super-stupid, but it serves an important purpose: if we just
1625 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1626 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1627 // object, which is destroyed by Tmp's destructor.
1628 APValue Tmp;
1629 O->swap(Tmp);
1630 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001631 return true;
1632}
1633
Richard Smithf15fda02012-02-02 01:16:57 +00001634/// Find the position where two subobject designators diverge, or equivalently
1635/// the length of the common initial subsequence.
1636static unsigned FindDesignatorMismatch(QualType ObjType,
1637 const SubobjectDesignator &A,
1638 const SubobjectDesignator &B,
1639 bool &WasArrayIndex) {
1640 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1641 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001642 if (!ObjType.isNull() &&
1643 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001644 // Next subobject is an array element.
1645 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1646 WasArrayIndex = true;
1647 return I;
1648 }
Richard Smith86024012012-02-18 22:04:06 +00001649 if (ObjType->isAnyComplexType())
1650 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1651 else
1652 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001653 } else {
1654 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1655 WasArrayIndex = false;
1656 return I;
1657 }
1658 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1659 // Next subobject is a field.
1660 ObjType = FD->getType();
1661 else
1662 // Next subobject is a base class.
1663 ObjType = QualType();
1664 }
1665 }
1666 WasArrayIndex = false;
1667 return I;
1668}
1669
1670/// Determine whether the given subobject designators refer to elements of the
1671/// same array object.
1672static bool AreElementsOfSameArray(QualType ObjType,
1673 const SubobjectDesignator &A,
1674 const SubobjectDesignator &B) {
1675 if (A.Entries.size() != B.Entries.size())
1676 return false;
1677
1678 bool IsArray = A.MostDerivedArraySize != 0;
1679 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1680 // A is a subobject of the array element.
1681 return false;
1682
1683 // If A (and B) designates an array element, the last entry will be the array
1684 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1685 // of length 1' case, and the entire path must match.
1686 bool WasArrayIndex;
1687 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1688 return CommonLength >= A.Entries.size() - IsArray;
1689}
1690
Richard Smith180f4792011-11-10 06:34:14 +00001691/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1692/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1693/// for looking up the glvalue referred to by an entity of reference type.
1694///
1695/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001696/// \param Conv - The expression for which we are performing the conversion.
1697/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001698/// \param Type - The type we expect this conversion to produce, before
1699/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001700/// \param LVal - The glvalue on which we are attempting to perform this action.
1701/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001702static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1703 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001704 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001705 if (LVal.Designator.Invalid)
1706 // A diagnostic will have already been produced.
1707 return false;
1708
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001709 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001710
Richard Smithf48fdb02011-12-09 22:58:01 +00001711 if (!LVal.Base) {
1712 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001713 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001714 return false;
1715 }
1716
Richard Smith83587db2012-02-15 02:18:13 +00001717 CallStackFrame *Frame = 0;
1718 if (LVal.CallIndex) {
1719 Frame = Info.getCallFrame(LVal.CallIndex);
1720 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001721 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001722 NoteLValueLocation(Info, LVal.Base);
1723 return false;
1724 }
1725 }
1726
Richard Smith7098cbd2011-12-21 05:04:46 +00001727 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1728 // is not a constant expression (even if the object is non-volatile). We also
1729 // apply this rule to C++98, in order to conform to the expected 'volatile'
1730 // semantics.
1731 if (Type.isVolatileQualified()) {
1732 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001733 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001734 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001735 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001736 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001737 }
Richard Smithc49bd112011-10-28 17:51:58 +00001738
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001739 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001740 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1741 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001742 // expressions are constant expressions too. Inside constexpr functions,
1743 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001744 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001745 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregord2008e22012-04-06 22:40:38 +00001746 if (VD) {
1747 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1748 VD = VDef;
1749 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001750 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001751 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001752 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001753 }
1754
Richard Smith7098cbd2011-12-21 05:04:46 +00001755 // DR1313: If the object is volatile-qualified but the glvalue was not,
1756 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001757 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001758 if (VT.isVolatileQualified()) {
1759 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001760 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001761 Info.Note(VD->getLocation(), diag::note_declared_at);
1762 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001763 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001764 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001765 return false;
1766 }
1767
1768 if (!isa<ParmVarDecl>(VD)) {
1769 if (VD->isConstexpr()) {
1770 // OK, we can read this variable.
1771 } else if (VT->isIntegralOrEnumerationType()) {
1772 if (!VT.isConstQualified()) {
1773 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001774 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001775 Info.Note(VD->getLocation(), diag::note_declared_at);
1776 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001777 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001778 }
1779 return false;
1780 }
1781 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1782 // We support folding of const floating-point types, in order to make
1783 // static const data members of such types (supported as an extension)
1784 // more useful.
1785 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001786 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001787 Info.Note(VD->getLocation(), diag::note_declared_at);
1788 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001789 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001790 }
1791 } else {
1792 // FIXME: Allow folding of values of any literal type in all languages.
1793 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001794 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001795 Info.Note(VD->getLocation(), diag::note_declared_at);
1796 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001797 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001798 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001799 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001800 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001801 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001802
Richard Smithf48fdb02011-12-09 22:58:01 +00001803 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001804 return false;
1805
Richard Smith47a1eed2011-10-29 20:57:55 +00001806 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001807 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001808
1809 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1810 // conversion. This happens when the declaration and the lvalue should be
1811 // considered synonymous, for instance when initializing an array of char
1812 // from a string literal. Continue as if the initializer lvalue was the
1813 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001814 assert(RVal.getLValueOffset().isZero() &&
1815 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001816 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001817
1818 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1819 Frame = Info.getCallFrame(CallIndex);
1820 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001821 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001822 NoteLValueLocation(Info, RVal.getLValueBase());
1823 return false;
1824 }
1825 } else {
1826 Frame = 0;
1827 }
Richard Smithc49bd112011-10-28 17:51:58 +00001828 }
1829
Richard Smith7098cbd2011-12-21 05:04:46 +00001830 // Volatile temporary objects cannot be read in constant expressions.
1831 if (Base->getType().isVolatileQualified()) {
1832 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001833 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001834 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1835 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001836 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001837 }
1838 return false;
1839 }
1840
Richard Smithcc5d4f62011-11-07 09:22:26 +00001841 if (Frame) {
1842 // If this is a temporary expression with a nontrivial initializer, grab the
1843 // value from the relevant stack frame.
1844 RVal = Frame->Temporaries[Base];
1845 } else if (const CompoundLiteralExpr *CLE
1846 = dyn_cast<CompoundLiteralExpr>(Base)) {
1847 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1848 // initializer until now for such expressions. Such an expression can't be
1849 // an ICE in C, so this only matters for fold.
1850 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1851 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1852 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001853 } else if (isa<StringLiteral>(Base)) {
1854 // We represent a string literal array as an lvalue pointing at the
1855 // corresponding expression, rather than building an array of chars.
1856 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001857 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001858 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001859 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001860 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001861 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001862
Richard Smithf48fdb02011-12-09 22:58:01 +00001863 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1864 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001865}
1866
Richard Smith59efe262011-11-11 04:05:33 +00001867/// Build an lvalue for the object argument of a member function call.
1868static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1869 LValue &This) {
1870 if (Object->getType()->isPointerType())
1871 return EvaluatePointer(Object, This, Info);
1872
1873 if (Object->isGLValue())
1874 return EvaluateLValue(Object, This, Info);
1875
Richard Smithe24f5fc2011-11-17 22:56:20 +00001876 if (Object->getType()->isLiteralType())
1877 return EvaluateTemporary(Object, This, Info);
1878
1879 return false;
1880}
1881
1882/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1883/// lvalue referring to the result.
1884///
1885/// \param Info - Information about the ongoing evaluation.
1886/// \param BO - The member pointer access operation.
1887/// \param LV - Filled in with a reference to the resulting object.
1888/// \param IncludeMember - Specifies whether the member itself is included in
1889/// the resulting LValue subobject designator. This is not possible when
1890/// creating a bound member function.
1891/// \return The field or method declaration to which the member pointer refers,
1892/// or 0 if evaluation fails.
1893static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1894 const BinaryOperator *BO,
1895 LValue &LV,
1896 bool IncludeMember = true) {
1897 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1898
Richard Smith745f5142012-01-27 01:14:48 +00001899 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1900 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001901 return 0;
1902
1903 MemberPtr MemPtr;
1904 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1905 return 0;
1906
1907 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1908 // member value, the behavior is undefined.
1909 if (!MemPtr.getDecl())
1910 return 0;
1911
Richard Smith745f5142012-01-27 01:14:48 +00001912 if (!EvalObjOK)
1913 return 0;
1914
Richard Smithe24f5fc2011-11-17 22:56:20 +00001915 if (MemPtr.isDerivedMember()) {
1916 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001917 // The end of the derived-to-base path for the base object must match the
1918 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001919 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001920 LV.Designator.Entries.size())
1921 return 0;
1922 unsigned PathLengthToMember =
1923 LV.Designator.Entries.size() - MemPtr.Path.size();
1924 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1925 const CXXRecordDecl *LVDecl = getAsBaseClass(
1926 LV.Designator.Entries[PathLengthToMember + I]);
1927 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1928 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1929 return 0;
1930 }
1931
1932 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001933 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1934 PathLengthToMember))
1935 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001936 } else if (!MemPtr.Path.empty()) {
1937 // Extend the LValue path with the member pointer's path.
1938 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1939 MemPtr.Path.size() + IncludeMember);
1940
1941 // Walk down to the appropriate base class.
1942 QualType LVType = BO->getLHS()->getType();
1943 if (const PointerType *PT = LVType->getAs<PointerType>())
1944 LVType = PT->getPointeeType();
1945 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1946 assert(RD && "member pointer access on non-class-type expression");
1947 // The first class in the path is that of the lvalue.
1948 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1949 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001950 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001951 RD = Base;
1952 }
1953 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001954 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001955 }
1956
1957 // Add the member. Note that we cannot build bound member functions here.
1958 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001959 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1960 HandleLValueMember(Info, BO, LV, FD);
1961 else if (const IndirectFieldDecl *IFD =
1962 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1963 HandleLValueIndirectMember(Info, BO, LV, IFD);
1964 else
1965 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001966 }
1967
1968 return MemPtr.getDecl();
1969}
1970
1971/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1972/// the provided lvalue, which currently refers to the base object.
1973static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1974 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001975 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001976 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001977 return false;
1978
Richard Smithb4e85ed2012-01-06 16:39:00 +00001979 QualType TargetQT = E->getType();
1980 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1981 TargetQT = PT->getPointeeType();
1982
1983 // Check this cast lands within the final derived-to-base subobject path.
1984 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001985 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00001986 << D.MostDerivedType << TargetQT;
1987 return false;
1988 }
1989
Richard Smithe24f5fc2011-11-17 22:56:20 +00001990 // Check the type of the final cast. We don't need to check the path,
1991 // since a cast can only be formed if the path is unique.
1992 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001993 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1994 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001995 if (NewEntriesSize == D.MostDerivedPathLength)
1996 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1997 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001998 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001999 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002000 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002001 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002002 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002003 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002004
2005 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002006 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002007}
2008
Mike Stumpc4c90452009-10-27 22:09:17 +00002009namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002010enum EvalStmtResult {
2011 /// Evaluation failed.
2012 ESR_Failed,
2013 /// Hit a 'return' statement.
2014 ESR_Returned,
2015 /// Evaluation succeeded.
2016 ESR_Succeeded
2017};
2018}
2019
2020// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002021static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002022 const Stmt *S) {
2023 switch (S->getStmtClass()) {
2024 default:
2025 return ESR_Failed;
2026
2027 case Stmt::NullStmtClass:
2028 case Stmt::DeclStmtClass:
2029 return ESR_Succeeded;
2030
Richard Smithc1c5f272011-12-13 06:39:58 +00002031 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002032 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002033 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002034 return ESR_Failed;
2035 return ESR_Returned;
2036 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002037
2038 case Stmt::CompoundStmtClass: {
2039 const CompoundStmt *CS = cast<CompoundStmt>(S);
2040 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2041 BE = CS->body_end(); BI != BE; ++BI) {
2042 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2043 if (ESR != ESR_Succeeded)
2044 return ESR;
2045 }
2046 return ESR_Succeeded;
2047 }
2048 }
2049}
2050
Richard Smith61802452011-12-22 02:22:31 +00002051/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2052/// default constructor. If so, we'll fold it whether or not it's marked as
2053/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2054/// so we need special handling.
2055static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002056 const CXXConstructorDecl *CD,
2057 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002058 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2059 return false;
2060
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002061 // Value-initialization does not call a trivial default constructor, so such a
2062 // call is a core constant expression whether or not the constructor is
2063 // constexpr.
2064 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002065 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002066 // FIXME: If DiagDecl is an implicitly-declared special member function,
2067 // we should be much more explicit about why it's not constexpr.
2068 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2069 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2070 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002071 } else {
2072 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2073 }
2074 }
2075 return true;
2076}
2077
Richard Smithc1c5f272011-12-13 06:39:58 +00002078/// CheckConstexprFunction - Check that a function can be called in a constant
2079/// expression.
2080static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2081 const FunctionDecl *Declaration,
2082 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002083 // Potential constant expressions can contain calls to declared, but not yet
2084 // defined, constexpr functions.
2085 if (Info.CheckingPotentialConstantExpression && !Definition &&
2086 Declaration->isConstexpr())
2087 return false;
2088
Richard Smithc1c5f272011-12-13 06:39:58 +00002089 // Can we evaluate this function call?
2090 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2091 return true;
2092
2093 if (Info.getLangOpts().CPlusPlus0x) {
2094 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002095 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2096 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002097 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2098 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2099 << DiagDecl;
2100 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2101 } else {
2102 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2103 }
2104 return false;
2105}
2106
Richard Smith180f4792011-11-10 06:34:14 +00002107namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002108typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002109}
2110
2111/// EvaluateArgs - Evaluate the arguments to a function call.
2112static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2113 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002114 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002115 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002116 I != E; ++I) {
2117 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2118 // If we're checking for a potential constant expression, evaluate all
2119 // initializers even if some of them fail.
2120 if (!Info.keepEvaluatingAfterFailure())
2121 return false;
2122 Success = false;
2123 }
2124 }
2125 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002126}
2127
Richard Smithd0dccea2011-10-28 22:34:42 +00002128/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002129static bool HandleFunctionCall(SourceLocation CallLoc,
2130 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002131 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002132 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002133 ArgVector ArgValues(Args.size());
2134 if (!EvaluateArgs(Args, ArgValues, Info))
2135 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002136
Richard Smith745f5142012-01-27 01:14:48 +00002137 if (!Info.CheckCallLimit(CallLoc))
2138 return false;
2139
2140 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002141 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2142}
2143
Richard Smith180f4792011-11-10 06:34:14 +00002144/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002145static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002146 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002147 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002148 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002149 ArgVector ArgValues(Args.size());
2150 if (!EvaluateArgs(Args, ArgValues, Info))
2151 return false;
2152
Richard Smith745f5142012-01-27 01:14:48 +00002153 if (!Info.CheckCallLimit(CallLoc))
2154 return false;
2155
Richard Smith86c3ae42012-02-13 03:54:03 +00002156 const CXXRecordDecl *RD = Definition->getParent();
2157 if (RD->getNumVBases()) {
2158 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2159 return false;
2160 }
2161
Richard Smith745f5142012-01-27 01:14:48 +00002162 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002163
2164 // If it's a delegating constructor, just delegate.
2165 if (Definition->isDelegatingConstructor()) {
2166 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002167 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002168 }
2169
Richard Smith610a60c2012-01-10 04:32:03 +00002170 // For a trivial copy or move constructor, perform an APValue copy. This is
2171 // essential for unions, where the operations performed by the constructor
2172 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002173 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002174 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2175 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002176 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002177 RHS.setFrom(Info.Ctx, ArgValues[0]);
2178 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2179 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002180 }
2181
2182 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002183 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002184 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2185 std::distance(RD->field_begin(), RD->field_end()));
2186
2187 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2188
Richard Smith745f5142012-01-27 01:14:48 +00002189 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002190 unsigned BasesSeen = 0;
2191#ifndef NDEBUG
2192 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2193#endif
2194 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2195 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002196 LValue Subobject = This;
2197 APValue *Value = &Result;
2198
2199 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002200 if ((*I)->isBaseInitializer()) {
2201 QualType BaseType((*I)->getBaseClass(), 0);
2202#ifndef NDEBUG
2203 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002204 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002205 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2206 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2207 "base class initializers not in expected order");
2208 ++BaseIt;
2209#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002210 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002211 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002212 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002213 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002214 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002215 if (RD->isUnion()) {
2216 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002217 Value = &Result.getUnionValue();
2218 } else {
2219 Value = &Result.getStructField(FD->getFieldIndex());
2220 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002221 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002222 // Walk the indirect field decl's chain to find the object to initialize,
2223 // and make sure we've initialized every step along it.
2224 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2225 CE = IFD->chain_end();
2226 C != CE; ++C) {
2227 FieldDecl *FD = cast<FieldDecl>(*C);
2228 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2229 // Switch the union field if it differs. This happens if we had
2230 // preceding zero-initialization, and we're now initializing a union
2231 // subobject other than the first.
2232 // FIXME: In this case, the values of the other subobjects are
2233 // specified, since zero-initialization sets all padding bits to zero.
2234 if (Value->isUninit() ||
2235 (Value->isUnion() && Value->getUnionField() != FD)) {
2236 if (CD->isUnion())
2237 *Value = APValue(FD);
2238 else
2239 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2240 std::distance(CD->field_begin(), CD->field_end()));
2241 }
Richard Smith745f5142012-01-27 01:14:48 +00002242 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002243 if (CD->isUnion())
2244 Value = &Value->getUnionValue();
2245 else
2246 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002247 }
Richard Smith180f4792011-11-10 06:34:14 +00002248 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002249 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002250 }
Richard Smith745f5142012-01-27 01:14:48 +00002251
Richard Smith83587db2012-02-15 02:18:13 +00002252 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2253 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002254 ? CCEK_Constant : CCEK_MemberInit)) {
2255 // If we're checking for a potential constant expression, evaluate all
2256 // initializers even if some of them fail.
2257 if (!Info.keepEvaluatingAfterFailure())
2258 return false;
2259 Success = false;
2260 }
Richard Smith180f4792011-11-10 06:34:14 +00002261 }
2262
Richard Smith745f5142012-01-27 01:14:48 +00002263 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002264}
2265
Richard Smithd0dccea2011-10-28 22:34:42 +00002266namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002267class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002268 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002269 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002270public:
2271
Richard Smith1e12c592011-10-16 21:26:27 +00002272 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002273
2274 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002275 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002276 return true;
2277 }
2278
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002279 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2280 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002281 return Visit(E->getResultExpr());
2282 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002283 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002284 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002285 return true;
2286 return false;
2287 }
John McCallf85e1932011-06-15 23:02:42 +00002288 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002289 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002290 return true;
2291 return false;
2292 }
John McCallf85e1932011-06-15 23:02:42 +00002293
Mike Stumpc4c90452009-10-27 22:09:17 +00002294 // We don't want to evaluate BlockExprs multiple times, as they generate
2295 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002296 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2297 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2298 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002299 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002300 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2301 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2302 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2303 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2304 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2305 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002306 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002307 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002308 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002309 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002310 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002311 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2312 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2313 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2314 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002315 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002316 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2317 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2318 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2319 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2320 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002321 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002322 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002323 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002324 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002325 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002326
2327 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002328 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002329 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2330 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002331 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002332 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002333 return false;
2334 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002335
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002336 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002337};
2338
John McCall56ca35d2011-02-17 10:25:35 +00002339class OpaqueValueEvaluation {
2340 EvalInfo &info;
2341 OpaqueValueExpr *opaqueValue;
2342
2343public:
2344 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2345 Expr *value)
2346 : info(info), opaqueValue(opaqueValue) {
2347
2348 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002349 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002350 this->opaqueValue = 0;
2351 return;
2352 }
John McCall56ca35d2011-02-17 10:25:35 +00002353 }
2354
2355 bool hasError() const { return opaqueValue == 0; }
2356
2357 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002358 // FIXME: For a recursive constexpr call, an outer stack frame might have
2359 // been using this opaque value too, and will now have to re-evaluate the
2360 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002361 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2362 }
2363};
2364
Mike Stumpc4c90452009-10-27 22:09:17 +00002365} // end anonymous namespace
2366
Eli Friedman4efaa272008-11-12 09:44:48 +00002367//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002368// Generic Evaluation
2369//===----------------------------------------------------------------------===//
2370namespace {
2371
Richard Smithf48fdb02011-12-09 22:58:01 +00002372// FIXME: RetTy is always bool. Remove it.
2373template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002374class ExprEvaluatorBase
2375 : public ConstStmtVisitor<Derived, RetTy> {
2376private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002377 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002378 return static_cast<Derived*>(this)->Success(V, E);
2379 }
Richard Smith51201882011-12-30 21:15:51 +00002380 RetTy DerivedZeroInitialization(const Expr *E) {
2381 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002382 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002383
Richard Smith74e1ad92012-02-16 02:46:34 +00002384 // Check whether a conditional operator with a non-constant condition is a
2385 // potential constant expression. If neither arm is a potential constant
2386 // expression, then the conditional operator is not either.
2387 template<typename ConditionalOperator>
2388 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2389 assert(Info.CheckingPotentialConstantExpression);
2390
2391 // Speculatively evaluate both arms.
2392 {
2393 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2394 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2395
2396 StmtVisitorTy::Visit(E->getFalseExpr());
2397 if (Diag.empty())
2398 return;
2399
2400 Diag.clear();
2401 StmtVisitorTy::Visit(E->getTrueExpr());
2402 if (Diag.empty())
2403 return;
2404 }
2405
2406 Error(E, diag::note_constexpr_conditional_never_const);
2407 }
2408
2409
2410 template<typename ConditionalOperator>
2411 bool HandleConditionalOperator(const ConditionalOperator *E) {
2412 bool BoolResult;
2413 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2414 if (Info.CheckingPotentialConstantExpression)
2415 CheckPotentialConstantConditional(E);
2416 return false;
2417 }
2418
2419 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2420 return StmtVisitorTy::Visit(EvalExpr);
2421 }
2422
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002423protected:
2424 EvalInfo &Info;
2425 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2426 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2427
Richard Smithdd1f29b2011-12-12 09:28:41 +00002428 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002429 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002430 }
2431
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00002432 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2433
2434public:
2435 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2436
2437 EvalInfo &getEvalInfo() { return Info; }
2438
Richard Smithf48fdb02011-12-09 22:58:01 +00002439 /// Report an evaluation error. This should only be called when an error is
2440 /// first discovered. When propagating an error, just return false.
2441 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002442 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002443 return false;
2444 }
2445 bool Error(const Expr *E) {
2446 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2447 }
2448
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002449 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002450 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002451 }
2452 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002453 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002454 }
2455
2456 RetTy VisitParenExpr(const ParenExpr *E)
2457 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2458 RetTy VisitUnaryExtension(const UnaryOperator *E)
2459 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2460 RetTy VisitUnaryPlus(const UnaryOperator *E)
2461 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2462 RetTy VisitChooseExpr(const ChooseExpr *E)
2463 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2464 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2465 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002466 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2467 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002468 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2469 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002470 // We cannot create any objects for which cleanups are required, so there is
2471 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2472 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2473 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002474
Richard Smithc216a012011-12-12 12:46:16 +00002475 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2476 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2477 return static_cast<Derived*>(this)->VisitCastExpr(E);
2478 }
2479 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2480 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2481 return static_cast<Derived*>(this)->VisitCastExpr(E);
2482 }
2483
Richard Smithe24f5fc2011-11-17 22:56:20 +00002484 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2485 switch (E->getOpcode()) {
2486 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002487 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002488
2489 case BO_Comma:
2490 VisitIgnoredValue(E->getLHS());
2491 return StmtVisitorTy::Visit(E->getRHS());
2492
2493 case BO_PtrMemD:
2494 case BO_PtrMemI: {
2495 LValue Obj;
2496 if (!HandleMemberPointerAccess(Info, E, Obj))
2497 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002498 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002499 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002500 return false;
2501 return DerivedSuccess(Result, E);
2502 }
2503 }
2504 }
2505
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002506 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002507 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002508 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2509 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002510 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002511
Richard Smith74e1ad92012-02-16 02:46:34 +00002512 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002513 }
2514
2515 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002516 bool IsBcpCall = false;
2517 // If the condition (ignoring parens) is a __builtin_constant_p call,
2518 // the result is a constant expression if it can be folded without
2519 // side-effects. This is an important GNU extension. See GCC PR38377
2520 // for discussion.
2521 if (const CallExpr *CallCE =
2522 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2523 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2524 IsBcpCall = true;
2525
2526 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2527 // constant expression; we can't check whether it's potentially foldable.
2528 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2529 return false;
2530
2531 FoldConstant Fold(Info);
2532
Richard Smith74e1ad92012-02-16 02:46:34 +00002533 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002534 return false;
2535
2536 if (IsBcpCall)
2537 Fold.Fold(Info);
2538
2539 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002540 }
2541
2542 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002543 const APValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002544 if (!Value) {
2545 const Expr *Source = E->getSourceExpr();
2546 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002547 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002548 if (Source == E) { // sanity checking.
2549 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002550 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002551 }
2552 return StmtVisitorTy::Visit(Source);
2553 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002554 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002555 }
Richard Smithf10d9172011-10-11 21:43:33 +00002556
Richard Smithd0dccea2011-10-28 22:34:42 +00002557 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002558 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002559 QualType CalleeType = Callee->getType();
2560
Richard Smithd0dccea2011-10-28 22:34:42 +00002561 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002562 LValue *This = 0, ThisVal;
2563 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002564 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002565
Richard Smith59efe262011-11-11 04:05:33 +00002566 // Extract function decl and 'this' pointer from the callee.
2567 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002568 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002569 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2570 // Explicit bound member calls, such as x.f() or p->g();
2571 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002572 return false;
2573 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002574 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002575 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002576 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2577 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002578 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2579 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002580 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002581 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002582 return Error(Callee);
2583
2584 FD = dyn_cast<FunctionDecl>(Member);
2585 if (!FD)
2586 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002587 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002588 LValue Call;
2589 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002590 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002591
Richard Smithb4e85ed2012-01-06 16:39:00 +00002592 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002593 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002594 FD = dyn_cast_or_null<FunctionDecl>(
2595 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002596 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002597 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002598
2599 // Overloaded operator calls to member functions are represented as normal
2600 // calls with '*this' as the first argument.
2601 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2602 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002603 // FIXME: When selecting an implicit conversion for an overloaded
2604 // operator delete, we sometimes try to evaluate calls to conversion
2605 // operators without a 'this' parameter!
2606 if (Args.empty())
2607 return Error(E);
2608
Richard Smith59efe262011-11-11 04:05:33 +00002609 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2610 return false;
2611 This = &ThisVal;
2612 Args = Args.slice(1);
2613 }
2614
2615 // Don't call function pointers which have been cast to some other type.
2616 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002617 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002618 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002619 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002620
Richard Smithb04035a2012-02-01 02:39:43 +00002621 if (This && !This->checkSubobject(Info, E, CSK_This))
2622 return false;
2623
Richard Smith86c3ae42012-02-13 03:54:03 +00002624 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2625 // calls to such functions in constant expressions.
2626 if (This && !HasQualifier &&
2627 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2628 return Error(E, diag::note_constexpr_virtual_call);
2629
Richard Smithc1c5f272011-12-13 06:39:58 +00002630 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002631 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002632 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002633
Richard Smithc1c5f272011-12-13 06:39:58 +00002634 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002635 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2636 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002637 return false;
2638
Richard Smith83587db2012-02-15 02:18:13 +00002639 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002640 }
2641
Richard Smithc49bd112011-10-28 17:51:58 +00002642 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2643 return StmtVisitorTy::Visit(E->getInitializer());
2644 }
Richard Smithf10d9172011-10-11 21:43:33 +00002645 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002646 if (E->getNumInits() == 0)
2647 return DerivedZeroInitialization(E);
2648 if (E->getNumInits() == 1)
2649 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002650 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002651 }
2652 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002653 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002654 }
2655 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002656 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002657 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002658 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002659 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002660 }
Richard Smithf10d9172011-10-11 21:43:33 +00002661
Richard Smith180f4792011-11-10 06:34:14 +00002662 /// A member expression where the object is a prvalue is itself a prvalue.
2663 RetTy VisitMemberExpr(const MemberExpr *E) {
2664 assert(!E->isArrow() && "missing call to bound member function?");
2665
Richard Smith1aa0be82012-03-03 22:46:17 +00002666 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002667 if (!Evaluate(Val, Info, E->getBase()))
2668 return false;
2669
2670 QualType BaseTy = E->getBase()->getType();
2671
2672 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002673 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002674 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2675 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2676 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2677
Richard Smithb4e85ed2012-01-06 16:39:00 +00002678 SubobjectDesignator Designator(BaseTy);
2679 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002680
Richard Smithf48fdb02011-12-09 22:58:01 +00002681 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002682 DerivedSuccess(Val, E);
2683 }
2684
Richard Smithc49bd112011-10-28 17:51:58 +00002685 RetTy VisitCastExpr(const CastExpr *E) {
2686 switch (E->getCastKind()) {
2687 default:
2688 break;
2689
David Chisnall7a7ee302012-01-16 17:27:18 +00002690 case CK_AtomicToNonAtomic:
2691 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002692 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002693 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002694 return StmtVisitorTy::Visit(E->getSubExpr());
2695
2696 case CK_LValueToRValue: {
2697 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002698 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2699 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002700 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002701 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2702 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2703 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002704 return false;
2705 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002706 }
2707 }
2708
Richard Smithf48fdb02011-12-09 22:58:01 +00002709 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002710 }
2711
Richard Smith8327fad2011-10-24 18:44:57 +00002712 /// Visit a value which is evaluated, but whose value is ignored.
2713 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002714 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002715 if (!Evaluate(Scratch, Info, E))
2716 Info.EvalStatus.HasSideEffects = true;
2717 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002718};
2719
2720}
2721
2722//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002723// Common base class for lvalue and temporary evaluation.
2724//===----------------------------------------------------------------------===//
2725namespace {
2726template<class Derived>
2727class LValueExprEvaluatorBase
2728 : public ExprEvaluatorBase<Derived, bool> {
2729protected:
2730 LValue &Result;
2731 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2732 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2733
2734 bool Success(APValue::LValueBase B) {
2735 Result.set(B);
2736 return true;
2737 }
2738
2739public:
2740 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2741 ExprEvaluatorBaseTy(Info), Result(Result) {}
2742
Richard Smith1aa0be82012-03-03 22:46:17 +00002743 bool Success(const APValue &V, const Expr *E) {
2744 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002745 return true;
2746 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002747
Richard Smithe24f5fc2011-11-17 22:56:20 +00002748 bool VisitMemberExpr(const MemberExpr *E) {
2749 // Handle non-static data members.
2750 QualType BaseTy;
2751 if (E->isArrow()) {
2752 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2753 return false;
2754 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002755 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002756 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002757 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2758 return false;
2759 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002760 } else {
2761 if (!this->Visit(E->getBase()))
2762 return false;
2763 BaseTy = E->getBase()->getType();
2764 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002765
Richard Smithd9b02e72012-01-25 22:15:11 +00002766 const ValueDecl *MD = E->getMemberDecl();
2767 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2768 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2769 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2770 (void)BaseTy;
2771 HandleLValueMember(this->Info, E, Result, FD);
2772 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2773 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2774 } else
2775 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002776
Richard Smithd9b02e72012-01-25 22:15:11 +00002777 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002778 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002779 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002780 RefValue))
2781 return false;
2782 return Success(RefValue, E);
2783 }
2784 return true;
2785 }
2786
2787 bool VisitBinaryOperator(const BinaryOperator *E) {
2788 switch (E->getOpcode()) {
2789 default:
2790 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2791
2792 case BO_PtrMemD:
2793 case BO_PtrMemI:
2794 return HandleMemberPointerAccess(this->Info, E, Result);
2795 }
2796 }
2797
2798 bool VisitCastExpr(const CastExpr *E) {
2799 switch (E->getCastKind()) {
2800 default:
2801 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2802
2803 case CK_DerivedToBase:
2804 case CK_UncheckedDerivedToBase: {
2805 if (!this->Visit(E->getSubExpr()))
2806 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002807
2808 // Now figure out the necessary offset to add to the base LV to get from
2809 // the derived class to the base class.
2810 QualType Type = E->getSubExpr()->getType();
2811
2812 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2813 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002814 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002815 *PathI))
2816 return false;
2817 Type = (*PathI)->getType();
2818 }
2819
2820 return true;
2821 }
2822 }
2823 }
2824};
2825}
2826
2827//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002828// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002829//
2830// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2831// function designators (in C), decl references to void objects (in C), and
2832// temporaries (if building with -Wno-address-of-temporary).
2833//
2834// LValue evaluation produces values comprising a base expression of one of the
2835// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002836// - Declarations
2837// * VarDecl
2838// * FunctionDecl
2839// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002840// * CompoundLiteralExpr in C
2841// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002842// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002843// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002844// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002845// * ObjCEncodeExpr
2846// * AddrLabelExpr
2847// * BlockExpr
2848// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002849// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002850// * Any Expr, with a CallIndex indicating the function in which the temporary
2851// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002852// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002853//===----------------------------------------------------------------------===//
2854namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002855class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002856 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002857public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002858 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2859 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002860
Richard Smithc49bd112011-10-28 17:51:58 +00002861 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2862
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002863 bool VisitDeclRefExpr(const DeclRefExpr *E);
2864 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002865 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002866 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2867 bool VisitMemberExpr(const MemberExpr *E);
2868 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2869 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002870 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002871 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2872 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002873 bool VisitUnaryReal(const UnaryOperator *E);
2874 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002875
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002876 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002877 switch (E->getCastKind()) {
2878 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002879 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002880
Eli Friedmandb924222011-10-11 00:13:24 +00002881 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002882 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002883 if (!Visit(E->getSubExpr()))
2884 return false;
2885 Result.Designator.setInvalid();
2886 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002887
Richard Smithe24f5fc2011-11-17 22:56:20 +00002888 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002889 if (!Visit(E->getSubExpr()))
2890 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002891 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002892 }
2893 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002894};
2895} // end anonymous namespace
2896
Richard Smithc49bd112011-10-28 17:51:58 +00002897/// Evaluate an expression as an lvalue. This can be legitimately called on
2898/// expressions which are not glvalues, in a few cases:
2899/// * function designators in C,
2900/// * "extern void" objects,
2901/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002902static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002903 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2904 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2905 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002906 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002907}
2908
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002909bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002910 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2911 return Success(FD);
2912 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002913 return VisitVarDecl(E, VD);
2914 return Error(E);
2915}
Richard Smith436c8892011-10-24 23:14:33 +00002916
Richard Smithc49bd112011-10-28 17:51:58 +00002917bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002918 if (!VD->getType()->isReferenceType()) {
2919 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002920 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002921 return true;
2922 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002923 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002924 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002925
Richard Smith1aa0be82012-03-03 22:46:17 +00002926 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002927 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2928 return false;
2929 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002930}
2931
Richard Smithbd552ef2011-10-31 05:52:43 +00002932bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2933 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002934 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002935 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002936 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2937
Richard Smith83587db2012-02-15 02:18:13 +00002938 Result.set(E, Info.CurrentCall->Index);
2939 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2940 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002941 }
2942
2943 // Materialization of an lvalue temporary occurs when we need to force a copy
2944 // (for instance, if it's a bitfield).
2945 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2946 if (!Visit(E->GetTemporaryExpr()))
2947 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002948 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002949 Info.CurrentCall->Temporaries[E]))
2950 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002951 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002952 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002953}
2954
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002955bool
2956LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002957 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2958 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2959 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002960 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002961}
2962
Richard Smith47d21452011-12-27 12:18:28 +00002963bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2964 if (E->isTypeOperand())
2965 return Success(E);
2966 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2967 if (RD && RD->isPolymorphic()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002968 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith47d21452011-12-27 12:18:28 +00002969 << E->getExprOperand()->getType()
2970 << E->getExprOperand()->getSourceRange();
2971 return false;
2972 }
2973 return Success(E);
2974}
2975
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002976bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002977 // Handle static data members.
2978 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2979 VisitIgnoredValue(E->getBase());
2980 return VisitVarDecl(E, VD);
2981 }
2982
Richard Smithd0dccea2011-10-28 22:34:42 +00002983 // Handle static member functions.
2984 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2985 if (MD->isStatic()) {
2986 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002987 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002988 }
2989 }
2990
Richard Smith180f4792011-11-10 06:34:14 +00002991 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002992 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002993}
2994
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002995bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002996 // FIXME: Deal with vectors as array subscript bases.
2997 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002998 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002999
Anders Carlsson3068d112008-11-16 19:01:22 +00003000 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003001 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Anders Carlsson3068d112008-11-16 19:01:22 +00003003 APSInt Index;
3004 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003005 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003006 int64_t IndexValue
3007 = Index.isSigned() ? Index.getSExtValue()
3008 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003009
Richard Smithb4e85ed2012-01-06 16:39:00 +00003010 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003011}
Eli Friedman4efaa272008-11-12 09:44:48 +00003012
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003013bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003014 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003015}
3016
Richard Smith86024012012-02-18 22:04:06 +00003017bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3018 if (!Visit(E->getSubExpr()))
3019 return false;
3020 // __real is a no-op on scalar lvalues.
3021 if (E->getSubExpr()->getType()->isAnyComplexType())
3022 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3023 return true;
3024}
3025
3026bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3027 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3028 "lvalue __imag__ on scalar?");
3029 if (!Visit(E->getSubExpr()))
3030 return false;
3031 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3032 return true;
3033}
3034
Eli Friedman4efaa272008-11-12 09:44:48 +00003035//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003036// Pointer Evaluation
3037//===----------------------------------------------------------------------===//
3038
Anders Carlssonc754aa62008-07-08 05:13:58 +00003039namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003040class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003041 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003042 LValue &Result;
3043
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003044 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003045 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003046 return true;
3047 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003048public:
Mike Stump1eb44332009-09-09 15:08:12 +00003049
John McCallefdb83e2010-05-07 21:00:08 +00003050 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003051 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003052
Richard Smith1aa0be82012-03-03 22:46:17 +00003053 bool Success(const APValue &V, const Expr *E) {
3054 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003055 return true;
3056 }
Richard Smith51201882011-12-30 21:15:51 +00003057 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003058 return Success((Expr*)0);
3059 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003060
John McCallefdb83e2010-05-07 21:00:08 +00003061 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003062 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003063 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003064 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003065 { return Success(E); }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003066 bool VisitObjCNumericLiteral(const ObjCNumericLiteral *E)
3067 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003068 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003069 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003070 bool VisitCallExpr(const CallExpr *E);
3071 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003072 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003073 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003074 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003075 }
Richard Smith180f4792011-11-10 06:34:14 +00003076 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3077 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003078 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003079 Result = *Info.CurrentCall->This;
3080 return true;
3081 }
John McCall56ca35d2011-02-17 10:25:35 +00003082
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003083 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003084};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003085} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003086
John McCallefdb83e2010-05-07 21:00:08 +00003087static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003088 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003089 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003090}
3091
John McCallefdb83e2010-05-07 21:00:08 +00003092bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003093 if (E->getOpcode() != BO_Add &&
3094 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003095 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003096
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003097 const Expr *PExp = E->getLHS();
3098 const Expr *IExp = E->getRHS();
3099 if (IExp->getType()->isPointerType())
3100 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003101
Richard Smith745f5142012-01-27 01:14:48 +00003102 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3103 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003104 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003105
John McCallefdb83e2010-05-07 21:00:08 +00003106 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003107 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003108 return false;
3109 int64_t AdditionalOffset
3110 = Offset.isSigned() ? Offset.getSExtValue()
3111 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003112 if (E->getOpcode() == BO_Sub)
3113 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003114
Richard Smith180f4792011-11-10 06:34:14 +00003115 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003116 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3117 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003118}
Eli Friedman4efaa272008-11-12 09:44:48 +00003119
John McCallefdb83e2010-05-07 21:00:08 +00003120bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3121 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003122}
Mike Stump1eb44332009-09-09 15:08:12 +00003123
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003124bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3125 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003126
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003127 switch (E->getCastKind()) {
3128 default:
3129 break;
3130
John McCall2de56d12010-08-25 11:45:40 +00003131 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003132 case CK_CPointerToObjCPointerCast:
3133 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003134 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003135 if (!Visit(SubExpr))
3136 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003137 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3138 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3139 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003140 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003141 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003142 if (SubExpr->getType()->isVoidPointerType())
3143 CCEDiag(E, diag::note_constexpr_invalid_cast)
3144 << 3 << SubExpr->getType();
3145 else
3146 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3147 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003148 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003149
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003150 case CK_DerivedToBase:
3151 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003152 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003153 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003154 if (!Result.Base && Result.Offset.isZero())
3155 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003156
Richard Smith180f4792011-11-10 06:34:14 +00003157 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003158 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003159 QualType Type =
3160 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003161
Richard Smith180f4792011-11-10 06:34:14 +00003162 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003163 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003164 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3165 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003166 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003167 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003168 }
3169
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003170 return true;
3171 }
3172
Richard Smithe24f5fc2011-11-17 22:56:20 +00003173 case CK_BaseToDerived:
3174 if (!Visit(E->getSubExpr()))
3175 return false;
3176 if (!Result.Base && Result.Offset.isZero())
3177 return true;
3178 return HandleBaseToDerivedCast(Info, E, Result);
3179
Richard Smith47a1eed2011-10-29 20:57:55 +00003180 case CK_NullToPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003181 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003182 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003183
John McCall2de56d12010-08-25 11:45:40 +00003184 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003185 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3186
Richard Smith1aa0be82012-03-03 22:46:17 +00003187 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003188 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003189 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003190
John McCallefdb83e2010-05-07 21:00:08 +00003191 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003192 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3193 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003194 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003195 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003196 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003197 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003198 return true;
3199 } else {
3200 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003201 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003202 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003203 }
3204 }
John McCall2de56d12010-08-25 11:45:40 +00003205 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003206 if (SubExpr->isGLValue()) {
3207 if (!EvaluateLValue(SubExpr, Result, Info))
3208 return false;
3209 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003210 Result.set(SubExpr, Info.CurrentCall->Index);
3211 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3212 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003213 return false;
3214 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003215 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003216 if (const ConstantArrayType *CAT
3217 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3218 Result.addArray(Info, E, CAT);
3219 else
3220 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003221 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003222
John McCall2de56d12010-08-25 11:45:40 +00003223 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003224 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003225 }
3226
Richard Smithc49bd112011-10-28 17:51:58 +00003227 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003228}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003229
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003230bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003231 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003232 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003233
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003234 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003235}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003236
3237//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003238// Member Pointer Evaluation
3239//===----------------------------------------------------------------------===//
3240
3241namespace {
3242class MemberPointerExprEvaluator
3243 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3244 MemberPtr &Result;
3245
3246 bool Success(const ValueDecl *D) {
3247 Result = MemberPtr(D);
3248 return true;
3249 }
3250public:
3251
3252 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3253 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3254
Richard Smith1aa0be82012-03-03 22:46:17 +00003255 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003256 Result.setFrom(V);
3257 return true;
3258 }
Richard Smith51201882011-12-30 21:15:51 +00003259 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003260 return Success((const ValueDecl*)0);
3261 }
3262
3263 bool VisitCastExpr(const CastExpr *E);
3264 bool VisitUnaryAddrOf(const UnaryOperator *E);
3265};
3266} // end anonymous namespace
3267
3268static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3269 EvalInfo &Info) {
3270 assert(E->isRValue() && E->getType()->isMemberPointerType());
3271 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3272}
3273
3274bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3275 switch (E->getCastKind()) {
3276 default:
3277 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3278
3279 case CK_NullToMemberPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003280 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003281 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003282
3283 case CK_BaseToDerivedMemberPointer: {
3284 if (!Visit(E->getSubExpr()))
3285 return false;
3286 if (E->path_empty())
3287 return true;
3288 // Base-to-derived member pointer casts store the path in derived-to-base
3289 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3290 // the wrong end of the derived->base arc, so stagger the path by one class.
3291 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3292 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3293 PathI != PathE; ++PathI) {
3294 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3295 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3296 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003297 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003298 }
3299 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3300 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003301 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003302 return true;
3303 }
3304
3305 case CK_DerivedToBaseMemberPointer:
3306 if (!Visit(E->getSubExpr()))
3307 return false;
3308 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3309 PathE = E->path_end(); PathI != PathE; ++PathI) {
3310 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3311 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3312 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003313 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003314 }
3315 return true;
3316 }
3317}
3318
3319bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3320 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3321 // member can be formed.
3322 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3323}
3324
3325//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003326// Record Evaluation
3327//===----------------------------------------------------------------------===//
3328
3329namespace {
3330 class RecordExprEvaluator
3331 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3332 const LValue &This;
3333 APValue &Result;
3334 public:
3335
3336 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3337 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3338
Richard Smith1aa0be82012-03-03 22:46:17 +00003339 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003340 Result = V;
3341 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003342 }
Richard Smith51201882011-12-30 21:15:51 +00003343 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003344
Richard Smith59efe262011-11-11 04:05:33 +00003345 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003346 bool VisitInitListExpr(const InitListExpr *E);
3347 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3348 };
3349}
3350
Richard Smith51201882011-12-30 21:15:51 +00003351/// Perform zero-initialization on an object of non-union class type.
3352/// C++11 [dcl.init]p5:
3353/// To zero-initialize an object or reference of type T means:
3354/// [...]
3355/// -- if T is a (possibly cv-qualified) non-union class type,
3356/// each non-static data member and each base-class subobject is
3357/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003358static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3359 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003360 const LValue &This, APValue &Result) {
3361 assert(!RD->isUnion() && "Expected non-union class type");
3362 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3363 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3364 std::distance(RD->field_begin(), RD->field_end()));
3365
3366 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3367
3368 if (CD) {
3369 unsigned Index = 0;
3370 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003371 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003372 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3373 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003374 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3375 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003376 Result.getStructBase(Index)))
3377 return false;
3378 }
3379 }
3380
Richard Smithb4e85ed2012-01-06 16:39:00 +00003381 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3382 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003383 // -- if T is a reference type, no initialization is performed.
3384 if ((*I)->getType()->isReferenceType())
3385 continue;
3386
3387 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003388 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003389
3390 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003391 if (!EvaluateInPlace(
Richard Smith51201882011-12-30 21:15:51 +00003392 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3393 return false;
3394 }
3395
3396 return true;
3397}
3398
3399bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3400 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3401 if (RD->isUnion()) {
3402 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3403 // object's first non-static named data member is zero-initialized
3404 RecordDecl::field_iterator I = RD->field_begin();
3405 if (I == RD->field_end()) {
3406 Result = APValue((const FieldDecl*)0);
3407 return true;
3408 }
3409
3410 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003411 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003412 Result = APValue(*I);
3413 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003414 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003415 }
3416
Richard Smithce582fe2012-02-17 00:44:16 +00003417 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003418 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003419 return false;
3420 }
3421
Richard Smithb4e85ed2012-01-06 16:39:00 +00003422 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003423}
3424
Richard Smith59efe262011-11-11 04:05:33 +00003425bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3426 switch (E->getCastKind()) {
3427 default:
3428 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3429
3430 case CK_ConstructorConversion:
3431 return Visit(E->getSubExpr());
3432
3433 case CK_DerivedToBase:
3434 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003435 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003436 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003437 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003438 if (!DerivedObject.isStruct())
3439 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003440
3441 // Derived-to-base rvalue conversion: just slice off the derived part.
3442 APValue *Value = &DerivedObject;
3443 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3444 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3445 PathE = E->path_end(); PathI != PathE; ++PathI) {
3446 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3447 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3448 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3449 RD = Base;
3450 }
3451 Result = *Value;
3452 return true;
3453 }
3454 }
3455}
3456
Richard Smith180f4792011-11-10 06:34:14 +00003457bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003458 // Cannot constant-evaluate std::initializer_list inits.
3459 if (E->initializesStdInitializerList())
3460 return false;
3461
Richard Smith180f4792011-11-10 06:34:14 +00003462 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3463 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3464
3465 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003466 const FieldDecl *Field = E->getInitializedFieldInUnion();
3467 Result = APValue(Field);
3468 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003469 return true;
Richard Smithec789162012-01-12 18:54:33 +00003470
3471 // If the initializer list for a union does not contain any elements, the
3472 // first element of the union is value-initialized.
3473 ImplicitValueInitExpr VIE(Field->getType());
3474 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3475
Richard Smith180f4792011-11-10 06:34:14 +00003476 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003477 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith83587db2012-02-15 02:18:13 +00003478 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003479 }
3480
3481 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3482 "initializer list for class with base classes");
3483 Result = APValue(APValue::UninitStruct(), 0,
3484 std::distance(RD->field_begin(), RD->field_end()));
3485 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003486 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003487 for (RecordDecl::field_iterator Field = RD->field_begin(),
3488 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3489 // Anonymous bit-fields are not considered members of the class for
3490 // purposes of aggregate initialization.
3491 if (Field->isUnnamedBitfield())
3492 continue;
3493
3494 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003495
Richard Smith745f5142012-01-27 01:14:48 +00003496 bool HaveInit = ElementNo < E->getNumInits();
3497
3498 // FIXME: Diagnostics here should point to the end of the initializer
3499 // list, not the start.
3500 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3501 *Field, &Layout);
3502
3503 // Perform an implicit value-initialization for members beyond the end of
3504 // the initializer list.
3505 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3506
Richard Smith83587db2012-02-15 02:18:13 +00003507 if (!EvaluateInPlace(
Richard Smith745f5142012-01-27 01:14:48 +00003508 Result.getStructField((*Field)->getFieldIndex()),
3509 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3510 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003511 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003512 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003513 }
3514 }
3515
Richard Smith745f5142012-01-27 01:14:48 +00003516 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003517}
3518
3519bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3520 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003521 bool ZeroInit = E->requiresZeroInitialization();
3522 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003523 // If we've already performed zero-initialization, we're already done.
3524 if (!Result.isUninit())
3525 return true;
3526
Richard Smith51201882011-12-30 21:15:51 +00003527 if (ZeroInit)
3528 return ZeroInitialization(E);
3529
Richard Smith61802452011-12-22 02:22:31 +00003530 const CXXRecordDecl *RD = FD->getParent();
3531 if (RD->isUnion())
3532 Result = APValue((FieldDecl*)0);
3533 else
3534 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3535 std::distance(RD->field_begin(), RD->field_end()));
3536 return true;
3537 }
3538
Richard Smith180f4792011-11-10 06:34:14 +00003539 const FunctionDecl *Definition = 0;
3540 FD->getBody(Definition);
3541
Richard Smithc1c5f272011-12-13 06:39:58 +00003542 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3543 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003544
Richard Smith610a60c2012-01-10 04:32:03 +00003545 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003546 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003547 if (const MaterializeTemporaryExpr *ME
3548 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3549 return Visit(ME->GetTemporaryExpr());
3550
Richard Smith51201882011-12-30 21:15:51 +00003551 if (ZeroInit && !ZeroInitialization(E))
3552 return false;
3553
Richard Smith180f4792011-11-10 06:34:14 +00003554 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003555 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003556 cast<CXXConstructorDecl>(Definition), Info,
3557 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003558}
3559
3560static bool EvaluateRecord(const Expr *E, const LValue &This,
3561 APValue &Result, EvalInfo &Info) {
3562 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003563 "can't evaluate expression as a record rvalue");
3564 return RecordExprEvaluator(Info, This, Result).Visit(E);
3565}
3566
3567//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003568// Temporary Evaluation
3569//
3570// Temporaries are represented in the AST as rvalues, but generally behave like
3571// lvalues. The full-object of which the temporary is a subobject is implicitly
3572// materialized so that a reference can bind to it.
3573//===----------------------------------------------------------------------===//
3574namespace {
3575class TemporaryExprEvaluator
3576 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3577public:
3578 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3579 LValueExprEvaluatorBaseTy(Info, Result) {}
3580
3581 /// Visit an expression which constructs the value of this temporary.
3582 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003583 Result.set(E, Info.CurrentCall->Index);
3584 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003585 }
3586
3587 bool VisitCastExpr(const CastExpr *E) {
3588 switch (E->getCastKind()) {
3589 default:
3590 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3591
3592 case CK_ConstructorConversion:
3593 return VisitConstructExpr(E->getSubExpr());
3594 }
3595 }
3596 bool VisitInitListExpr(const InitListExpr *E) {
3597 return VisitConstructExpr(E);
3598 }
3599 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3600 return VisitConstructExpr(E);
3601 }
3602 bool VisitCallExpr(const CallExpr *E) {
3603 return VisitConstructExpr(E);
3604 }
3605};
3606} // end anonymous namespace
3607
3608/// Evaluate an expression of record type as a temporary.
3609static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003610 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003611 return TemporaryExprEvaluator(Info, Result).Visit(E);
3612}
3613
3614//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003615// Vector Evaluation
3616//===----------------------------------------------------------------------===//
3617
3618namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003619 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003620 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3621 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003622 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003623
Richard Smith07fc6572011-10-22 21:10:00 +00003624 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3625 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003626
Richard Smith07fc6572011-10-22 21:10:00 +00003627 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3628 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3629 // FIXME: remove this APValue copy.
3630 Result = APValue(V.data(), V.size());
3631 return true;
3632 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003633 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003634 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003635 Result = V;
3636 return true;
3637 }
Richard Smith51201882011-12-30 21:15:51 +00003638 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003639
Richard Smith07fc6572011-10-22 21:10:00 +00003640 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003641 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003642 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003643 bool VisitInitListExpr(const InitListExpr *E);
3644 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003645 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003646 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003647 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003648 };
3649} // end anonymous namespace
3650
3651static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003652 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003653 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003654}
3655
Richard Smith07fc6572011-10-22 21:10:00 +00003656bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3657 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003658 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003659
Richard Smithd62ca372011-12-06 22:44:34 +00003660 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003661 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003662
Eli Friedman46a52322011-03-25 00:43:55 +00003663 switch (E->getCastKind()) {
3664 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003665 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003666 if (SETy->isIntegerType()) {
3667 APSInt IntResult;
3668 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003669 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003670 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003671 } else if (SETy->isRealFloatingType()) {
3672 APFloat F(0.0);
3673 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003674 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003675 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003676 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003677 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003678 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003679
3680 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003681 SmallVector<APValue, 4> Elts(NElts, Val);
3682 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003683 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003684 case CK_BitCast: {
3685 // Evaluate the operand into an APInt we can extract from.
3686 llvm::APInt SValInt;
3687 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3688 return false;
3689 // Extract the elements
3690 QualType EltTy = VTy->getElementType();
3691 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3692 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3693 SmallVector<APValue, 4> Elts;
3694 if (EltTy->isRealFloatingType()) {
3695 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3696 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3697 unsigned FloatEltSize = EltSize;
3698 if (&Sem == &APFloat::x87DoubleExtended)
3699 FloatEltSize = 80;
3700 for (unsigned i = 0; i < NElts; i++) {
3701 llvm::APInt Elt;
3702 if (BigEndian)
3703 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3704 else
3705 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3706 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3707 }
3708 } else if (EltTy->isIntegerType()) {
3709 for (unsigned i = 0; i < NElts; i++) {
3710 llvm::APInt Elt;
3711 if (BigEndian)
3712 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3713 else
3714 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3715 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3716 }
3717 } else {
3718 return Error(E);
3719 }
3720 return Success(Elts, E);
3721 }
Eli Friedman46a52322011-03-25 00:43:55 +00003722 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003723 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003724 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003725}
3726
Richard Smith07fc6572011-10-22 21:10:00 +00003727bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003728VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003729 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003730 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003731 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003732
Nate Begeman59b5da62009-01-18 03:20:47 +00003733 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003734 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003735
Eli Friedman3edd5a92012-01-03 23:24:20 +00003736 // The number of initializers can be less than the number of
3737 // vector elements. For OpenCL, this can be due to nested vector
3738 // initialization. For GCC compatibility, missing trailing elements
3739 // should be initialized with zeroes.
3740 unsigned CountInits = 0, CountElts = 0;
3741 while (CountElts < NumElements) {
3742 // Handle nested vector initialization.
3743 if (CountInits < NumInits
3744 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3745 APValue v;
3746 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3747 return Error(E);
3748 unsigned vlen = v.getVectorLength();
3749 for (unsigned j = 0; j < vlen; j++)
3750 Elements.push_back(v.getVectorElt(j));
3751 CountElts += vlen;
3752 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003753 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003754 if (CountInits < NumInits) {
3755 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003756 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003757 } else // trailing integer zero.
3758 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3759 Elements.push_back(APValue(sInt));
3760 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003761 } else {
3762 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003763 if (CountInits < NumInits) {
3764 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003765 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003766 } else // trailing float zero.
3767 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3768 Elements.push_back(APValue(f));
3769 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003770 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003771 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003772 }
Richard Smith07fc6572011-10-22 21:10:00 +00003773 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003774}
3775
Richard Smith07fc6572011-10-22 21:10:00 +00003776bool
Richard Smith51201882011-12-30 21:15:51 +00003777VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003778 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003779 QualType EltTy = VT->getElementType();
3780 APValue ZeroElement;
3781 if (EltTy->isIntegerType())
3782 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3783 else
3784 ZeroElement =
3785 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3786
Chris Lattner5f9e2722011-07-23 10:55:15 +00003787 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003788 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003789}
3790
Richard Smith07fc6572011-10-22 21:10:00 +00003791bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003792 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003793 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003794}
3795
Nate Begeman59b5da62009-01-18 03:20:47 +00003796//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003797// Array Evaluation
3798//===----------------------------------------------------------------------===//
3799
3800namespace {
3801 class ArrayExprEvaluator
3802 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003803 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003804 APValue &Result;
3805 public:
3806
Richard Smith180f4792011-11-10 06:34:14 +00003807 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3808 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003809
3810 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003811 assert((V.isArray() || V.isLValue()) &&
3812 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003813 Result = V;
3814 return true;
3815 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003816
Richard Smith51201882011-12-30 21:15:51 +00003817 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003818 const ConstantArrayType *CAT =
3819 Info.Ctx.getAsConstantArrayType(E->getType());
3820 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003821 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003822
3823 Result = APValue(APValue::UninitArray(), 0,
3824 CAT->getSize().getZExtValue());
3825 if (!Result.hasArrayFiller()) return true;
3826
Richard Smith51201882011-12-30 21:15:51 +00003827 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003828 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003829 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003830 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003831 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003832 }
3833
Richard Smithcc5d4f62011-11-07 09:22:26 +00003834 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003835 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003836 };
3837} // end anonymous namespace
3838
Richard Smith180f4792011-11-10 06:34:14 +00003839static bool EvaluateArray(const Expr *E, const LValue &This,
3840 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003841 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003842 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003843}
3844
3845bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3846 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3847 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003848 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003849
Richard Smith974c5f92011-12-22 01:07:19 +00003850 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3851 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003852 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003853 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3854 LValue LV;
3855 if (!EvaluateLValue(E->getInit(0), LV, Info))
3856 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003857 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003858 LV.moveInto(Val);
3859 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003860 }
3861
Richard Smith745f5142012-01-27 01:14:48 +00003862 bool Success = true;
3863
Richard Smithcc5d4f62011-11-07 09:22:26 +00003864 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3865 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003866 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003867 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003868 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003869 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003870 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003871 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3872 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003873 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3874 CAT->getElementType(), 1)) {
3875 if (!Info.keepEvaluatingAfterFailure())
3876 return false;
3877 Success = false;
3878 }
Richard Smith180f4792011-11-10 06:34:14 +00003879 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003880
Richard Smith745f5142012-01-27 01:14:48 +00003881 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003882 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003883 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3884 // but sometimes does:
3885 // struct S { constexpr S() : p(&p) {} void *p; };
3886 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003887 return EvaluateInPlace(Result.getArrayFiller(), Info,
3888 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003889}
3890
Richard Smithe24f5fc2011-11-17 22:56:20 +00003891bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3892 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3893 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003894 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003895
Richard Smithec789162012-01-12 18:54:33 +00003896 bool HadZeroInit = !Result.isUninit();
3897 if (!HadZeroInit)
3898 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003899 if (!Result.hasArrayFiller())
3900 return true;
3901
3902 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003903
Richard Smith51201882011-12-30 21:15:51 +00003904 bool ZeroInit = E->requiresZeroInitialization();
3905 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003906 if (HadZeroInit)
3907 return true;
3908
Richard Smith51201882011-12-30 21:15:51 +00003909 if (ZeroInit) {
3910 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003911 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003912 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003913 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003914 }
3915
Richard Smith61802452011-12-22 02:22:31 +00003916 const CXXRecordDecl *RD = FD->getParent();
3917 if (RD->isUnion())
3918 Result.getArrayFiller() = APValue((FieldDecl*)0);
3919 else
3920 Result.getArrayFiller() =
3921 APValue(APValue::UninitStruct(), RD->getNumBases(),
3922 std::distance(RD->field_begin(), RD->field_end()));
3923 return true;
3924 }
3925
Richard Smithe24f5fc2011-11-17 22:56:20 +00003926 const FunctionDecl *Definition = 0;
3927 FD->getBody(Definition);
3928
Richard Smithc1c5f272011-12-13 06:39:58 +00003929 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3930 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003931
3932 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3933 // but sometimes does:
3934 // struct S { constexpr S() : p(&p) {} void *p; };
3935 // S s[10];
3936 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003937 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003938
Richard Smithec789162012-01-12 18:54:33 +00003939 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003940 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003941 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003942 return false;
3943 }
3944
Richard Smithe24f5fc2011-11-17 22:56:20 +00003945 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003946 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003947 cast<CXXConstructorDecl>(Definition),
3948 Info, Result.getArrayFiller());
3949}
3950
Richard Smithcc5d4f62011-11-07 09:22:26 +00003951//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003952// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003953//
3954// As a GNU extension, we support casting pointers to sufficiently-wide integer
3955// types and back in constant folding. Integer values are thus represented
3956// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003957//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003958
3959namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003960class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003961 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003962 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003963public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003964 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003965 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003966
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003967 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003968 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003969 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003970 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003971 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003972 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003973 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003974 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003975 return true;
3976 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003977 bool Success(const llvm::APSInt &SI, const Expr *E) {
3978 return Success(SI, E, Result);
3979 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003980
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003981 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003982 assert(E->getType()->isIntegralOrEnumerationType() &&
3983 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003984 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003985 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003986 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003987 Result.getInt().setIsUnsigned(
3988 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003989 return true;
3990 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003991 bool Success(const llvm::APInt &I, const Expr *E) {
3992 return Success(I, E, Result);
3993 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00003994
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003995 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003996 assert(E->getType()->isIntegralOrEnumerationType() &&
3997 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003998 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003999 return true;
4000 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004001 bool Success(uint64_t Value, const Expr *E) {
4002 return Success(Value, E, Result);
4003 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00004004
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004005 bool Success(CharUnits Size, const Expr *E) {
4006 return Success(Size.getQuantity(), E);
4007 }
4008
Richard Smith1aa0be82012-03-03 22:46:17 +00004009 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00004010 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00004011 Result = V;
4012 return true;
4013 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004014 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00004015 }
Mike Stump1eb44332009-09-09 15:08:12 +00004016
Richard Smith51201882011-12-30 21:15:51 +00004017 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00004018
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004019 //===--------------------------------------------------------------------===//
4020 // Visitor Methods
4021 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004022
Chris Lattner4c4867e2008-07-12 00:38:25 +00004023 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004024 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004025 }
4026 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004027 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004028 }
Eli Friedman04309752009-11-24 05:28:59 +00004029
4030 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4031 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004032 if (CheckReferencedDecl(E, E->getDecl()))
4033 return true;
4034
4035 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004036 }
4037 bool VisitMemberExpr(const MemberExpr *E) {
4038 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004039 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004040 return true;
4041 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004042
4043 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004044 }
4045
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004046 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004047 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004048 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004049 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004050
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004051 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004052 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004053
Anders Carlsson3068d112008-11-16 19:01:22 +00004054 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004055 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004056 }
Mike Stump1eb44332009-09-09 15:08:12 +00004057
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004058 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4059 return Success(E->getValue(), E);
4060 }
4061
Richard Smithf10d9172011-10-11 21:43:33 +00004062 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004063 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004064 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004065 }
4066
Sebastian Redl64b45f72009-01-05 20:52:13 +00004067 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004068 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004069 }
4070
Francois Pichet6ad6f282010-12-07 00:08:36 +00004071 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4072 return Success(E->getValue(), E);
4073 }
4074
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004075 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4076 return Success(E->getValue(), E);
4077 }
4078
John Wiegley21ff2e52011-04-28 00:16:57 +00004079 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4080 return Success(E->getValue(), E);
4081 }
4082
John Wiegley55262202011-04-25 06:54:41 +00004083 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4084 return Success(E->getValue(), E);
4085 }
4086
Eli Friedman722c7172009-02-28 03:59:05 +00004087 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004088 bool VisitUnaryImag(const UnaryOperator *E);
4089
Sebastian Redl295995c2010-09-10 20:55:47 +00004090 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004091 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004092
Chris Lattnerfcee0012008-07-11 21:24:13 +00004093private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004094 CharUnits GetAlignOfExpr(const Expr *E);
4095 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004096 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004097 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004098 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004099};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004100} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004101
Richard Smithc49bd112011-10-28 17:51:58 +00004102/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4103/// produce either the integer value or a pointer.
4104///
4105/// GCC has a heinous extension which folds casts between pointer types and
4106/// pointer-sized integral types. We support this by allowing the evaluation of
4107/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4108/// Some simple arithmetic on such values is supported (they are treated much
4109/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004110static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004111 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004112 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004113 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004114}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004115
Richard Smithf48fdb02011-12-09 22:58:01 +00004116static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004117 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004118 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004119 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004120 if (!Val.isInt()) {
4121 // FIXME: It would be better to produce the diagnostic for casting
4122 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004123 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004124 return false;
4125 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004126 Result = Val.getInt();
4127 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004128}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004129
Richard Smithf48fdb02011-12-09 22:58:01 +00004130/// Check whether the given declaration can be directly converted to an integral
4131/// rvalue. If not, no diagnostic is produced; there are other things we can
4132/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004133bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004134 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004135 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004136 // Check for signedness/width mismatches between E type and ECD value.
4137 bool SameSign = (ECD->getInitVal().isSigned()
4138 == E->getType()->isSignedIntegerOrEnumerationType());
4139 bool SameWidth = (ECD->getInitVal().getBitWidth()
4140 == Info.Ctx.getIntWidth(E->getType()));
4141 if (SameSign && SameWidth)
4142 return Success(ECD->getInitVal(), E);
4143 else {
4144 // Get rid of mismatch (otherwise Success assertions will fail)
4145 // by computing a new value matching the type of E.
4146 llvm::APSInt Val = ECD->getInitVal();
4147 if (!SameSign)
4148 Val.setIsSigned(!ECD->getInitVal().isSigned());
4149 if (!SameWidth)
4150 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4151 return Success(Val, E);
4152 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004153 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004154 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004155}
4156
Chris Lattnera4d55d82008-10-06 06:40:35 +00004157/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4158/// as GCC.
4159static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4160 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004161 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004162 enum gcc_type_class {
4163 no_type_class = -1,
4164 void_type_class, integer_type_class, char_type_class,
4165 enumeral_type_class, boolean_type_class,
4166 pointer_type_class, reference_type_class, offset_type_class,
4167 real_type_class, complex_type_class,
4168 function_type_class, method_type_class,
4169 record_type_class, union_type_class,
4170 array_type_class, string_type_class,
4171 lang_type_class
4172 };
Mike Stump1eb44332009-09-09 15:08:12 +00004173
4174 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004175 // ideal, however it is what gcc does.
4176 if (E->getNumArgs() == 0)
4177 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004178
Chris Lattnera4d55d82008-10-06 06:40:35 +00004179 QualType ArgTy = E->getArg(0)->getType();
4180 if (ArgTy->isVoidType())
4181 return void_type_class;
4182 else if (ArgTy->isEnumeralType())
4183 return enumeral_type_class;
4184 else if (ArgTy->isBooleanType())
4185 return boolean_type_class;
4186 else if (ArgTy->isCharType())
4187 return string_type_class; // gcc doesn't appear to use char_type_class
4188 else if (ArgTy->isIntegerType())
4189 return integer_type_class;
4190 else if (ArgTy->isPointerType())
4191 return pointer_type_class;
4192 else if (ArgTy->isReferenceType())
4193 return reference_type_class;
4194 else if (ArgTy->isRealType())
4195 return real_type_class;
4196 else if (ArgTy->isComplexType())
4197 return complex_type_class;
4198 else if (ArgTy->isFunctionType())
4199 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004200 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004201 return record_type_class;
4202 else if (ArgTy->isUnionType())
4203 return union_type_class;
4204 else if (ArgTy->isArrayType())
4205 return array_type_class;
4206 else if (ArgTy->isUnionType())
4207 return union_type_class;
4208 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004209 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004210}
4211
Richard Smith80d4b552011-12-28 19:48:30 +00004212/// EvaluateBuiltinConstantPForLValue - Determine the result of
4213/// __builtin_constant_p when applied to the given lvalue.
4214///
4215/// An lvalue is only "constant" if it is a pointer or reference to the first
4216/// character of a string literal.
4217template<typename LValue>
4218static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004219 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004220 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4221}
4222
4223/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4224/// GCC as we can manage.
4225static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4226 QualType ArgType = Arg->getType();
4227
4228 // __builtin_constant_p always has one operand. The rules which gcc follows
4229 // are not precisely documented, but are as follows:
4230 //
4231 // - If the operand is of integral, floating, complex or enumeration type,
4232 // and can be folded to a known value of that type, it returns 1.
4233 // - If the operand and can be folded to a pointer to the first character
4234 // of a string literal (or such a pointer cast to an integral type), it
4235 // returns 1.
4236 //
4237 // Otherwise, it returns 0.
4238 //
4239 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4240 // its support for this does not currently work.
4241 if (ArgType->isIntegralOrEnumerationType()) {
4242 Expr::EvalResult Result;
4243 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4244 return false;
4245
4246 APValue &V = Result.Val;
4247 if (V.getKind() == APValue::Int)
4248 return true;
4249
4250 return EvaluateBuiltinConstantPForLValue(V);
4251 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4252 return Arg->isEvaluatable(Ctx);
4253 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4254 LValue LV;
4255 Expr::EvalStatus Status;
4256 EvalInfo Info(Ctx, Status);
4257 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4258 : EvaluatePointer(Arg, LV, Info)) &&
4259 !Status.HasSideEffects)
4260 return EvaluateBuiltinConstantPForLValue(LV);
4261 }
4262
4263 // Anything else isn't considered to be sufficiently constant.
4264 return false;
4265}
4266
John McCall42c8f872010-05-10 23:27:23 +00004267/// Retrieves the "underlying object type" of the given expression,
4268/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004269QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4270 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4271 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004272 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004273 } else if (const Expr *E = B.get<const Expr*>()) {
4274 if (isa<CompoundLiteralExpr>(E))
4275 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004276 }
4277
4278 return QualType();
4279}
4280
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004281bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004282 // TODO: Perhaps we should let LLVM lower this?
4283 LValue Base;
4284 if (!EvaluatePointer(E->getArg(0), Base, Info))
4285 return false;
4286
4287 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004288 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004289
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004290 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004291 if (T.isNull() ||
4292 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004293 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004294 T->isVariablyModifiedType() ||
4295 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004296 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004297
4298 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4299 CharUnits Offset = Base.getLValueOffset();
4300
4301 if (!Offset.isNegative() && Offset <= Size)
4302 Size -= Offset;
4303 else
4304 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004305 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004306}
4307
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004308bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith2c39d712012-04-13 00:45:38 +00004309 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004310 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004311 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004312
4313 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004314 if (TryEvaluateBuiltinObjectSize(E))
4315 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004316
Eric Christopherb2aaf512010-01-19 22:58:35 +00004317 // If evaluating the argument has side-effects we can't determine
4318 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004319 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004320 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004321 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004322 return Success(0, E);
4323 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004324
Richard Smithf48fdb02011-12-09 22:58:01 +00004325 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004326 }
4327
Chris Lattner019f4e82008-10-06 05:28:25 +00004328 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004329 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004330
Richard Smith80d4b552011-12-28 19:48:30 +00004331 case Builtin::BI__builtin_constant_p:
4332 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004333
Chris Lattner21fb98e2009-09-23 06:06:36 +00004334 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004335 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004336 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004337 return Success(Operand, E);
4338 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004339
4340 case Builtin::BI__builtin_expect:
4341 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004342
Douglas Gregor5726d402010-09-10 06:27:15 +00004343 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004344 // A call to strlen is not a constant expression.
4345 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004346 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004347 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4348 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004349 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004350 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004351 case Builtin::BI__builtin_strlen:
4352 // As an extension, we support strlen() and __builtin_strlen() as constant
4353 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004354 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004355 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4356 // The string literal may have embedded null characters. Find the first
4357 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004358 StringRef Str = S->getString();
4359 StringRef::size_type Pos = Str.find(0);
4360 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004361 Str = Str.substr(0, Pos);
4362
4363 return Success(Str.size(), E);
4364 }
4365
Richard Smithf48fdb02011-12-09 22:58:01 +00004366 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004367
Richard Smith2c39d712012-04-13 00:45:38 +00004368 case Builtin::BI__atomic_always_lock_free:
Richard Smithfafbf062012-04-11 17:55:32 +00004369 case Builtin::BI__atomic_is_lock_free:
4370 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedman454b57a2011-10-17 21:44:23 +00004371 APSInt SizeVal;
4372 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4373 return false;
4374
4375 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4376 // of two less than the maximum inline atomic width, we know it is
4377 // lock-free. If the size isn't a power of two, or greater than the
4378 // maximum alignment where we promote atomics, we know it is not lock-free
4379 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4380 // the answer can only be determined at runtime; for example, 16-byte
4381 // atomics have lock-free implementations on some, but not all,
4382 // x86-64 processors.
4383
4384 // Check power-of-two.
4385 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith2c39d712012-04-13 00:45:38 +00004386 if (Size.isPowerOfTwo()) {
4387 // Check against inlining width.
4388 unsigned InlineWidthBits =
4389 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4390 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4391 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4392 Size == CharUnits::One() ||
4393 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4394 Expr::NPC_NeverValueDependent))
4395 // OK, we will inline appropriately-aligned operations of this size,
4396 // and _Atomic(T) is appropriately-aligned.
4397 return Success(1, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004398
Richard Smith2c39d712012-04-13 00:45:38 +00004399 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4400 castAs<PointerType>()->getPointeeType();
4401 if (!PointeeType->isIncompleteType() &&
4402 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4403 // OK, we will inline operations on this object.
4404 return Success(1, E);
4405 }
4406 }
4407 }
Eli Friedman454b57a2011-10-17 21:44:23 +00004408
Richard Smith2c39d712012-04-13 00:45:38 +00004409 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4410 Success(0, E) : Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004411 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004412 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004413}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004414
Richard Smith625b8072011-10-31 01:37:14 +00004415static bool HasSameBase(const LValue &A, const LValue &B) {
4416 if (!A.getLValueBase())
4417 return !B.getLValueBase();
4418 if (!B.getLValueBase())
4419 return false;
4420
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004421 if (A.getLValueBase().getOpaqueValue() !=
4422 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004423 const Decl *ADecl = GetLValueBaseDecl(A);
4424 if (!ADecl)
4425 return false;
4426 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004427 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004428 return false;
4429 }
4430
4431 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004432 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004433}
4434
Richard Smith7b48a292012-02-01 05:53:12 +00004435/// Perform the given integer operation, which is known to need at most BitWidth
4436/// bits, and check for overflow in the original type (if that type was not an
4437/// unsigned type).
4438template<typename Operation>
4439static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4440 const APSInt &LHS, const APSInt &RHS,
4441 unsigned BitWidth, Operation Op) {
4442 if (LHS.isUnsigned())
4443 return Op(LHS, RHS);
4444
4445 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4446 APSInt Result = Value.trunc(LHS.getBitWidth());
4447 if (Result.extend(BitWidth) != Value)
4448 HandleOverflow(Info, E, Value, E->getType());
4449 return Result;
4450}
4451
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004452namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00004453
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004454/// \brief Data recursive integer evaluator of certain binary operators.
4455///
4456/// We use a data recursive algorithm for binary operators so that we are able
4457/// to handle extreme cases of chained binary operators without causing stack
4458/// overflow.
4459class DataRecursiveIntBinOpEvaluator {
4460 struct EvalResult {
4461 APValue Val;
4462 bool Failed;
4463
4464 EvalResult() : Failed(false) { }
4465
4466 void swap(EvalResult &RHS) {
4467 Val.swap(RHS.Val);
4468 Failed = RHS.Failed;
4469 RHS.Failed = false;
4470 }
4471 };
4472
4473 struct Job {
4474 const Expr *E;
4475 EvalResult LHSResult; // meaningful only for binary operator expression.
4476 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4477
4478 Job() : StoredInfo(0) { }
4479 void startSpeculativeEval(EvalInfo &Info) {
4480 OldEvalStatus = Info.EvalStatus;
4481 Info.EvalStatus.Diag = 0;
4482 StoredInfo = &Info;
4483 }
4484 ~Job() {
4485 if (StoredInfo) {
4486 StoredInfo->EvalStatus = OldEvalStatus;
4487 }
4488 }
4489 private:
4490 EvalInfo *StoredInfo; // non-null if status changed.
4491 Expr::EvalStatus OldEvalStatus;
4492 };
4493
4494 SmallVector<Job, 16> Queue;
4495
4496 IntExprEvaluator &IntEval;
4497 EvalInfo &Info;
4498 APValue &FinalResult;
4499
4500public:
4501 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4502 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4503
4504 /// \brief True if \param E is a binary operator that we are going to handle
4505 /// data recursively.
4506 /// We handle binary operators that are comma, logical, or that have operands
4507 /// with integral or enumeration type.
4508 static bool shouldEnqueue(const BinaryOperator *E) {
4509 return E->getOpcode() == BO_Comma ||
4510 E->isLogicalOp() ||
4511 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4512 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00004513 }
4514
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004515 bool Traverse(const BinaryOperator *E) {
4516 enqueue(E);
4517 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00004518 while (!Queue.empty())
4519 process(PrevResult);
4520
4521 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004522
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004523 FinalResult.swap(PrevResult.Val);
4524 return true;
4525 }
4526
4527private:
4528 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4529 return IntEval.Success(Value, E, Result);
4530 }
4531 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4532 return IntEval.Success(Value, E, Result);
4533 }
4534 bool Error(const Expr *E) {
4535 return IntEval.Error(E);
4536 }
4537 bool Error(const Expr *E, diag::kind D) {
4538 return IntEval.Error(E, D);
4539 }
4540
4541 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4542 return Info.CCEDiag(E, D);
4543 }
4544
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004545 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4546 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004547 bool &SuppressRHSDiags);
4548
4549 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4550 const BinaryOperator *E, APValue &Result);
4551
4552 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4553 Result.Failed = !Evaluate(Result.Val, Info, E);
4554 if (Result.Failed)
4555 Result.Val = APValue();
4556 }
4557
Richard Trieub7783052012-03-21 23:30:30 +00004558 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004559
4560 void enqueue(const Expr *E) {
4561 E = E->IgnoreParens();
4562 Queue.resize(Queue.size()+1);
4563 Queue.back().E = E;
4564 Queue.back().Kind = Job::AnyExprKind;
4565 }
4566};
4567
4568}
4569
4570bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004571 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004572 bool &SuppressRHSDiags) {
4573 if (E->getOpcode() == BO_Comma) {
4574 // Ignore LHS but note if we could not evaluate it.
4575 if (LHSResult.Failed)
4576 Info.EvalStatus.HasSideEffects = true;
4577 return true;
4578 }
4579
4580 if (E->isLogicalOp()) {
4581 bool lhsResult;
4582 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004583 // We were able to evaluate the LHS, see if we can get away with not
4584 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004585 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004586 Success(lhsResult, E, LHSResult.Val);
4587 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004588 }
4589 } else {
4590 // Since we weren't able to evaluate the left hand side, it
4591 // must have had side effects.
4592 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004593
4594 // We can't evaluate the LHS; however, sometimes the result
4595 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4596 // Don't ignore RHS and suppress diagnostics from this arm.
4597 SuppressRHSDiags = true;
4598 }
4599
4600 return true;
4601 }
4602
4603 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4604 E->getRHS()->getType()->isIntegralOrEnumerationType());
4605
4606 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004607 return false; // Ignore RHS;
4608
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004609 return true;
4610}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004611
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004612bool DataRecursiveIntBinOpEvaluator::
4613 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4614 const BinaryOperator *E, APValue &Result) {
4615 if (E->getOpcode() == BO_Comma) {
4616 if (RHSResult.Failed)
4617 return false;
4618 Result = RHSResult.Val;
4619 return true;
4620 }
4621
4622 if (E->isLogicalOp()) {
4623 bool lhsResult, rhsResult;
4624 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4625 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4626
4627 if (LHSIsOK) {
4628 if (RHSIsOK) {
4629 if (E->getOpcode() == BO_LOr)
4630 return Success(lhsResult || rhsResult, E, Result);
4631 else
4632 return Success(lhsResult && rhsResult, E, Result);
4633 }
4634 } else {
4635 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004636 // We can't evaluate the LHS; however, sometimes the result
4637 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4638 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004639 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004640 }
4641 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004642
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004643 return false;
4644 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004645
4646 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4647 E->getRHS()->getType()->isIntegralOrEnumerationType());
4648
4649 if (LHSResult.Failed || RHSResult.Failed)
4650 return false;
4651
4652 const APValue &LHSVal = LHSResult.Val;
4653 const APValue &RHSVal = RHSResult.Val;
4654
4655 // Handle cases like (unsigned long)&a + 4.
4656 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4657 Result = LHSVal;
4658 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4659 RHSVal.getInt().getZExtValue());
4660 if (E->getOpcode() == BO_Add)
4661 Result.getLValueOffset() += AdditionalOffset;
4662 else
4663 Result.getLValueOffset() -= AdditionalOffset;
4664 return true;
4665 }
4666
4667 // Handle cases like 4 + (unsigned long)&a
4668 if (E->getOpcode() == BO_Add &&
4669 RHSVal.isLValue() && LHSVal.isInt()) {
4670 Result = RHSVal;
4671 Result.getLValueOffset() += CharUnits::fromQuantity(
4672 LHSVal.getInt().getZExtValue());
4673 return true;
4674 }
4675
4676 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4677 // Handle (intptr_t)&&A - (intptr_t)&&B.
4678 if (!LHSVal.getLValueOffset().isZero() ||
4679 !RHSVal.getLValueOffset().isZero())
4680 return false;
4681 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4682 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4683 if (!LHSExpr || !RHSExpr)
4684 return false;
4685 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4686 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4687 if (!LHSAddrExpr || !RHSAddrExpr)
4688 return false;
4689 // Make sure both labels come from the same function.
4690 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4691 RHSAddrExpr->getLabel()->getDeclContext())
4692 return false;
4693 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4694 return true;
4695 }
4696
4697 // All the following cases expect both operands to be an integer
4698 if (!LHSVal.isInt() || !RHSVal.isInt())
4699 return Error(E);
4700
4701 const APSInt &LHS = LHSVal.getInt();
4702 APSInt RHS = RHSVal.getInt();
4703
4704 switch (E->getOpcode()) {
4705 default:
4706 return Error(E);
4707 case BO_Mul:
4708 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4709 LHS.getBitWidth() * 2,
4710 std::multiplies<APSInt>()), E,
4711 Result);
4712 case BO_Add:
4713 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4714 LHS.getBitWidth() + 1,
4715 std::plus<APSInt>()), E, Result);
4716 case BO_Sub:
4717 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4718 LHS.getBitWidth() + 1,
4719 std::minus<APSInt>()), E, Result);
4720 case BO_And: return Success(LHS & RHS, E, Result);
4721 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4722 case BO_Or: return Success(LHS | RHS, E, Result);
4723 case BO_Div:
4724 case BO_Rem:
4725 if (RHS == 0)
4726 return Error(E, diag::note_expr_divide_by_zero);
4727 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4728 // not actually undefined behavior in C++11 due to a language defect.
4729 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4730 LHS.isSigned() && LHS.isMinSignedValue())
4731 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4732 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4733 Result);
4734 case BO_Shl: {
4735 // During constant-folding, a negative shift is an opposite shift. Such
4736 // a shift is not a constant expression.
4737 if (RHS.isSigned() && RHS.isNegative()) {
4738 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4739 RHS = -RHS;
4740 goto shift_right;
4741 }
4742
4743 shift_left:
4744 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4745 // the shifted type.
4746 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4747 if (SA != RHS) {
4748 CCEDiag(E, diag::note_constexpr_large_shift)
4749 << RHS << E->getType() << LHS.getBitWidth();
4750 } else if (LHS.isSigned()) {
4751 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4752 // operand, and must not overflow the corresponding unsigned type.
4753 if (LHS.isNegative())
4754 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4755 else if (LHS.countLeadingZeros() < SA)
4756 CCEDiag(E, diag::note_constexpr_lshift_discards);
4757 }
4758
4759 return Success(LHS << SA, E, Result);
4760 }
4761 case BO_Shr: {
4762 // During constant-folding, a negative shift is an opposite shift. Such a
4763 // shift is not a constant expression.
4764 if (RHS.isSigned() && RHS.isNegative()) {
4765 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4766 RHS = -RHS;
4767 goto shift_left;
4768 }
4769
4770 shift_right:
4771 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4772 // shifted type.
4773 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4774 if (SA != RHS)
4775 CCEDiag(E, diag::note_constexpr_large_shift)
4776 << RHS << E->getType() << LHS.getBitWidth();
4777
4778 return Success(LHS >> SA, E, Result);
4779 }
4780
4781 case BO_LT: return Success(LHS < RHS, E, Result);
4782 case BO_GT: return Success(LHS > RHS, E, Result);
4783 case BO_LE: return Success(LHS <= RHS, E, Result);
4784 case BO_GE: return Success(LHS >= RHS, E, Result);
4785 case BO_EQ: return Success(LHS == RHS, E, Result);
4786 case BO_NE: return Success(LHS != RHS, E, Result);
4787 }
4788}
4789
Richard Trieub7783052012-03-21 23:30:30 +00004790void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004791 Job &job = Queue.back();
4792
4793 switch (job.Kind) {
4794 case Job::AnyExprKind: {
4795 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4796 if (shouldEnqueue(Bop)) {
4797 job.Kind = Job::BinOpKind;
4798 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00004799 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004800 }
4801 }
4802
4803 EvaluateExpr(job.E, Result);
4804 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004805 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004806 }
4807
4808 case Job::BinOpKind: {
4809 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004810 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004811 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004812 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004813 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004814 }
4815 if (SuppressRHSDiags)
4816 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004817 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004818 job.Kind = Job::BinOpVisitedLHSKind;
4819 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00004820 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004821 }
4822
4823 case Job::BinOpVisitedLHSKind: {
4824 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4825 EvalResult RHS;
4826 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00004827 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004828 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004829 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004830 }
4831 }
4832
4833 llvm_unreachable("Invalid Job::Kind!");
4834}
4835
4836bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4837 if (E->isAssignmentOp())
4838 return Error(E);
4839
4840 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4841 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004842
Anders Carlsson286f85e2008-11-16 07:17:21 +00004843 QualType LHSTy = E->getLHS()->getType();
4844 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004845
4846 if (LHSTy->isAnyComplexType()) {
4847 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004848 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004849
Richard Smith745f5142012-01-27 01:14:48 +00004850 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4851 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004852 return false;
4853
Richard Smith745f5142012-01-27 01:14:48 +00004854 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004855 return false;
4856
4857 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004858 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004859 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004860 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004861 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4862
John McCall2de56d12010-08-25 11:45:40 +00004863 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004864 return Success((CR_r == APFloat::cmpEqual &&
4865 CR_i == APFloat::cmpEqual), E);
4866 else {
John McCall2de56d12010-08-25 11:45:40 +00004867 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004868 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004869 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004870 CR_r == APFloat::cmpLessThan ||
4871 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004872 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004873 CR_i == APFloat::cmpLessThan ||
4874 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004875 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004876 } else {
John McCall2de56d12010-08-25 11:45:40 +00004877 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004878 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4879 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4880 else {
John McCall2de56d12010-08-25 11:45:40 +00004881 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004882 "Invalid compex comparison.");
4883 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4884 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4885 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004886 }
4887 }
Mike Stump1eb44332009-09-09 15:08:12 +00004888
Anders Carlsson286f85e2008-11-16 07:17:21 +00004889 if (LHSTy->isRealFloatingType() &&
4890 RHSTy->isRealFloatingType()) {
4891 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004892
Richard Smith745f5142012-01-27 01:14:48 +00004893 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4894 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004895 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004896
Richard Smith745f5142012-01-27 01:14:48 +00004897 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004898 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004899
Anders Carlsson286f85e2008-11-16 07:17:21 +00004900 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004901
Anders Carlsson286f85e2008-11-16 07:17:21 +00004902 switch (E->getOpcode()) {
4903 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004904 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004905 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004906 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004907 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004908 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004909 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004910 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004911 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004912 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004913 E);
John McCall2de56d12010-08-25 11:45:40 +00004914 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004915 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004916 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004917 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004918 || CR == APFloat::cmpLessThan
4919 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004920 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004921 }
Mike Stump1eb44332009-09-09 15:08:12 +00004922
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004923 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004924 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004925 LValue LHSValue, RHSValue;
4926
4927 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4928 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004929 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004930
Richard Smith745f5142012-01-27 01:14:48 +00004931 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004932 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004933
Richard Smith625b8072011-10-31 01:37:14 +00004934 // Reject differing bases from the normal codepath; we special-case
4935 // comparisons to null.
4936 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004937 if (E->getOpcode() == BO_Sub) {
4938 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004939 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4940 return false;
4941 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4942 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4943 if (!LHSExpr || !RHSExpr)
4944 return false;
4945 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4946 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4947 if (!LHSAddrExpr || !RHSAddrExpr)
4948 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004949 // Make sure both labels come from the same function.
4950 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4951 RHSAddrExpr->getLabel()->getDeclContext())
4952 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004953 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004954 return true;
4955 }
Richard Smith9e36b532011-10-31 05:11:32 +00004956 // Inequalities and subtractions between unrelated pointers have
4957 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004958 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004959 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004960 // A constant address may compare equal to the address of a symbol.
4961 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004962 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004963 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4964 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004965 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004966 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004967 // distinct addresses. In clang, the result of such a comparison is
4968 // unspecified, so it is not a constant expression. However, we do know
4969 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004970 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4971 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004972 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004973 // We can't tell whether weak symbols will end up pointing to the same
4974 // object.
4975 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004976 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004977 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004978 // (Note that clang defaults to -fmerge-all-constants, which can
4979 // lead to inconsistent results for comparisons involving the address
4980 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004981 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004982 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004983
Richard Smith15efc4d2012-02-01 08:10:20 +00004984 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4985 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4986
Richard Smithf15fda02012-02-02 01:16:57 +00004987 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4988 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4989
John McCall2de56d12010-08-25 11:45:40 +00004990 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004991 // C++11 [expr.add]p6:
4992 // Unless both pointers point to elements of the same array object, or
4993 // one past the last element of the array object, the behavior is
4994 // undefined.
4995 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4996 !AreElementsOfSameArray(getType(LHSValue.Base),
4997 LHSDesignator, RHSDesignator))
4998 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4999
Chris Lattner4992bdd2010-04-20 17:13:14 +00005000 QualType Type = E->getLHS()->getType();
5001 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00005002
Richard Smith180f4792011-11-10 06:34:14 +00005003 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00005004 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00005005 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00005006
Richard Smith15efc4d2012-02-01 08:10:20 +00005007 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5008 // and produce incorrect results when it overflows. Such behavior
5009 // appears to be non-conforming, but is common, so perhaps we should
5010 // assume the standard intended for such cases to be undefined behavior
5011 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00005012
Richard Smith15efc4d2012-02-01 08:10:20 +00005013 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5014 // overflow in the final conversion to ptrdiff_t.
5015 APSInt LHS(
5016 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5017 APSInt RHS(
5018 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5019 APSInt ElemSize(
5020 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5021 APSInt TrueResult = (LHS - RHS) / ElemSize;
5022 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5023
5024 if (Result.extend(65) != TrueResult)
5025 HandleOverflow(Info, E, TrueResult, E->getType());
5026 return Success(Result, E);
5027 }
Richard Smith82f28582012-01-31 06:41:30 +00005028
5029 // C++11 [expr.rel]p3:
5030 // Pointers to void (after pointer conversions) can be compared, with a
5031 // result defined as follows: If both pointers represent the same
5032 // address or are both the null pointer value, the result is true if the
5033 // operator is <= or >= and false otherwise; otherwise the result is
5034 // unspecified.
5035 // We interpret this as applying to pointers to *cv* void.
5036 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00005037 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00005038 CCEDiag(E, diag::note_constexpr_void_comparison);
5039
Richard Smithf15fda02012-02-02 01:16:57 +00005040 // C++11 [expr.rel]p2:
5041 // - If two pointers point to non-static data members of the same object,
5042 // or to subobjects or array elements fo such members, recursively, the
5043 // pointer to the later declared member compares greater provided the
5044 // two members have the same access control and provided their class is
5045 // not a union.
5046 // [...]
5047 // - Otherwise pointer comparisons are unspecified.
5048 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5049 E->isRelationalOp()) {
5050 bool WasArrayIndex;
5051 unsigned Mismatch =
5052 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5053 RHSDesignator, WasArrayIndex);
5054 // At the point where the designators diverge, the comparison has a
5055 // specified value if:
5056 // - we are comparing array indices
5057 // - we are comparing fields of a union, or fields with the same access
5058 // Otherwise, the result is unspecified and thus the comparison is not a
5059 // constant expression.
5060 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5061 Mismatch < RHSDesignator.Entries.size()) {
5062 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5063 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5064 if (!LF && !RF)
5065 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5066 else if (!LF)
5067 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5068 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5069 << RF->getParent() << RF;
5070 else if (!RF)
5071 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5072 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5073 << LF->getParent() << LF;
5074 else if (!LF->getParent()->isUnion() &&
5075 LF->getAccess() != RF->getAccess())
5076 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5077 << LF << LF->getAccess() << RF << RF->getAccess()
5078 << LF->getParent();
5079 }
5080 }
5081
Richard Smith625b8072011-10-31 01:37:14 +00005082 switch (E->getOpcode()) {
5083 default: llvm_unreachable("missing comparison operator");
5084 case BO_LT: return Success(LHSOffset < RHSOffset, E);
5085 case BO_GT: return Success(LHSOffset > RHSOffset, E);
5086 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
5087 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
5088 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
5089 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00005090 }
Anders Carlsson3068d112008-11-16 19:01:22 +00005091 }
5092 }
Richard Smithb02e4622012-02-01 01:42:44 +00005093
5094 if (LHSTy->isMemberPointerType()) {
5095 assert(E->isEqualityOp() && "unexpected member pointer operation");
5096 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5097
5098 MemberPtr LHSValue, RHSValue;
5099
5100 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5101 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5102 return false;
5103
5104 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5105 return false;
5106
5107 // C++11 [expr.eq]p2:
5108 // If both operands are null, they compare equal. Otherwise if only one is
5109 // null, they compare unequal.
5110 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5111 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5112 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5113 }
5114
5115 // Otherwise if either is a pointer to a virtual member function, the
5116 // result is unspecified.
5117 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5118 if (MD->isVirtual())
5119 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5120 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5121 if (MD->isVirtual())
5122 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5123
5124 // Otherwise they compare equal if and only if they would refer to the
5125 // same member of the same most derived object or the same subobject if
5126 // they were dereferenced with a hypothetical object of the associated
5127 // class type.
5128 bool Equal = LHSValue == RHSValue;
5129 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5130 }
5131
Richard Smith26f2cac2012-02-14 22:35:28 +00005132 if (LHSTy->isNullPtrType()) {
5133 assert(E->isComparisonOp() && "unexpected nullptr operation");
5134 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5135 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5136 // are compared, the result is true of the operator is <=, >= or ==, and
5137 // false otherwise.
5138 BinaryOperator::Opcode Opcode = E->getOpcode();
5139 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5140 }
5141
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005142 assert((!LHSTy->isIntegralOrEnumerationType() ||
5143 !RHSTy->isIntegralOrEnumerationType()) &&
5144 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5145 // We can't continue from here for non-integral types.
5146 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005147}
5148
Ken Dyck8b752f12010-01-27 17:10:57 +00005149CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005150 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5151 // result shall be the alignment of the referenced type."
5152 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5153 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005154
5155 // __alignof is defined to return the preferred alignment.
5156 return Info.Ctx.toCharUnitsFromBits(
5157 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005158}
5159
Ken Dyck8b752f12010-01-27 17:10:57 +00005160CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005161 E = E->IgnoreParens();
5162
5163 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005164 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005165 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005166 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5167 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005168
Chris Lattneraf707ab2009-01-24 21:53:27 +00005169 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005170 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5171 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005172
Chris Lattnere9feb472009-01-24 21:09:06 +00005173 return GetAlignOfType(E->getType());
5174}
5175
5176
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005177/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5178/// a result as the expression's type.
5179bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5180 const UnaryExprOrTypeTraitExpr *E) {
5181 switch(E->getKind()) {
5182 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005183 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005184 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005185 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005186 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005187 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005188
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005189 case UETT_VecStep: {
5190 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005191
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005192 if (Ty->isVectorType()) {
5193 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005194
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005195 // The vec_step built-in functions that take a 3-component
5196 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5197 if (n == 3)
5198 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005199
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005200 return Success(n, E);
5201 } else
5202 return Success(1, E);
5203 }
5204
5205 case UETT_SizeOf: {
5206 QualType SrcTy = E->getTypeOfArgument();
5207 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5208 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005209 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5210 SrcTy = Ref->getPointeeType();
5211
Richard Smith180f4792011-11-10 06:34:14 +00005212 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005213 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005214 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005215 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005216 }
5217 }
5218
5219 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005220}
5221
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005222bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005223 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005224 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005225 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005226 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005227 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005228 for (unsigned i = 0; i != n; ++i) {
5229 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5230 switch (ON.getKind()) {
5231 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005232 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005233 APSInt IdxResult;
5234 if (!EvaluateInteger(Idx, IdxResult, Info))
5235 return false;
5236 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5237 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005238 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005239 CurrentType = AT->getElementType();
5240 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5241 Result += IdxResult.getSExtValue() * ElementSize;
5242 break;
5243 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005244
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005245 case OffsetOfExpr::OffsetOfNode::Field: {
5246 FieldDecl *MemberDecl = ON.getField();
5247 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005248 if (!RT)
5249 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005250 RecordDecl *RD = RT->getDecl();
5251 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005252 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005253 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005254 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005255 CurrentType = MemberDecl->getType().getNonReferenceType();
5256 break;
5257 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005258
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005259 case OffsetOfExpr::OffsetOfNode::Identifier:
5260 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005261
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005262 case OffsetOfExpr::OffsetOfNode::Base: {
5263 CXXBaseSpecifier *BaseSpec = ON.getBase();
5264 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005265 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005266
5267 // Find the layout of the class whose base we are looking into.
5268 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005269 if (!RT)
5270 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005271 RecordDecl *RD = RT->getDecl();
5272 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5273
5274 // Find the base class itself.
5275 CurrentType = BaseSpec->getType();
5276 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5277 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005278 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005279
5280 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005281 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005282 break;
5283 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005284 }
5285 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005286 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005287}
5288
Chris Lattnerb542afe2008-07-11 19:10:17 +00005289bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005290 switch (E->getOpcode()) {
5291 default:
5292 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5293 // See C99 6.6p3.
5294 return Error(E);
5295 case UO_Extension:
5296 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5297 // If so, we could clear the diagnostic ID.
5298 return Visit(E->getSubExpr());
5299 case UO_Plus:
5300 // The result is just the value.
5301 return Visit(E->getSubExpr());
5302 case UO_Minus: {
5303 if (!Visit(E->getSubExpr()))
5304 return false;
5305 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005306 const APSInt &Value = Result.getInt();
5307 if (Value.isSigned() && Value.isMinSignedValue())
5308 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5309 E->getType());
5310 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005311 }
5312 case UO_Not: {
5313 if (!Visit(E->getSubExpr()))
5314 return false;
5315 if (!Result.isInt()) return Error(E);
5316 return Success(~Result.getInt(), E);
5317 }
5318 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005319 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005320 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005321 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005322 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005323 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005324 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005325}
Mike Stump1eb44332009-09-09 15:08:12 +00005326
Chris Lattner732b2232008-07-12 01:15:53 +00005327/// HandleCast - This is used to evaluate implicit or explicit casts where the
5328/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005329bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5330 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005331 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005332 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005333
Eli Friedman46a52322011-03-25 00:43:55 +00005334 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005335 case CK_BaseToDerived:
5336 case CK_DerivedToBase:
5337 case CK_UncheckedDerivedToBase:
5338 case CK_Dynamic:
5339 case CK_ToUnion:
5340 case CK_ArrayToPointerDecay:
5341 case CK_FunctionToPointerDecay:
5342 case CK_NullToPointer:
5343 case CK_NullToMemberPointer:
5344 case CK_BaseToDerivedMemberPointer:
5345 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005346 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005347 case CK_ConstructorConversion:
5348 case CK_IntegralToPointer:
5349 case CK_ToVoid:
5350 case CK_VectorSplat:
5351 case CK_IntegralToFloating:
5352 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005353 case CK_CPointerToObjCPointerCast:
5354 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005355 case CK_AnyPointerToBlockPointerCast:
5356 case CK_ObjCObjectLValueCast:
5357 case CK_FloatingRealToComplex:
5358 case CK_FloatingComplexToReal:
5359 case CK_FloatingComplexCast:
5360 case CK_FloatingComplexToIntegralComplex:
5361 case CK_IntegralRealToComplex:
5362 case CK_IntegralComplexCast:
5363 case CK_IntegralComplexToFloatingComplex:
5364 llvm_unreachable("invalid cast kind for integral value");
5365
Eli Friedmane50c2972011-03-25 19:07:11 +00005366 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005367 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005368 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005369 case CK_ARCProduceObject:
5370 case CK_ARCConsumeObject:
5371 case CK_ARCReclaimReturnedObject:
5372 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005373 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005374 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005375
Richard Smith7d580a42012-01-17 21:17:26 +00005376 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005377 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005378 case CK_AtomicToNonAtomic:
5379 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005380 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005381 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005382
5383 case CK_MemberPointerToBoolean:
5384 case CK_PointerToBoolean:
5385 case CK_IntegralToBoolean:
5386 case CK_FloatingToBoolean:
5387 case CK_FloatingComplexToBoolean:
5388 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005389 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005390 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005391 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005392 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005393 }
5394
Eli Friedman46a52322011-03-25 00:43:55 +00005395 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005396 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005397 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005398
Eli Friedmanbe265702009-02-20 01:15:07 +00005399 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005400 // Allow casts of address-of-label differences if they are no-ops
5401 // or narrowing. (The narrowing case isn't actually guaranteed to
5402 // be constant-evaluatable except in some narrow cases which are hard
5403 // to detect here. We let it through on the assumption the user knows
5404 // what they are doing.)
5405 if (Result.isAddrLabelDiff())
5406 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005407 // Only allow casts of lvalues if they are lossless.
5408 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5409 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005410
Richard Smithf72fccf2012-01-30 22:27:01 +00005411 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5412 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005413 }
Mike Stump1eb44332009-09-09 15:08:12 +00005414
Eli Friedman46a52322011-03-25 00:43:55 +00005415 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005416 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5417
John McCallefdb83e2010-05-07 21:00:08 +00005418 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005419 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005420 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005421
Daniel Dunbardd211642009-02-19 22:24:01 +00005422 if (LV.getLValueBase()) {
5423 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005424 // FIXME: Allow a larger integer size than the pointer size, and allow
5425 // narrowing back down to pointer width in subsequent integral casts.
5426 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005427 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005428 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005429
Richard Smithb755a9d2011-11-16 07:18:12 +00005430 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005431 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005432 return true;
5433 }
5434
Ken Dycka7305832010-01-15 12:37:54 +00005435 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5436 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005437 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005438 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005439
Eli Friedman46a52322011-03-25 00:43:55 +00005440 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005441 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005442 if (!EvaluateComplex(SubExpr, C, Info))
5443 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005444 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005445 }
Eli Friedman2217c872009-02-22 11:46:18 +00005446
Eli Friedman46a52322011-03-25 00:43:55 +00005447 case CK_FloatingToIntegral: {
5448 APFloat F(0.0);
5449 if (!EvaluateFloat(SubExpr, F, Info))
5450 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005451
Richard Smithc1c5f272011-12-13 06:39:58 +00005452 APSInt Value;
5453 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5454 return false;
5455 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005456 }
5457 }
Mike Stump1eb44332009-09-09 15:08:12 +00005458
Eli Friedman46a52322011-03-25 00:43:55 +00005459 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005460}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005461
Eli Friedman722c7172009-02-28 03:59:05 +00005462bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5463 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005464 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005465 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5466 return false;
5467 if (!LV.isComplexInt())
5468 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005469 return Success(LV.getComplexIntReal(), E);
5470 }
5471
5472 return Visit(E->getSubExpr());
5473}
5474
Eli Friedman664a1042009-02-27 04:45:43 +00005475bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005476 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005477 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005478 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5479 return false;
5480 if (!LV.isComplexInt())
5481 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005482 return Success(LV.getComplexIntImag(), E);
5483 }
5484
Richard Smith8327fad2011-10-24 18:44:57 +00005485 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005486 return Success(0, E);
5487}
5488
Douglas Gregoree8aff02011-01-04 17:33:58 +00005489bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5490 return Success(E->getPackLength(), E);
5491}
5492
Sebastian Redl295995c2010-09-10 20:55:47 +00005493bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5494 return Success(E->getValue(), E);
5495}
5496
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005497//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005498// Float Evaluation
5499//===----------------------------------------------------------------------===//
5500
5501namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005502class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005503 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005504 APFloat &Result;
5505public:
5506 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005507 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005508
Richard Smith1aa0be82012-03-03 22:46:17 +00005509 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005510 Result = V.getFloat();
5511 return true;
5512 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005513
Richard Smith51201882011-12-30 21:15:51 +00005514 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005515 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5516 return true;
5517 }
5518
Chris Lattner019f4e82008-10-06 05:28:25 +00005519 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005520
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005521 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005522 bool VisitBinaryOperator(const BinaryOperator *E);
5523 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005524 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005525
John McCallabd3a852010-05-07 22:08:54 +00005526 bool VisitUnaryReal(const UnaryOperator *E);
5527 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005528
Richard Smith51201882011-12-30 21:15:51 +00005529 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005530};
5531} // end anonymous namespace
5532
5533static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005534 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005535 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005536}
5537
Jay Foad4ba2a172011-01-12 09:06:06 +00005538static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005539 QualType ResultTy,
5540 const Expr *Arg,
5541 bool SNaN,
5542 llvm::APFloat &Result) {
5543 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5544 if (!S) return false;
5545
5546 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5547
5548 llvm::APInt fill;
5549
5550 // Treat empty strings as if they were zero.
5551 if (S->getString().empty())
5552 fill = llvm::APInt(32, 0);
5553 else if (S->getString().getAsInteger(0, fill))
5554 return false;
5555
5556 if (SNaN)
5557 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5558 else
5559 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5560 return true;
5561}
5562
Chris Lattner019f4e82008-10-06 05:28:25 +00005563bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005564 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005565 default:
5566 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5567
Chris Lattner019f4e82008-10-06 05:28:25 +00005568 case Builtin::BI__builtin_huge_val:
5569 case Builtin::BI__builtin_huge_valf:
5570 case Builtin::BI__builtin_huge_vall:
5571 case Builtin::BI__builtin_inf:
5572 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005573 case Builtin::BI__builtin_infl: {
5574 const llvm::fltSemantics &Sem =
5575 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005576 Result = llvm::APFloat::getInf(Sem);
5577 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005578 }
Mike Stump1eb44332009-09-09 15:08:12 +00005579
John McCalldb7b72a2010-02-28 13:00:19 +00005580 case Builtin::BI__builtin_nans:
5581 case Builtin::BI__builtin_nansf:
5582 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005583 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5584 true, Result))
5585 return Error(E);
5586 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005587
Chris Lattner9e621712008-10-06 06:31:58 +00005588 case Builtin::BI__builtin_nan:
5589 case Builtin::BI__builtin_nanf:
5590 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005591 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005592 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005593 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5594 false, Result))
5595 return Error(E);
5596 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005597
5598 case Builtin::BI__builtin_fabs:
5599 case Builtin::BI__builtin_fabsf:
5600 case Builtin::BI__builtin_fabsl:
5601 if (!EvaluateFloat(E->getArg(0), Result, Info))
5602 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005603
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005604 if (Result.isNegative())
5605 Result.changeSign();
5606 return true;
5607
Mike Stump1eb44332009-09-09 15:08:12 +00005608 case Builtin::BI__builtin_copysign:
5609 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005610 case Builtin::BI__builtin_copysignl: {
5611 APFloat RHS(0.);
5612 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5613 !EvaluateFloat(E->getArg(1), RHS, Info))
5614 return false;
5615 Result.copySign(RHS);
5616 return true;
5617 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005618 }
5619}
5620
John McCallabd3a852010-05-07 22:08:54 +00005621bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005622 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5623 ComplexValue CV;
5624 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5625 return false;
5626 Result = CV.FloatReal;
5627 return true;
5628 }
5629
5630 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005631}
5632
5633bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005634 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5635 ComplexValue CV;
5636 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5637 return false;
5638 Result = CV.FloatImag;
5639 return true;
5640 }
5641
Richard Smith8327fad2011-10-24 18:44:57 +00005642 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005643 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5644 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005645 return true;
5646}
5647
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005648bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005649 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005650 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005651 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005652 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005653 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005654 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5655 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005656 Result.changeSign();
5657 return true;
5658 }
5659}
Chris Lattner019f4e82008-10-06 05:28:25 +00005660
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005661bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005662 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5663 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005664
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005665 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005666 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5667 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005668 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005669 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005670 return false;
5671
5672 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005673 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005674 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005675 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005676 break;
John McCall2de56d12010-08-25 11:45:40 +00005677 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005678 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005679 break;
John McCall2de56d12010-08-25 11:45:40 +00005680 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005681 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005682 break;
John McCall2de56d12010-08-25 11:45:40 +00005683 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005684 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005685 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005686 }
Richard Smith7b48a292012-02-01 05:53:12 +00005687
5688 if (Result.isInfinity() || Result.isNaN())
5689 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5690 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005691}
5692
5693bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5694 Result = E->getValue();
5695 return true;
5696}
5697
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005698bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5699 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005700
Eli Friedman2a523ee2011-03-25 00:54:52 +00005701 switch (E->getCastKind()) {
5702 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005703 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005704
5705 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005706 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005707 return EvaluateInteger(SubExpr, IntResult, Info) &&
5708 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5709 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005710 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005711
5712 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005713 if (!Visit(SubExpr))
5714 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005715 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5716 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005717 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005718
Eli Friedman2a523ee2011-03-25 00:54:52 +00005719 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005720 ComplexValue V;
5721 if (!EvaluateComplex(SubExpr, V, Info))
5722 return false;
5723 Result = V.getComplexFloatReal();
5724 return true;
5725 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005726 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005727}
5728
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005729//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005730// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005731//===----------------------------------------------------------------------===//
5732
5733namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005734class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005735 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005736 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005737
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005738public:
John McCallf4cf1a12010-05-07 17:22:02 +00005739 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005740 : ExprEvaluatorBaseTy(info), Result(Result) {}
5741
Richard Smith1aa0be82012-03-03 22:46:17 +00005742 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005743 Result.setFrom(V);
5744 return true;
5745 }
Mike Stump1eb44332009-09-09 15:08:12 +00005746
Eli Friedman7ead5c72012-01-10 04:58:17 +00005747 bool ZeroInitialization(const Expr *E);
5748
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005749 //===--------------------------------------------------------------------===//
5750 // Visitor Methods
5751 //===--------------------------------------------------------------------===//
5752
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005753 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005754 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005755 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005756 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005757 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005758};
5759} // end anonymous namespace
5760
John McCallf4cf1a12010-05-07 17:22:02 +00005761static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5762 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005763 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005764 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005765}
5766
Eli Friedman7ead5c72012-01-10 04:58:17 +00005767bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005768 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005769 if (ElemTy->isRealFloatingType()) {
5770 Result.makeComplexFloat();
5771 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5772 Result.FloatReal = Zero;
5773 Result.FloatImag = Zero;
5774 } else {
5775 Result.makeComplexInt();
5776 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5777 Result.IntReal = Zero;
5778 Result.IntImag = Zero;
5779 }
5780 return true;
5781}
5782
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005783bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5784 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005785
5786 if (SubExpr->getType()->isRealFloatingType()) {
5787 Result.makeComplexFloat();
5788 APFloat &Imag = Result.FloatImag;
5789 if (!EvaluateFloat(SubExpr, Imag, Info))
5790 return false;
5791
5792 Result.FloatReal = APFloat(Imag.getSemantics());
5793 return true;
5794 } else {
5795 assert(SubExpr->getType()->isIntegerType() &&
5796 "Unexpected imaginary literal.");
5797
5798 Result.makeComplexInt();
5799 APSInt &Imag = Result.IntImag;
5800 if (!EvaluateInteger(SubExpr, Imag, Info))
5801 return false;
5802
5803 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5804 return true;
5805 }
5806}
5807
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005808bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005809
John McCall8786da72010-12-14 17:51:41 +00005810 switch (E->getCastKind()) {
5811 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005812 case CK_BaseToDerived:
5813 case CK_DerivedToBase:
5814 case CK_UncheckedDerivedToBase:
5815 case CK_Dynamic:
5816 case CK_ToUnion:
5817 case CK_ArrayToPointerDecay:
5818 case CK_FunctionToPointerDecay:
5819 case CK_NullToPointer:
5820 case CK_NullToMemberPointer:
5821 case CK_BaseToDerivedMemberPointer:
5822 case CK_DerivedToBaseMemberPointer:
5823 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005824 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005825 case CK_ConstructorConversion:
5826 case CK_IntegralToPointer:
5827 case CK_PointerToIntegral:
5828 case CK_PointerToBoolean:
5829 case CK_ToVoid:
5830 case CK_VectorSplat:
5831 case CK_IntegralCast:
5832 case CK_IntegralToBoolean:
5833 case CK_IntegralToFloating:
5834 case CK_FloatingToIntegral:
5835 case CK_FloatingToBoolean:
5836 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005837 case CK_CPointerToObjCPointerCast:
5838 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005839 case CK_AnyPointerToBlockPointerCast:
5840 case CK_ObjCObjectLValueCast:
5841 case CK_FloatingComplexToReal:
5842 case CK_FloatingComplexToBoolean:
5843 case CK_IntegralComplexToReal:
5844 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005845 case CK_ARCProduceObject:
5846 case CK_ARCConsumeObject:
5847 case CK_ARCReclaimReturnedObject:
5848 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005849 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005850 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005851
John McCall8786da72010-12-14 17:51:41 +00005852 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005853 case CK_AtomicToNonAtomic:
5854 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005855 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005856 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005857
5858 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005859 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005860 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005861 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005862
5863 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005864 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005865 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005866 return false;
5867
John McCall8786da72010-12-14 17:51:41 +00005868 Result.makeComplexFloat();
5869 Result.FloatImag = APFloat(Real.getSemantics());
5870 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005871 }
5872
John McCall8786da72010-12-14 17:51:41 +00005873 case CK_FloatingComplexCast: {
5874 if (!Visit(E->getSubExpr()))
5875 return false;
5876
5877 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5878 QualType From
5879 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5880
Richard Smithc1c5f272011-12-13 06:39:58 +00005881 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5882 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005883 }
5884
5885 case CK_FloatingComplexToIntegralComplex: {
5886 if (!Visit(E->getSubExpr()))
5887 return false;
5888
5889 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5890 QualType From
5891 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5892 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005893 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5894 To, Result.IntReal) &&
5895 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5896 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005897 }
5898
5899 case CK_IntegralRealToComplex: {
5900 APSInt &Real = Result.IntReal;
5901 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5902 return false;
5903
5904 Result.makeComplexInt();
5905 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5906 return true;
5907 }
5908
5909 case CK_IntegralComplexCast: {
5910 if (!Visit(E->getSubExpr()))
5911 return false;
5912
5913 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5914 QualType From
5915 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5916
Richard Smithf72fccf2012-01-30 22:27:01 +00005917 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5918 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005919 return true;
5920 }
5921
5922 case CK_IntegralComplexToFloatingComplex: {
5923 if (!Visit(E->getSubExpr()))
5924 return false;
5925
5926 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5927 QualType From
5928 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5929 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005930 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5931 To, Result.FloatReal) &&
5932 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5933 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005934 }
5935 }
5936
5937 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005938}
5939
John McCallf4cf1a12010-05-07 17:22:02 +00005940bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005941 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005942 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5943
Richard Smith745f5142012-01-27 01:14:48 +00005944 bool LHSOK = Visit(E->getLHS());
5945 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005946 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005947
John McCallf4cf1a12010-05-07 17:22:02 +00005948 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005949 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005950 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005951
Daniel Dunbar3f279872009-01-29 01:32:56 +00005952 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5953 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005954 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005955 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005956 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005957 if (Result.isComplexFloat()) {
5958 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5959 APFloat::rmNearestTiesToEven);
5960 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5961 APFloat::rmNearestTiesToEven);
5962 } else {
5963 Result.getComplexIntReal() += RHS.getComplexIntReal();
5964 Result.getComplexIntImag() += RHS.getComplexIntImag();
5965 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005966 break;
John McCall2de56d12010-08-25 11:45:40 +00005967 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005968 if (Result.isComplexFloat()) {
5969 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5970 APFloat::rmNearestTiesToEven);
5971 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5972 APFloat::rmNearestTiesToEven);
5973 } else {
5974 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5975 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5976 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005977 break;
John McCall2de56d12010-08-25 11:45:40 +00005978 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005979 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005980 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005981 APFloat &LHS_r = LHS.getComplexFloatReal();
5982 APFloat &LHS_i = LHS.getComplexFloatImag();
5983 APFloat &RHS_r = RHS.getComplexFloatReal();
5984 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005985
Daniel Dunbar3f279872009-01-29 01:32:56 +00005986 APFloat Tmp = LHS_r;
5987 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5988 Result.getComplexFloatReal() = Tmp;
5989 Tmp = LHS_i;
5990 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5991 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5992
5993 Tmp = LHS_r;
5994 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5995 Result.getComplexFloatImag() = Tmp;
5996 Tmp = LHS_i;
5997 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5998 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5999 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00006000 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00006001 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006002 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6003 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00006004 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006005 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6006 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6007 }
6008 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006009 case BO_Div:
6010 if (Result.isComplexFloat()) {
6011 ComplexValue LHS = Result;
6012 APFloat &LHS_r = LHS.getComplexFloatReal();
6013 APFloat &LHS_i = LHS.getComplexFloatImag();
6014 APFloat &RHS_r = RHS.getComplexFloatReal();
6015 APFloat &RHS_i = RHS.getComplexFloatImag();
6016 APFloat &Res_r = Result.getComplexFloatReal();
6017 APFloat &Res_i = Result.getComplexFloatImag();
6018
6019 APFloat Den = RHS_r;
6020 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6021 APFloat Tmp = RHS_i;
6022 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6023 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6024
6025 Res_r = LHS_r;
6026 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6027 Tmp = LHS_i;
6028 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6029 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6030 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6031
6032 Res_i = LHS_i;
6033 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6034 Tmp = LHS_r;
6035 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6036 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6037 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6038 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00006039 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6040 return Error(E, diag::note_expr_divide_by_zero);
6041
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006042 ComplexValue LHS = Result;
6043 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6044 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6045 Result.getComplexIntReal() =
6046 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6047 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6048 Result.getComplexIntImag() =
6049 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6050 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6051 }
6052 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006053 }
6054
John McCallf4cf1a12010-05-07 17:22:02 +00006055 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006056}
6057
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006058bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6059 // Get the operand value into 'Result'.
6060 if (!Visit(E->getSubExpr()))
6061 return false;
6062
6063 switch (E->getOpcode()) {
6064 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00006065 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006066 case UO_Extension:
6067 return true;
6068 case UO_Plus:
6069 // The result is always just the subexpr.
6070 return true;
6071 case UO_Minus:
6072 if (Result.isComplexFloat()) {
6073 Result.getComplexFloatReal().changeSign();
6074 Result.getComplexFloatImag().changeSign();
6075 }
6076 else {
6077 Result.getComplexIntReal() = -Result.getComplexIntReal();
6078 Result.getComplexIntImag() = -Result.getComplexIntImag();
6079 }
6080 return true;
6081 case UO_Not:
6082 if (Result.isComplexFloat())
6083 Result.getComplexFloatImag().changeSign();
6084 else
6085 Result.getComplexIntImag() = -Result.getComplexIntImag();
6086 return true;
6087 }
6088}
6089
Eli Friedman7ead5c72012-01-10 04:58:17 +00006090bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6091 if (E->getNumInits() == 2) {
6092 if (E->getType()->isComplexType()) {
6093 Result.makeComplexFloat();
6094 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6095 return false;
6096 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6097 return false;
6098 } else {
6099 Result.makeComplexInt();
6100 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6101 return false;
6102 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6103 return false;
6104 }
6105 return true;
6106 }
6107 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6108}
6109
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00006110//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00006111// Void expression evaluation, primarily for a cast to void on the LHS of a
6112// comma operator
6113//===----------------------------------------------------------------------===//
6114
6115namespace {
6116class VoidExprEvaluator
6117 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6118public:
6119 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6120
Richard Smith1aa0be82012-03-03 22:46:17 +00006121 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00006122
6123 bool VisitCastExpr(const CastExpr *E) {
6124 switch (E->getCastKind()) {
6125 default:
6126 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6127 case CK_ToVoid:
6128 VisitIgnoredValue(E->getSubExpr());
6129 return true;
6130 }
6131 }
6132};
6133} // end anonymous namespace
6134
6135static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6136 assert(E->isRValue() && E->getType()->isVoidType());
6137 return VoidExprEvaluator(Info).Visit(E);
6138}
6139
6140//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006141// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006142//===----------------------------------------------------------------------===//
6143
Richard Smith1aa0be82012-03-03 22:46:17 +00006144static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006145 // In C, function designators are not lvalues, but we evaluate them as if they
6146 // are.
6147 if (E->isGLValue() || E->getType()->isFunctionType()) {
6148 LValue LV;
6149 if (!EvaluateLValue(E, LV, Info))
6150 return false;
6151 LV.moveInto(Result);
6152 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006153 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006154 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006155 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006156 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006157 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006158 } else if (E->getType()->hasPointerRepresentation()) {
6159 LValue LV;
6160 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006161 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006162 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006163 } else if (E->getType()->isRealFloatingType()) {
6164 llvm::APFloat F(0.0);
6165 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006166 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006167 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006168 } else if (E->getType()->isAnyComplexType()) {
6169 ComplexValue C;
6170 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006171 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006172 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006173 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006174 MemberPtr P;
6175 if (!EvaluateMemberPointer(E, P, Info))
6176 return false;
6177 P.moveInto(Result);
6178 return true;
Richard Smith51201882011-12-30 21:15:51 +00006179 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006180 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006181 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006182 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006183 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006184 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006185 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006186 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006187 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006188 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6189 return false;
6190 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006191 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00006192 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006193 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00006194 << E->getType();
6195 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00006196 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00006197 if (!EvaluateVoid(E, Info))
6198 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006199 } else if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006200 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006201 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006202 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006203 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006204 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006205 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006206
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006207 return true;
6208}
6209
Richard Smith83587db2012-02-15 02:18:13 +00006210/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6211/// cases, the in-place evaluation is essential, since later initializers for
6212/// an object can indirectly refer to subobjects which were initialized earlier.
6213static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6214 const Expr *E, CheckConstantExpressionKind CCEK,
6215 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006216 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006217 return false;
6218
6219 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006220 // Evaluate arrays and record types in-place, so that later initializers can
6221 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006222 if (E->getType()->isArrayType())
6223 return EvaluateArray(E, This, Result, Info);
6224 else if (E->getType()->isRecordType())
6225 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006226 }
6227
6228 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006229 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006230}
6231
Richard Smithf48fdb02011-12-09 22:58:01 +00006232/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6233/// lvalue-to-rvalue cast if it is an lvalue.
6234static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006235 if (!CheckLiteralType(Info, E))
6236 return false;
6237
Richard Smith1aa0be82012-03-03 22:46:17 +00006238 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006239 return false;
6240
6241 if (E->isGLValue()) {
6242 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006243 LV.setFrom(Info.Ctx, Result);
6244 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006245 return false;
6246 }
6247
Richard Smith1aa0be82012-03-03 22:46:17 +00006248 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006249 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006250}
Richard Smithc49bd112011-10-28 17:51:58 +00006251
Richard Smith51f47082011-10-29 00:50:52 +00006252/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006253/// any crazy technique (that has nothing to do with language standards) that
6254/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006255/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6256/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006257bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006258 // Fast-path evaluations of integer literals, since we sometimes see files
6259 // containing vast quantities of these.
6260 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6261 Result.Val = APValue(APSInt(L->getValue(),
6262 L->getType()->isUnsignedIntegerType()));
6263 return true;
6264 }
6265
Richard Smith2d6a5672012-01-14 04:30:29 +00006266 // FIXME: Evaluating values of large array and record types can cause
6267 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006268 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006269 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006270 return false;
6271
Richard Smithf48fdb02011-12-09 22:58:01 +00006272 EvalInfo Info(Ctx, Result);
6273 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006274}
6275
Jay Foad4ba2a172011-01-12 09:06:06 +00006276bool Expr::EvaluateAsBooleanCondition(bool &Result,
6277 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006278 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006279 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006280 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006281}
6282
Richard Smith80d4b552011-12-28 19:48:30 +00006283bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6284 SideEffectsKind AllowSideEffects) const {
6285 if (!getType()->isIntegralOrEnumerationType())
6286 return false;
6287
Richard Smithc49bd112011-10-28 17:51:58 +00006288 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006289 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6290 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006291 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006292
Richard Smithc49bd112011-10-28 17:51:58 +00006293 Result = ExprResult.Val.getInt();
6294 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006295}
6296
Jay Foad4ba2a172011-01-12 09:06:06 +00006297bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006298 EvalInfo Info(Ctx, Result);
6299
John McCallefdb83e2010-05-07 21:00:08 +00006300 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006301 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6302 !CheckLValueConstantExpression(Info, getExprLoc(),
6303 Ctx.getLValueReferenceType(getType()), LV))
6304 return false;
6305
Richard Smith1aa0be82012-03-03 22:46:17 +00006306 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006307 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006308}
6309
Richard Smith099e7f62011-12-19 06:19:21 +00006310bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6311 const VarDecl *VD,
6312 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006313 // FIXME: Evaluating initializers for large array and record types can cause
6314 // performance problems. Only do so in C++11 for now.
6315 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006316 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith2d6a5672012-01-14 04:30:29 +00006317 return false;
6318
Richard Smith099e7f62011-12-19 06:19:21 +00006319 Expr::EvalStatus EStatus;
6320 EStatus.Diag = &Notes;
6321
6322 EvalInfo InitInfo(Ctx, EStatus);
6323 InitInfo.setEvaluatingDecl(VD, Value);
6324
6325 LValue LVal;
6326 LVal.set(VD);
6327
Richard Smith51201882011-12-30 21:15:51 +00006328 // C++11 [basic.start.init]p2:
6329 // Variables with static storage duration or thread storage duration shall be
6330 // zero-initialized before any other initialization takes place.
6331 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006332 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006333 !VD->getType()->isReferenceType()) {
6334 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006335 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6336 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006337 return false;
6338 }
6339
Richard Smith83587db2012-02-15 02:18:13 +00006340 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6341 /*AllowNonLiteralTypes=*/true) ||
6342 EStatus.HasSideEffects)
6343 return false;
6344
6345 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6346 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006347}
6348
Richard Smith51f47082011-10-29 00:50:52 +00006349/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6350/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006351bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006352 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006353 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006354}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006355
Jay Foad4ba2a172011-01-12 09:06:06 +00006356bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006357 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006358}
6359
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006360APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006361 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006362 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006363 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006364 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006365 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006366
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006367 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006368}
John McCalld905f5a2010-05-07 05:32:02 +00006369
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006370 bool Expr::EvalResult::isGlobalLValue() const {
6371 assert(Val.isLValue());
6372 return IsGlobalLValue(Val.getLValueBase());
6373 }
6374
6375
John McCalld905f5a2010-05-07 05:32:02 +00006376/// isIntegerConstantExpr - this recursive routine will test if an expression is
6377/// an integer constant expression.
6378
6379/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6380/// comma, etc
6381///
6382/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6383/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6384/// cast+dereference.
6385
6386// CheckICE - This function does the fundamental ICE checking: the returned
6387// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6388// Note that to reduce code duplication, this helper does no evaluation
6389// itself; the caller checks whether the expression is evaluatable, and
6390// in the rare cases where CheckICE actually cares about the evaluated
6391// value, it calls into Evalute.
6392//
6393// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006394// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006395// 1: This expression is not an ICE, but if it isn't evaluated, it's
6396// a legal subexpression for an ICE. This return value is used to handle
6397// the comma operator in C99 mode.
6398// 2: This expression is not an ICE, and is not a legal subexpression for one.
6399
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006400namespace {
6401
John McCalld905f5a2010-05-07 05:32:02 +00006402struct ICEDiag {
6403 unsigned Val;
6404 SourceLocation Loc;
6405
6406 public:
6407 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6408 ICEDiag() : Val(0) {}
6409};
6410
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006411}
6412
6413static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006414
6415static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6416 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006417 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006418 !EVResult.Val.isInt()) {
6419 return ICEDiag(2, E->getLocStart());
6420 }
6421 return NoDiag();
6422}
6423
6424static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6425 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006426 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006427 return ICEDiag(2, E->getLocStart());
6428 }
6429
6430 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006431#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006432#define STMT(Node, Base) case Expr::Node##Class:
6433#define EXPR(Node, Base)
6434#include "clang/AST/StmtNodes.inc"
6435 case Expr::PredefinedExprClass:
6436 case Expr::FloatingLiteralClass:
6437 case Expr::ImaginaryLiteralClass:
6438 case Expr::StringLiteralClass:
6439 case Expr::ArraySubscriptExprClass:
6440 case Expr::MemberExprClass:
6441 case Expr::CompoundAssignOperatorClass:
6442 case Expr::CompoundLiteralExprClass:
6443 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006444 case Expr::DesignatedInitExprClass:
6445 case Expr::ImplicitValueInitExprClass:
6446 case Expr::ParenListExprClass:
6447 case Expr::VAArgExprClass:
6448 case Expr::AddrLabelExprClass:
6449 case Expr::StmtExprClass:
6450 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006451 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006452 case Expr::CXXDynamicCastExprClass:
6453 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006454 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006455 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006456 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006457 case Expr::CXXThisExprClass:
6458 case Expr::CXXThrowExprClass:
6459 case Expr::CXXNewExprClass:
6460 case Expr::CXXDeleteExprClass:
6461 case Expr::CXXPseudoDestructorExprClass:
6462 case Expr::UnresolvedLookupExprClass:
6463 case Expr::DependentScopeDeclRefExprClass:
6464 case Expr::CXXConstructExprClass:
6465 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006466 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006467 case Expr::CXXTemporaryObjectExprClass:
6468 case Expr::CXXUnresolvedConstructExprClass:
6469 case Expr::CXXDependentScopeMemberExprClass:
6470 case Expr::UnresolvedMemberExprClass:
6471 case Expr::ObjCStringLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006472 case Expr::ObjCNumericLiteralClass:
6473 case Expr::ObjCArrayLiteralClass:
6474 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006475 case Expr::ObjCEncodeExprClass:
6476 case Expr::ObjCMessageExprClass:
6477 case Expr::ObjCSelectorExprClass:
6478 case Expr::ObjCProtocolExprClass:
6479 case Expr::ObjCIvarRefExprClass:
6480 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006481 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006482 case Expr::ObjCIsaExprClass:
6483 case Expr::ShuffleVectorExprClass:
6484 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006485 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006486 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006487 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006488 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006489 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006490 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006491 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006492 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006493 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006494 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006495 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006496 return ICEDiag(2, E->getLocStart());
6497
Douglas Gregoree8aff02011-01-04 17:33:58 +00006498 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006499 case Expr::GNUNullExprClass:
6500 // GCC considers the GNU __null value to be an integral constant expression.
6501 return NoDiag();
6502
John McCall91a57552011-07-15 05:09:51 +00006503 case Expr::SubstNonTypeTemplateParmExprClass:
6504 return
6505 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6506
John McCalld905f5a2010-05-07 05:32:02 +00006507 case Expr::ParenExprClass:
6508 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006509 case Expr::GenericSelectionExprClass:
6510 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006511 case Expr::IntegerLiteralClass:
6512 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006513 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006514 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006515 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006516 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006517 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006518 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006519 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006520 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006521 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006522 return NoDiag();
6523 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006524 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006525 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6526 // constant expressions, but they can never be ICEs because an ICE cannot
6527 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006528 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006529 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006530 return CheckEvalInICE(E, Ctx);
6531 return ICEDiag(2, E->getLocStart());
6532 }
Richard Smith359c89d2012-02-24 22:12:32 +00006533 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006534 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6535 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006536 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006537 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006538 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006539 // Parameter variables are never constants. Without this check,
6540 // getAnyInitializer() can find a default argument, which leads
6541 // to chaos.
6542 if (isa<ParmVarDecl>(D))
6543 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6544
6545 // C++ 7.1.5.1p2
6546 // A variable of non-volatile const-qualified integral or enumeration
6547 // type initialized by an ICE can be used in ICEs.
6548 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006549 if (!Dcl->getType()->isIntegralOrEnumerationType())
6550 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6551
Richard Smith099e7f62011-12-19 06:19:21 +00006552 const VarDecl *VD;
6553 // Look for a declaration of this variable that has an initializer, and
6554 // check whether it is an ICE.
6555 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6556 return NoDiag();
6557 else
6558 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006559 }
6560 }
6561 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006562 }
John McCalld905f5a2010-05-07 05:32:02 +00006563 case Expr::UnaryOperatorClass: {
6564 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6565 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006566 case UO_PostInc:
6567 case UO_PostDec:
6568 case UO_PreInc:
6569 case UO_PreDec:
6570 case UO_AddrOf:
6571 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006572 // C99 6.6/3 allows increment and decrement within unevaluated
6573 // subexpressions of constant expressions, but they can never be ICEs
6574 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006575 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006576 case UO_Extension:
6577 case UO_LNot:
6578 case UO_Plus:
6579 case UO_Minus:
6580 case UO_Not:
6581 case UO_Real:
6582 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006583 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006584 }
6585
6586 // OffsetOf falls through here.
6587 }
6588 case Expr::OffsetOfExprClass: {
6589 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006590 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006591 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006592 // compliance: we should warn earlier for offsetof expressions with
6593 // array subscripts that aren't ICEs, and if the array subscripts
6594 // are ICEs, the value of the offsetof must be an integer constant.
6595 return CheckEvalInICE(E, Ctx);
6596 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006597 case Expr::UnaryExprOrTypeTraitExprClass: {
6598 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6599 if ((Exp->getKind() == UETT_SizeOf) &&
6600 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006601 return ICEDiag(2, E->getLocStart());
6602 return NoDiag();
6603 }
6604 case Expr::BinaryOperatorClass: {
6605 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6606 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006607 case BO_PtrMemD:
6608 case BO_PtrMemI:
6609 case BO_Assign:
6610 case BO_MulAssign:
6611 case BO_DivAssign:
6612 case BO_RemAssign:
6613 case BO_AddAssign:
6614 case BO_SubAssign:
6615 case BO_ShlAssign:
6616 case BO_ShrAssign:
6617 case BO_AndAssign:
6618 case BO_XorAssign:
6619 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006620 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6621 // constant expressions, but they can never be ICEs because an ICE cannot
6622 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006623 return ICEDiag(2, E->getLocStart());
6624
John McCall2de56d12010-08-25 11:45:40 +00006625 case BO_Mul:
6626 case BO_Div:
6627 case BO_Rem:
6628 case BO_Add:
6629 case BO_Sub:
6630 case BO_Shl:
6631 case BO_Shr:
6632 case BO_LT:
6633 case BO_GT:
6634 case BO_LE:
6635 case BO_GE:
6636 case BO_EQ:
6637 case BO_NE:
6638 case BO_And:
6639 case BO_Xor:
6640 case BO_Or:
6641 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006642 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6643 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006644 if (Exp->getOpcode() == BO_Div ||
6645 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006646 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006647 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006648 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006649 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006650 if (REval == 0)
6651 return ICEDiag(1, E->getLocStart());
6652 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006653 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006654 if (LEval.isMinSignedValue())
6655 return ICEDiag(1, E->getLocStart());
6656 }
6657 }
6658 }
John McCall2de56d12010-08-25 11:45:40 +00006659 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006660 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006661 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6662 // if it isn't evaluated.
6663 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6664 return ICEDiag(1, E->getLocStart());
6665 } else {
6666 // In both C89 and C++, commas in ICEs are illegal.
6667 return ICEDiag(2, E->getLocStart());
6668 }
6669 }
6670 if (LHSResult.Val >= RHSResult.Val)
6671 return LHSResult;
6672 return RHSResult;
6673 }
John McCall2de56d12010-08-25 11:45:40 +00006674 case BO_LAnd:
6675 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006676 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6677 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6678 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6679 // Rare case where the RHS has a comma "side-effect"; we need
6680 // to actually check the condition to see whether the side
6681 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006682 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006683 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006684 return RHSResult;
6685 return NoDiag();
6686 }
6687
6688 if (LHSResult.Val >= RHSResult.Val)
6689 return LHSResult;
6690 return RHSResult;
6691 }
6692 }
6693 }
6694 case Expr::ImplicitCastExprClass:
6695 case Expr::CStyleCastExprClass:
6696 case Expr::CXXFunctionalCastExprClass:
6697 case Expr::CXXStaticCastExprClass:
6698 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006699 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006700 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006701 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006702 if (isa<ExplicitCastExpr>(E)) {
6703 if (const FloatingLiteral *FL
6704 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6705 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6706 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6707 APSInt IgnoredVal(DestWidth, !DestSigned);
6708 bool Ignored;
6709 // If the value does not fit in the destination type, the behavior is
6710 // undefined, so we are not required to treat it as a constant
6711 // expression.
6712 if (FL->getValue().convertToInteger(IgnoredVal,
6713 llvm::APFloat::rmTowardZero,
6714 &Ignored) & APFloat::opInvalidOp)
6715 return ICEDiag(2, E->getLocStart());
6716 return NoDiag();
6717 }
6718 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006719 switch (cast<CastExpr>(E)->getCastKind()) {
6720 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006721 case CK_AtomicToNonAtomic:
6722 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006723 case CK_NoOp:
6724 case CK_IntegralToBoolean:
6725 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006726 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006727 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006728 return ICEDiag(2, E->getLocStart());
6729 }
John McCalld905f5a2010-05-07 05:32:02 +00006730 }
John McCall56ca35d2011-02-17 10:25:35 +00006731 case Expr::BinaryConditionalOperatorClass: {
6732 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6733 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6734 if (CommonResult.Val == 2) return CommonResult;
6735 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6736 if (FalseResult.Val == 2) return FalseResult;
6737 if (CommonResult.Val == 1) return CommonResult;
6738 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006739 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006740 return FalseResult;
6741 }
John McCalld905f5a2010-05-07 05:32:02 +00006742 case Expr::ConditionalOperatorClass: {
6743 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6744 // If the condition (ignoring parens) is a __builtin_constant_p call,
6745 // then only the true side is actually considered in an integer constant
6746 // expression, and it is fully evaluated. This is an important GNU
6747 // extension. See GCC PR38377 for discussion.
6748 if (const CallExpr *CallCE
6749 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006750 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6751 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006752 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006753 if (CondResult.Val == 2)
6754 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006755
Richard Smithf48fdb02011-12-09 22:58:01 +00006756 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6757 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006758
John McCalld905f5a2010-05-07 05:32:02 +00006759 if (TrueResult.Val == 2)
6760 return TrueResult;
6761 if (FalseResult.Val == 2)
6762 return FalseResult;
6763 if (CondResult.Val == 1)
6764 return CondResult;
6765 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6766 return NoDiag();
6767 // Rare case where the diagnostics depend on which side is evaluated
6768 // Note that if we get here, CondResult is 0, and at least one of
6769 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006770 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006771 return FalseResult;
6772 }
6773 return TrueResult;
6774 }
6775 case Expr::CXXDefaultArgExprClass:
6776 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6777 case Expr::ChooseExprClass: {
6778 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6779 }
6780 }
6781
David Blaikie30263482012-01-20 21:50:17 +00006782 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006783}
6784
Richard Smithf48fdb02011-12-09 22:58:01 +00006785/// Evaluate an expression as a C++11 integral constant expression.
6786static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6787 const Expr *E,
6788 llvm::APSInt *Value,
6789 SourceLocation *Loc) {
6790 if (!E->getType()->isIntegralOrEnumerationType()) {
6791 if (Loc) *Loc = E->getExprLoc();
6792 return false;
6793 }
6794
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006795 APValue Result;
6796 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006797 return false;
6798
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006799 assert(Result.isInt() && "pointer cast to int is not an ICE");
6800 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006801 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006802}
6803
Richard Smithdd1f29b2011-12-12 09:28:41 +00006804bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006805 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006806 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6807
John McCalld905f5a2010-05-07 05:32:02 +00006808 ICEDiag d = CheckICE(this, Ctx);
6809 if (d.Val != 0) {
6810 if (Loc) *Loc = d.Loc;
6811 return false;
6812 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006813 return true;
6814}
6815
6816bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6817 SourceLocation *Loc, bool isEvaluated) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006818 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006819 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6820
6821 if (!isIntegerConstantExpr(Ctx, Loc))
6822 return false;
6823 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006824 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006825 return true;
6826}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006827
Richard Smith70488e22012-02-14 21:38:30 +00006828bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6829 return CheckICE(this, Ctx).Val == 0;
6830}
6831
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006832bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6833 SourceLocation *Loc) const {
6834 // We support this checking in C++98 mode in order to diagnose compatibility
6835 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006836 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006837
Richard Smith70488e22012-02-14 21:38:30 +00006838 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006839 Expr::EvalStatus Status;
6840 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6841 Status.Diag = &Diags;
6842 EvalInfo Info(Ctx, Status);
6843
6844 APValue Scratch;
6845 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6846
6847 if (!Diags.empty()) {
6848 IsConstExpr = false;
6849 if (Loc) *Loc = Diags[0].first;
6850 } else if (!IsConstExpr) {
6851 // FIXME: This shouldn't happen.
6852 if (Loc) *Loc = getExprLoc();
6853 }
6854
6855 return IsConstExpr;
6856}
Richard Smith745f5142012-01-27 01:14:48 +00006857
6858bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6859 llvm::SmallVectorImpl<
6860 PartialDiagnosticAt> &Diags) {
6861 // FIXME: It would be useful to check constexpr function templates, but at the
6862 // moment the constant expression evaluator cannot cope with the non-rigorous
6863 // ASTs which we build for dependent expressions.
6864 if (FD->isDependentContext())
6865 return true;
6866
6867 Expr::EvalStatus Status;
6868 Status.Diag = &Diags;
6869
6870 EvalInfo Info(FD->getASTContext(), Status);
6871 Info.CheckingPotentialConstantExpression = true;
6872
6873 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6874 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6875
6876 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6877 // is a temporary being used as the 'this' pointer.
6878 LValue This;
6879 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006880 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006881
Richard Smith745f5142012-01-27 01:14:48 +00006882 ArrayRef<const Expr*> Args;
6883
6884 SourceLocation Loc = FD->getLocation();
6885
Richard Smith1aa0be82012-03-03 22:46:17 +00006886 APValue Scratch;
6887 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006888 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006889 else
Richard Smith745f5142012-01-27 01:14:48 +00006890 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6891 Args, FD->getBody(), Info, Scratch);
6892
6893 return Diags.empty();
6894}