blob: 0d8490e137de9fe51284726b010d22c82a126c1e [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);
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001746 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
Richard Smithf15fda02012-02-02 01:16:57 +00001747 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001748 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001749 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001750 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001751 }
1752
Richard Smith7098cbd2011-12-21 05:04:46 +00001753 // DR1313: If the object is volatile-qualified but the glvalue was not,
1754 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001755 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001756 if (VT.isVolatileQualified()) {
1757 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001758 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001759 Info.Note(VD->getLocation(), diag::note_declared_at);
1760 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001761 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001762 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001763 return false;
1764 }
1765
1766 if (!isa<ParmVarDecl>(VD)) {
1767 if (VD->isConstexpr()) {
1768 // OK, we can read this variable.
1769 } else if (VT->isIntegralOrEnumerationType()) {
1770 if (!VT.isConstQualified()) {
1771 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001772 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001773 Info.Note(VD->getLocation(), diag::note_declared_at);
1774 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001775 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001776 }
1777 return false;
1778 }
1779 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1780 // We support folding of const floating-point types, in order to make
1781 // static const data members of such types (supported as an extension)
1782 // more useful.
1783 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001784 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001785 Info.Note(VD->getLocation(), diag::note_declared_at);
1786 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001787 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001788 }
1789 } else {
1790 // FIXME: Allow folding of values of any literal type in all languages.
1791 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001792 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001793 Info.Note(VD->getLocation(), diag::note_declared_at);
1794 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001795 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001796 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001797 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001798 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001799 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001800
Richard Smithf48fdb02011-12-09 22:58:01 +00001801 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001802 return false;
1803
Richard Smith47a1eed2011-10-29 20:57:55 +00001804 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001805 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001806
1807 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1808 // conversion. This happens when the declaration and the lvalue should be
1809 // considered synonymous, for instance when initializing an array of char
1810 // from a string literal. Continue as if the initializer lvalue was the
1811 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001812 assert(RVal.getLValueOffset().isZero() &&
1813 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001814 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001815
1816 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1817 Frame = Info.getCallFrame(CallIndex);
1818 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001819 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001820 NoteLValueLocation(Info, RVal.getLValueBase());
1821 return false;
1822 }
1823 } else {
1824 Frame = 0;
1825 }
Richard Smithc49bd112011-10-28 17:51:58 +00001826 }
1827
Richard Smith7098cbd2011-12-21 05:04:46 +00001828 // Volatile temporary objects cannot be read in constant expressions.
1829 if (Base->getType().isVolatileQualified()) {
1830 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001831 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001832 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1833 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001834 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001835 }
1836 return false;
1837 }
1838
Richard Smithcc5d4f62011-11-07 09:22:26 +00001839 if (Frame) {
1840 // If this is a temporary expression with a nontrivial initializer, grab the
1841 // value from the relevant stack frame.
1842 RVal = Frame->Temporaries[Base];
1843 } else if (const CompoundLiteralExpr *CLE
1844 = dyn_cast<CompoundLiteralExpr>(Base)) {
1845 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1846 // initializer until now for such expressions. Such an expression can't be
1847 // an ICE in C, so this only matters for fold.
1848 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1849 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1850 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001851 } else if (isa<StringLiteral>(Base)) {
1852 // We represent a string literal array as an lvalue pointing at the
1853 // corresponding expression, rather than building an array of chars.
1854 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001855 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001856 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001857 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001858 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001859 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001860
Richard Smithf48fdb02011-12-09 22:58:01 +00001861 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1862 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001863}
1864
Richard Smith59efe262011-11-11 04:05:33 +00001865/// Build an lvalue for the object argument of a member function call.
1866static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1867 LValue &This) {
1868 if (Object->getType()->isPointerType())
1869 return EvaluatePointer(Object, This, Info);
1870
1871 if (Object->isGLValue())
1872 return EvaluateLValue(Object, This, Info);
1873
Richard Smithe24f5fc2011-11-17 22:56:20 +00001874 if (Object->getType()->isLiteralType())
1875 return EvaluateTemporary(Object, This, Info);
1876
1877 return false;
1878}
1879
1880/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1881/// lvalue referring to the result.
1882///
1883/// \param Info - Information about the ongoing evaluation.
1884/// \param BO - The member pointer access operation.
1885/// \param LV - Filled in with a reference to the resulting object.
1886/// \param IncludeMember - Specifies whether the member itself is included in
1887/// the resulting LValue subobject designator. This is not possible when
1888/// creating a bound member function.
1889/// \return The field or method declaration to which the member pointer refers,
1890/// or 0 if evaluation fails.
1891static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1892 const BinaryOperator *BO,
1893 LValue &LV,
1894 bool IncludeMember = true) {
1895 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1896
Richard Smith745f5142012-01-27 01:14:48 +00001897 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1898 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001899 return 0;
1900
1901 MemberPtr MemPtr;
1902 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1903 return 0;
1904
1905 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1906 // member value, the behavior is undefined.
1907 if (!MemPtr.getDecl())
1908 return 0;
1909
Richard Smith745f5142012-01-27 01:14:48 +00001910 if (!EvalObjOK)
1911 return 0;
1912
Richard Smithe24f5fc2011-11-17 22:56:20 +00001913 if (MemPtr.isDerivedMember()) {
1914 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001915 // The end of the derived-to-base path for the base object must match the
1916 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001917 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001918 LV.Designator.Entries.size())
1919 return 0;
1920 unsigned PathLengthToMember =
1921 LV.Designator.Entries.size() - MemPtr.Path.size();
1922 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1923 const CXXRecordDecl *LVDecl = getAsBaseClass(
1924 LV.Designator.Entries[PathLengthToMember + I]);
1925 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1926 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1927 return 0;
1928 }
1929
1930 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001931 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1932 PathLengthToMember))
1933 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001934 } else if (!MemPtr.Path.empty()) {
1935 // Extend the LValue path with the member pointer's path.
1936 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1937 MemPtr.Path.size() + IncludeMember);
1938
1939 // Walk down to the appropriate base class.
1940 QualType LVType = BO->getLHS()->getType();
1941 if (const PointerType *PT = LVType->getAs<PointerType>())
1942 LVType = PT->getPointeeType();
1943 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1944 assert(RD && "member pointer access on non-class-type expression");
1945 // The first class in the path is that of the lvalue.
1946 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1947 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001948 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001949 RD = Base;
1950 }
1951 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001952 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001953 }
1954
1955 // Add the member. Note that we cannot build bound member functions here.
1956 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001957 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1958 HandleLValueMember(Info, BO, LV, FD);
1959 else if (const IndirectFieldDecl *IFD =
1960 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1961 HandleLValueIndirectMember(Info, BO, LV, IFD);
1962 else
1963 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001964 }
1965
1966 return MemPtr.getDecl();
1967}
1968
1969/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1970/// the provided lvalue, which currently refers to the base object.
1971static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1972 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001973 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001974 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001975 return false;
1976
Richard Smithb4e85ed2012-01-06 16:39:00 +00001977 QualType TargetQT = E->getType();
1978 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1979 TargetQT = PT->getPointeeType();
1980
1981 // Check this cast lands within the final derived-to-base subobject path.
1982 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001983 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00001984 << D.MostDerivedType << TargetQT;
1985 return false;
1986 }
1987
Richard Smithe24f5fc2011-11-17 22:56:20 +00001988 // Check the type of the final cast. We don't need to check the path,
1989 // since a cast can only be formed if the path is unique.
1990 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001991 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1992 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001993 if (NewEntriesSize == D.MostDerivedPathLength)
1994 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1995 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001996 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001997 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001998 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00001999 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002000 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002001 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002002
2003 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002004 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002005}
2006
Mike Stumpc4c90452009-10-27 22:09:17 +00002007namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002008enum EvalStmtResult {
2009 /// Evaluation failed.
2010 ESR_Failed,
2011 /// Hit a 'return' statement.
2012 ESR_Returned,
2013 /// Evaluation succeeded.
2014 ESR_Succeeded
2015};
2016}
2017
2018// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002019static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002020 const Stmt *S) {
2021 switch (S->getStmtClass()) {
2022 default:
2023 return ESR_Failed;
2024
2025 case Stmt::NullStmtClass:
2026 case Stmt::DeclStmtClass:
2027 return ESR_Succeeded;
2028
Richard Smithc1c5f272011-12-13 06:39:58 +00002029 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002030 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002031 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002032 return ESR_Failed;
2033 return ESR_Returned;
2034 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002035
2036 case Stmt::CompoundStmtClass: {
2037 const CompoundStmt *CS = cast<CompoundStmt>(S);
2038 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2039 BE = CS->body_end(); BI != BE; ++BI) {
2040 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2041 if (ESR != ESR_Succeeded)
2042 return ESR;
2043 }
2044 return ESR_Succeeded;
2045 }
2046 }
2047}
2048
Richard Smith61802452011-12-22 02:22:31 +00002049/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2050/// default constructor. If so, we'll fold it whether or not it's marked as
2051/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2052/// so we need special handling.
2053static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002054 const CXXConstructorDecl *CD,
2055 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002056 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2057 return false;
2058
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002059 // Value-initialization does not call a trivial default constructor, so such a
2060 // call is a core constant expression whether or not the constructor is
2061 // constexpr.
2062 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002063 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002064 // FIXME: If DiagDecl is an implicitly-declared special member function,
2065 // we should be much more explicit about why it's not constexpr.
2066 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2067 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2068 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002069 } else {
2070 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2071 }
2072 }
2073 return true;
2074}
2075
Richard Smithc1c5f272011-12-13 06:39:58 +00002076/// CheckConstexprFunction - Check that a function can be called in a constant
2077/// expression.
2078static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2079 const FunctionDecl *Declaration,
2080 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002081 // Potential constant expressions can contain calls to declared, but not yet
2082 // defined, constexpr functions.
2083 if (Info.CheckingPotentialConstantExpression && !Definition &&
2084 Declaration->isConstexpr())
2085 return false;
2086
Richard Smithc1c5f272011-12-13 06:39:58 +00002087 // Can we evaluate this function call?
2088 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2089 return true;
2090
2091 if (Info.getLangOpts().CPlusPlus0x) {
2092 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002093 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2094 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002095 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2096 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2097 << DiagDecl;
2098 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2099 } else {
2100 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2101 }
2102 return false;
2103}
2104
Richard Smith180f4792011-11-10 06:34:14 +00002105namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002106typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002107}
2108
2109/// EvaluateArgs - Evaluate the arguments to a function call.
2110static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2111 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002112 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002113 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002114 I != E; ++I) {
2115 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2116 // If we're checking for a potential constant expression, evaluate all
2117 // initializers even if some of them fail.
2118 if (!Info.keepEvaluatingAfterFailure())
2119 return false;
2120 Success = false;
2121 }
2122 }
2123 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002124}
2125
Richard Smithd0dccea2011-10-28 22:34:42 +00002126/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002127static bool HandleFunctionCall(SourceLocation CallLoc,
2128 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002129 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002130 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002131 ArgVector ArgValues(Args.size());
2132 if (!EvaluateArgs(Args, ArgValues, Info))
2133 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002134
Richard Smith745f5142012-01-27 01:14:48 +00002135 if (!Info.CheckCallLimit(CallLoc))
2136 return false;
2137
2138 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002139 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2140}
2141
Richard Smith180f4792011-11-10 06:34:14 +00002142/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002143static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002144 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002145 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002146 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002147 ArgVector ArgValues(Args.size());
2148 if (!EvaluateArgs(Args, ArgValues, Info))
2149 return false;
2150
Richard Smith745f5142012-01-27 01:14:48 +00002151 if (!Info.CheckCallLimit(CallLoc))
2152 return false;
2153
Richard Smith86c3ae42012-02-13 03:54:03 +00002154 const CXXRecordDecl *RD = Definition->getParent();
2155 if (RD->getNumVBases()) {
2156 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2157 return false;
2158 }
2159
Richard Smith745f5142012-01-27 01:14:48 +00002160 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002161
2162 // If it's a delegating constructor, just delegate.
2163 if (Definition->isDelegatingConstructor()) {
2164 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002165 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002166 }
2167
Richard Smith610a60c2012-01-10 04:32:03 +00002168 // For a trivial copy or move constructor, perform an APValue copy. This is
2169 // essential for unions, where the operations performed by the constructor
2170 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002171 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002172 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2173 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002174 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002175 RHS.setFrom(Info.Ctx, ArgValues[0]);
2176 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2177 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002178 }
2179
2180 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002181 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002182 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2183 std::distance(RD->field_begin(), RD->field_end()));
2184
2185 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2186
Richard Smith745f5142012-01-27 01:14:48 +00002187 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002188 unsigned BasesSeen = 0;
2189#ifndef NDEBUG
2190 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2191#endif
2192 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2193 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002194 LValue Subobject = This;
2195 APValue *Value = &Result;
2196
2197 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002198 if ((*I)->isBaseInitializer()) {
2199 QualType BaseType((*I)->getBaseClass(), 0);
2200#ifndef NDEBUG
2201 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002202 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002203 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2204 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2205 "base class initializers not in expected order");
2206 ++BaseIt;
2207#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002208 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002209 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002210 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002211 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002212 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002213 if (RD->isUnion()) {
2214 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002215 Value = &Result.getUnionValue();
2216 } else {
2217 Value = &Result.getStructField(FD->getFieldIndex());
2218 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002219 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002220 // Walk the indirect field decl's chain to find the object to initialize,
2221 // and make sure we've initialized every step along it.
2222 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2223 CE = IFD->chain_end();
2224 C != CE; ++C) {
2225 FieldDecl *FD = cast<FieldDecl>(*C);
2226 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2227 // Switch the union field if it differs. This happens if we had
2228 // preceding zero-initialization, and we're now initializing a union
2229 // subobject other than the first.
2230 // FIXME: In this case, the values of the other subobjects are
2231 // specified, since zero-initialization sets all padding bits to zero.
2232 if (Value->isUninit() ||
2233 (Value->isUnion() && Value->getUnionField() != FD)) {
2234 if (CD->isUnion())
2235 *Value = APValue(FD);
2236 else
2237 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2238 std::distance(CD->field_begin(), CD->field_end()));
2239 }
Richard Smith745f5142012-01-27 01:14:48 +00002240 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002241 if (CD->isUnion())
2242 Value = &Value->getUnionValue();
2243 else
2244 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002245 }
Richard Smith180f4792011-11-10 06:34:14 +00002246 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002247 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002248 }
Richard Smith745f5142012-01-27 01:14:48 +00002249
Richard Smith83587db2012-02-15 02:18:13 +00002250 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2251 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002252 ? CCEK_Constant : CCEK_MemberInit)) {
2253 // If we're checking for a potential constant expression, evaluate all
2254 // initializers even if some of them fail.
2255 if (!Info.keepEvaluatingAfterFailure())
2256 return false;
2257 Success = false;
2258 }
Richard Smith180f4792011-11-10 06:34:14 +00002259 }
2260
Richard Smith745f5142012-01-27 01:14:48 +00002261 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002262}
2263
Richard Smithd0dccea2011-10-28 22:34:42 +00002264namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002265class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002266 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002267 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002268public:
2269
Richard Smith1e12c592011-10-16 21:26:27 +00002270 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002271
2272 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002273 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002274 return true;
2275 }
2276
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002277 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2278 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002279 return Visit(E->getResultExpr());
2280 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002281 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002282 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002283 return true;
2284 return false;
2285 }
John McCallf85e1932011-06-15 23:02:42 +00002286 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002287 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002288 return true;
2289 return false;
2290 }
John McCallf85e1932011-06-15 23:02:42 +00002291
Mike Stumpc4c90452009-10-27 22:09:17 +00002292 // We don't want to evaluate BlockExprs multiple times, as they generate
2293 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002294 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2295 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2296 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002297 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002298 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2299 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2300 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2301 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2302 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2303 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002304 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002305 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002306 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002307 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002308 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002309 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2310 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2311 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2312 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002313 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002314 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2315 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2316 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2317 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2318 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002319 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002320 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002321 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002322 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002323 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002324
2325 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002326 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002327 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2328 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002329 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002330 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002331 return false;
2332 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002333
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002334 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002335};
2336
John McCall56ca35d2011-02-17 10:25:35 +00002337class OpaqueValueEvaluation {
2338 EvalInfo &info;
2339 OpaqueValueExpr *opaqueValue;
2340
2341public:
2342 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2343 Expr *value)
2344 : info(info), opaqueValue(opaqueValue) {
2345
2346 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002347 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002348 this->opaqueValue = 0;
2349 return;
2350 }
John McCall56ca35d2011-02-17 10:25:35 +00002351 }
2352
2353 bool hasError() const { return opaqueValue == 0; }
2354
2355 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002356 // FIXME: For a recursive constexpr call, an outer stack frame might have
2357 // been using this opaque value too, and will now have to re-evaluate the
2358 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002359 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2360 }
2361};
2362
Mike Stumpc4c90452009-10-27 22:09:17 +00002363} // end anonymous namespace
2364
Eli Friedman4efaa272008-11-12 09:44:48 +00002365//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002366// Generic Evaluation
2367//===----------------------------------------------------------------------===//
2368namespace {
2369
Richard Smithf48fdb02011-12-09 22:58:01 +00002370// FIXME: RetTy is always bool. Remove it.
2371template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002372class ExprEvaluatorBase
2373 : public ConstStmtVisitor<Derived, RetTy> {
2374private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002375 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002376 return static_cast<Derived*>(this)->Success(V, E);
2377 }
Richard Smith51201882011-12-30 21:15:51 +00002378 RetTy DerivedZeroInitialization(const Expr *E) {
2379 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002380 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002381
Richard Smith74e1ad92012-02-16 02:46:34 +00002382 // Check whether a conditional operator with a non-constant condition is a
2383 // potential constant expression. If neither arm is a potential constant
2384 // expression, then the conditional operator is not either.
2385 template<typename ConditionalOperator>
2386 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2387 assert(Info.CheckingPotentialConstantExpression);
2388
2389 // Speculatively evaluate both arms.
2390 {
2391 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2392 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2393
2394 StmtVisitorTy::Visit(E->getFalseExpr());
2395 if (Diag.empty())
2396 return;
2397
2398 Diag.clear();
2399 StmtVisitorTy::Visit(E->getTrueExpr());
2400 if (Diag.empty())
2401 return;
2402 }
2403
2404 Error(E, diag::note_constexpr_conditional_never_const);
2405 }
2406
2407
2408 template<typename ConditionalOperator>
2409 bool HandleConditionalOperator(const ConditionalOperator *E) {
2410 bool BoolResult;
2411 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2412 if (Info.CheckingPotentialConstantExpression)
2413 CheckPotentialConstantConditional(E);
2414 return false;
2415 }
2416
2417 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2418 return StmtVisitorTy::Visit(EvalExpr);
2419 }
2420
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002421protected:
2422 EvalInfo &Info;
2423 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2424 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2425
Richard Smithdd1f29b2011-12-12 09:28:41 +00002426 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002427 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002428 }
2429
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00002430 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2431
2432public:
2433 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2434
2435 EvalInfo &getEvalInfo() { return Info; }
2436
Richard Smithf48fdb02011-12-09 22:58:01 +00002437 /// Report an evaluation error. This should only be called when an error is
2438 /// first discovered. When propagating an error, just return false.
2439 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002440 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002441 return false;
2442 }
2443 bool Error(const Expr *E) {
2444 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2445 }
2446
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002447 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002448 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002449 }
2450 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002451 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002452 }
2453
2454 RetTy VisitParenExpr(const ParenExpr *E)
2455 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2456 RetTy VisitUnaryExtension(const UnaryOperator *E)
2457 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2458 RetTy VisitUnaryPlus(const UnaryOperator *E)
2459 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2460 RetTy VisitChooseExpr(const ChooseExpr *E)
2461 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2462 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2463 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002464 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2465 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002466 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2467 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002468 // We cannot create any objects for which cleanups are required, so there is
2469 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2470 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2471 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002472
Richard Smithc216a012011-12-12 12:46:16 +00002473 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2474 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2475 return static_cast<Derived*>(this)->VisitCastExpr(E);
2476 }
2477 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2478 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2479 return static_cast<Derived*>(this)->VisitCastExpr(E);
2480 }
2481
Richard Smithe24f5fc2011-11-17 22:56:20 +00002482 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2483 switch (E->getOpcode()) {
2484 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002485 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002486
2487 case BO_Comma:
2488 VisitIgnoredValue(E->getLHS());
2489 return StmtVisitorTy::Visit(E->getRHS());
2490
2491 case BO_PtrMemD:
2492 case BO_PtrMemI: {
2493 LValue Obj;
2494 if (!HandleMemberPointerAccess(Info, E, Obj))
2495 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002496 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002497 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002498 return false;
2499 return DerivedSuccess(Result, E);
2500 }
2501 }
2502 }
2503
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002504 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002505 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002506 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2507 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002508 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002509
Richard Smith74e1ad92012-02-16 02:46:34 +00002510 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002511 }
2512
2513 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002514 bool IsBcpCall = false;
2515 // If the condition (ignoring parens) is a __builtin_constant_p call,
2516 // the result is a constant expression if it can be folded without
2517 // side-effects. This is an important GNU extension. See GCC PR38377
2518 // for discussion.
2519 if (const CallExpr *CallCE =
2520 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2521 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2522 IsBcpCall = true;
2523
2524 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2525 // constant expression; we can't check whether it's potentially foldable.
2526 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2527 return false;
2528
2529 FoldConstant Fold(Info);
2530
Richard Smith74e1ad92012-02-16 02:46:34 +00002531 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002532 return false;
2533
2534 if (IsBcpCall)
2535 Fold.Fold(Info);
2536
2537 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002538 }
2539
2540 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002541 const APValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002542 if (!Value) {
2543 const Expr *Source = E->getSourceExpr();
2544 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002545 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002546 if (Source == E) { // sanity checking.
2547 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002548 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002549 }
2550 return StmtVisitorTy::Visit(Source);
2551 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002552 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002553 }
Richard Smithf10d9172011-10-11 21:43:33 +00002554
Richard Smithd0dccea2011-10-28 22:34:42 +00002555 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002556 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002557 QualType CalleeType = Callee->getType();
2558
Richard Smithd0dccea2011-10-28 22:34:42 +00002559 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002560 LValue *This = 0, ThisVal;
2561 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002562 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002563
Richard Smith59efe262011-11-11 04:05:33 +00002564 // Extract function decl and 'this' pointer from the callee.
2565 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002566 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002567 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2568 // Explicit bound member calls, such as x.f() or p->g();
2569 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002570 return false;
2571 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002572 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002573 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002574 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2575 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002576 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2577 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002578 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002579 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002580 return Error(Callee);
2581
2582 FD = dyn_cast<FunctionDecl>(Member);
2583 if (!FD)
2584 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002585 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002586 LValue Call;
2587 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002588 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002589
Richard Smithb4e85ed2012-01-06 16:39:00 +00002590 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002591 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002592 FD = dyn_cast_or_null<FunctionDecl>(
2593 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002594 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002595 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002596
2597 // Overloaded operator calls to member functions are represented as normal
2598 // calls with '*this' as the first argument.
2599 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2600 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002601 // FIXME: When selecting an implicit conversion for an overloaded
2602 // operator delete, we sometimes try to evaluate calls to conversion
2603 // operators without a 'this' parameter!
2604 if (Args.empty())
2605 return Error(E);
2606
Richard Smith59efe262011-11-11 04:05:33 +00002607 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2608 return false;
2609 This = &ThisVal;
2610 Args = Args.slice(1);
2611 }
2612
2613 // Don't call function pointers which have been cast to some other type.
2614 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002615 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002616 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002617 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002618
Richard Smithb04035a2012-02-01 02:39:43 +00002619 if (This && !This->checkSubobject(Info, E, CSK_This))
2620 return false;
2621
Richard Smith86c3ae42012-02-13 03:54:03 +00002622 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2623 // calls to such functions in constant expressions.
2624 if (This && !HasQualifier &&
2625 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2626 return Error(E, diag::note_constexpr_virtual_call);
2627
Richard Smithc1c5f272011-12-13 06:39:58 +00002628 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002629 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002630 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002631
Richard Smithc1c5f272011-12-13 06:39:58 +00002632 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002633 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2634 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002635 return false;
2636
Richard Smith83587db2012-02-15 02:18:13 +00002637 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002638 }
2639
Richard Smithc49bd112011-10-28 17:51:58 +00002640 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2641 return StmtVisitorTy::Visit(E->getInitializer());
2642 }
Richard Smithf10d9172011-10-11 21:43:33 +00002643 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002644 if (E->getNumInits() == 0)
2645 return DerivedZeroInitialization(E);
2646 if (E->getNumInits() == 1)
2647 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002648 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002649 }
2650 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002651 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002652 }
2653 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002654 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002655 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002656 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002657 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002658 }
Richard Smithf10d9172011-10-11 21:43:33 +00002659
Richard Smith180f4792011-11-10 06:34:14 +00002660 /// A member expression where the object is a prvalue is itself a prvalue.
2661 RetTy VisitMemberExpr(const MemberExpr *E) {
2662 assert(!E->isArrow() && "missing call to bound member function?");
2663
Richard Smith1aa0be82012-03-03 22:46:17 +00002664 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002665 if (!Evaluate(Val, Info, E->getBase()))
2666 return false;
2667
2668 QualType BaseTy = E->getBase()->getType();
2669
2670 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002671 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002672 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2673 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2674 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2675
Richard Smithb4e85ed2012-01-06 16:39:00 +00002676 SubobjectDesignator Designator(BaseTy);
2677 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002678
Richard Smithf48fdb02011-12-09 22:58:01 +00002679 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002680 DerivedSuccess(Val, E);
2681 }
2682
Richard Smithc49bd112011-10-28 17:51:58 +00002683 RetTy VisitCastExpr(const CastExpr *E) {
2684 switch (E->getCastKind()) {
2685 default:
2686 break;
2687
David Chisnall7a7ee302012-01-16 17:27:18 +00002688 case CK_AtomicToNonAtomic:
2689 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002690 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002691 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002692 return StmtVisitorTy::Visit(E->getSubExpr());
2693
2694 case CK_LValueToRValue: {
2695 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002696 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2697 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002698 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002699 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2700 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2701 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002702 return false;
2703 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002704 }
2705 }
2706
Richard Smithf48fdb02011-12-09 22:58:01 +00002707 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002708 }
2709
Richard Smith8327fad2011-10-24 18:44:57 +00002710 /// Visit a value which is evaluated, but whose value is ignored.
2711 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002712 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002713 if (!Evaluate(Scratch, Info, E))
2714 Info.EvalStatus.HasSideEffects = true;
2715 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002716};
2717
2718}
2719
2720//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002721// Common base class for lvalue and temporary evaluation.
2722//===----------------------------------------------------------------------===//
2723namespace {
2724template<class Derived>
2725class LValueExprEvaluatorBase
2726 : public ExprEvaluatorBase<Derived, bool> {
2727protected:
2728 LValue &Result;
2729 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2730 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2731
2732 bool Success(APValue::LValueBase B) {
2733 Result.set(B);
2734 return true;
2735 }
2736
2737public:
2738 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2739 ExprEvaluatorBaseTy(Info), Result(Result) {}
2740
Richard Smith1aa0be82012-03-03 22:46:17 +00002741 bool Success(const APValue &V, const Expr *E) {
2742 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002743 return true;
2744 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002745
Richard Smithe24f5fc2011-11-17 22:56:20 +00002746 bool VisitMemberExpr(const MemberExpr *E) {
2747 // Handle non-static data members.
2748 QualType BaseTy;
2749 if (E->isArrow()) {
2750 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2751 return false;
2752 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002753 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002754 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002755 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2756 return false;
2757 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002758 } else {
2759 if (!this->Visit(E->getBase()))
2760 return false;
2761 BaseTy = E->getBase()->getType();
2762 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002763
Richard Smithd9b02e72012-01-25 22:15:11 +00002764 const ValueDecl *MD = E->getMemberDecl();
2765 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2766 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2767 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2768 (void)BaseTy;
2769 HandleLValueMember(this->Info, E, Result, FD);
2770 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2771 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2772 } else
2773 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002774
Richard Smithd9b02e72012-01-25 22:15:11 +00002775 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002776 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002777 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002778 RefValue))
2779 return false;
2780 return Success(RefValue, E);
2781 }
2782 return true;
2783 }
2784
2785 bool VisitBinaryOperator(const BinaryOperator *E) {
2786 switch (E->getOpcode()) {
2787 default:
2788 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2789
2790 case BO_PtrMemD:
2791 case BO_PtrMemI:
2792 return HandleMemberPointerAccess(this->Info, E, Result);
2793 }
2794 }
2795
2796 bool VisitCastExpr(const CastExpr *E) {
2797 switch (E->getCastKind()) {
2798 default:
2799 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2800
2801 case CK_DerivedToBase:
2802 case CK_UncheckedDerivedToBase: {
2803 if (!this->Visit(E->getSubExpr()))
2804 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002805
2806 // Now figure out the necessary offset to add to the base LV to get from
2807 // the derived class to the base class.
2808 QualType Type = E->getSubExpr()->getType();
2809
2810 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2811 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002812 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002813 *PathI))
2814 return false;
2815 Type = (*PathI)->getType();
2816 }
2817
2818 return true;
2819 }
2820 }
2821 }
2822};
2823}
2824
2825//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002826// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002827//
2828// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2829// function designators (in C), decl references to void objects (in C), and
2830// temporaries (if building with -Wno-address-of-temporary).
2831//
2832// LValue evaluation produces values comprising a base expression of one of the
2833// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002834// - Declarations
2835// * VarDecl
2836// * FunctionDecl
2837// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002838// * CompoundLiteralExpr in C
2839// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002840// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002841// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002842// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002843// * ObjCEncodeExpr
2844// * AddrLabelExpr
2845// * BlockExpr
2846// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002847// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002848// * Any Expr, with a CallIndex indicating the function in which the temporary
2849// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002850// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002851//===----------------------------------------------------------------------===//
2852namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002853class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002854 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002855public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002856 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2857 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002858
Richard Smithc49bd112011-10-28 17:51:58 +00002859 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2860
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002861 bool VisitDeclRefExpr(const DeclRefExpr *E);
2862 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002863 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002864 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2865 bool VisitMemberExpr(const MemberExpr *E);
2866 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2867 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002868 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002869 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2870 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002871 bool VisitUnaryReal(const UnaryOperator *E);
2872 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002873
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002874 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002875 switch (E->getCastKind()) {
2876 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002877 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002878
Eli Friedmandb924222011-10-11 00:13:24 +00002879 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002880 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002881 if (!Visit(E->getSubExpr()))
2882 return false;
2883 Result.Designator.setInvalid();
2884 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002885
Richard Smithe24f5fc2011-11-17 22:56:20 +00002886 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002887 if (!Visit(E->getSubExpr()))
2888 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002889 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002890 }
2891 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002892};
2893} // end anonymous namespace
2894
Richard Smithc49bd112011-10-28 17:51:58 +00002895/// Evaluate an expression as an lvalue. This can be legitimately called on
2896/// expressions which are not glvalues, in a few cases:
2897/// * function designators in C,
2898/// * "extern void" objects,
2899/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002900static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002901 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2902 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2903 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002904 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002905}
2906
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002907bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002908 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2909 return Success(FD);
2910 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002911 return VisitVarDecl(E, VD);
2912 return Error(E);
2913}
Richard Smith436c8892011-10-24 23:14:33 +00002914
Richard Smithc49bd112011-10-28 17:51:58 +00002915bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002916 if (!VD->getType()->isReferenceType()) {
2917 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002918 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002919 return true;
2920 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002921 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002922 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002923
Richard Smith1aa0be82012-03-03 22:46:17 +00002924 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002925 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2926 return false;
2927 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002928}
2929
Richard Smithbd552ef2011-10-31 05:52:43 +00002930bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2931 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002932 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002933 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002934 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2935
Richard Smith83587db2012-02-15 02:18:13 +00002936 Result.set(E, Info.CurrentCall->Index);
2937 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2938 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002939 }
2940
2941 // Materialization of an lvalue temporary occurs when we need to force a copy
2942 // (for instance, if it's a bitfield).
2943 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2944 if (!Visit(E->GetTemporaryExpr()))
2945 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002946 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002947 Info.CurrentCall->Temporaries[E]))
2948 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002949 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002950 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002951}
2952
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002953bool
2954LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002955 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2956 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2957 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002958 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002959}
2960
Richard Smith47d21452011-12-27 12:18:28 +00002961bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2962 if (E->isTypeOperand())
2963 return Success(E);
2964 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2965 if (RD && RD->isPolymorphic()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002966 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith47d21452011-12-27 12:18:28 +00002967 << E->getExprOperand()->getType()
2968 << E->getExprOperand()->getSourceRange();
2969 return false;
2970 }
2971 return Success(E);
2972}
2973
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002974bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002975 // Handle static data members.
2976 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2977 VisitIgnoredValue(E->getBase());
2978 return VisitVarDecl(E, VD);
2979 }
2980
Richard Smithd0dccea2011-10-28 22:34:42 +00002981 // Handle static member functions.
2982 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2983 if (MD->isStatic()) {
2984 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002985 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002986 }
2987 }
2988
Richard Smith180f4792011-11-10 06:34:14 +00002989 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002990 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002991}
2992
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002993bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002994 // FIXME: Deal with vectors as array subscript bases.
2995 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002996 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002997
Anders Carlsson3068d112008-11-16 19:01:22 +00002998 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002999 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003000
Anders Carlsson3068d112008-11-16 19:01:22 +00003001 APSInt Index;
3002 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003003 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003004 int64_t IndexValue
3005 = Index.isSigned() ? Index.getSExtValue()
3006 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003007
Richard Smithb4e85ed2012-01-06 16:39:00 +00003008 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003009}
Eli Friedman4efaa272008-11-12 09:44:48 +00003010
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003011bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003012 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003013}
3014
Richard Smith86024012012-02-18 22:04:06 +00003015bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3016 if (!Visit(E->getSubExpr()))
3017 return false;
3018 // __real is a no-op on scalar lvalues.
3019 if (E->getSubExpr()->getType()->isAnyComplexType())
3020 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3021 return true;
3022}
3023
3024bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3025 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3026 "lvalue __imag__ on scalar?");
3027 if (!Visit(E->getSubExpr()))
3028 return false;
3029 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3030 return true;
3031}
3032
Eli Friedman4efaa272008-11-12 09:44:48 +00003033//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003034// Pointer Evaluation
3035//===----------------------------------------------------------------------===//
3036
Anders Carlssonc754aa62008-07-08 05:13:58 +00003037namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003038class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003039 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003040 LValue &Result;
3041
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003042 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003043 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003044 return true;
3045 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003046public:
Mike Stump1eb44332009-09-09 15:08:12 +00003047
John McCallefdb83e2010-05-07 21:00:08 +00003048 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003049 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003050
Richard Smith1aa0be82012-03-03 22:46:17 +00003051 bool Success(const APValue &V, const Expr *E) {
3052 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003053 return true;
3054 }
Richard Smith51201882011-12-30 21:15:51 +00003055 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003056 return Success((Expr*)0);
3057 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003058
John McCallefdb83e2010-05-07 21:00:08 +00003059 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003060 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003061 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003062 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003063 { return Success(E); }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003064 bool VisitObjCNumericLiteral(const ObjCNumericLiteral *E)
3065 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003066 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003067 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003068 bool VisitCallExpr(const CallExpr *E);
3069 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003070 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003071 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003072 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003073 }
Richard Smith180f4792011-11-10 06:34:14 +00003074 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3075 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003076 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003077 Result = *Info.CurrentCall->This;
3078 return true;
3079 }
John McCall56ca35d2011-02-17 10:25:35 +00003080
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003081 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003082};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003083} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003084
John McCallefdb83e2010-05-07 21:00:08 +00003085static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003086 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003087 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003088}
3089
John McCallefdb83e2010-05-07 21:00:08 +00003090bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003091 if (E->getOpcode() != BO_Add &&
3092 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003093 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003094
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003095 const Expr *PExp = E->getLHS();
3096 const Expr *IExp = E->getRHS();
3097 if (IExp->getType()->isPointerType())
3098 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003099
Richard Smith745f5142012-01-27 01:14:48 +00003100 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3101 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003102 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003103
John McCallefdb83e2010-05-07 21:00:08 +00003104 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003105 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003106 return false;
3107 int64_t AdditionalOffset
3108 = Offset.isSigned() ? Offset.getSExtValue()
3109 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003110 if (E->getOpcode() == BO_Sub)
3111 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003112
Richard Smith180f4792011-11-10 06:34:14 +00003113 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003114 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3115 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003116}
Eli Friedman4efaa272008-11-12 09:44:48 +00003117
John McCallefdb83e2010-05-07 21:00:08 +00003118bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3119 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003120}
Mike Stump1eb44332009-09-09 15:08:12 +00003121
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003122bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3123 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003124
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003125 switch (E->getCastKind()) {
3126 default:
3127 break;
3128
John McCall2de56d12010-08-25 11:45:40 +00003129 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003130 case CK_CPointerToObjCPointerCast:
3131 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003132 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003133 if (!Visit(SubExpr))
3134 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003135 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3136 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3137 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003138 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003139 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003140 if (SubExpr->getType()->isVoidPointerType())
3141 CCEDiag(E, diag::note_constexpr_invalid_cast)
3142 << 3 << SubExpr->getType();
3143 else
3144 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3145 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003146 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003147
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003148 case CK_DerivedToBase:
3149 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003150 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003151 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003152 if (!Result.Base && Result.Offset.isZero())
3153 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003154
Richard Smith180f4792011-11-10 06:34:14 +00003155 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003156 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003157 QualType Type =
3158 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003159
Richard Smith180f4792011-11-10 06:34:14 +00003160 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003161 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003162 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3163 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003164 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003165 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003166 }
3167
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003168 return true;
3169 }
3170
Richard Smithe24f5fc2011-11-17 22:56:20 +00003171 case CK_BaseToDerived:
3172 if (!Visit(E->getSubExpr()))
3173 return false;
3174 if (!Result.Base && Result.Offset.isZero())
3175 return true;
3176 return HandleBaseToDerivedCast(Info, E, Result);
3177
Richard Smith47a1eed2011-10-29 20:57:55 +00003178 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003179 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003180
John McCall2de56d12010-08-25 11:45:40 +00003181 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003182 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3183
Richard Smith1aa0be82012-03-03 22:46:17 +00003184 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003185 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003186 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003187
John McCallefdb83e2010-05-07 21:00:08 +00003188 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003189 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3190 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003191 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003192 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003193 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003194 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003195 return true;
3196 } else {
3197 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003198 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003199 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003200 }
3201 }
John McCall2de56d12010-08-25 11:45:40 +00003202 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003203 if (SubExpr->isGLValue()) {
3204 if (!EvaluateLValue(SubExpr, Result, Info))
3205 return false;
3206 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003207 Result.set(SubExpr, Info.CurrentCall->Index);
3208 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3209 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003210 return false;
3211 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003212 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003213 if (const ConstantArrayType *CAT
3214 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3215 Result.addArray(Info, E, CAT);
3216 else
3217 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003218 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003219
John McCall2de56d12010-08-25 11:45:40 +00003220 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003221 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003222 }
3223
Richard Smithc49bd112011-10-28 17:51:58 +00003224 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003225}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003226
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003227bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003228 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003229 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003230
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003231 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003232}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003233
3234//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003235// Member Pointer Evaluation
3236//===----------------------------------------------------------------------===//
3237
3238namespace {
3239class MemberPointerExprEvaluator
3240 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3241 MemberPtr &Result;
3242
3243 bool Success(const ValueDecl *D) {
3244 Result = MemberPtr(D);
3245 return true;
3246 }
3247public:
3248
3249 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3250 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3251
Richard Smith1aa0be82012-03-03 22:46:17 +00003252 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003253 Result.setFrom(V);
3254 return true;
3255 }
Richard Smith51201882011-12-30 21:15:51 +00003256 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003257 return Success((const ValueDecl*)0);
3258 }
3259
3260 bool VisitCastExpr(const CastExpr *E);
3261 bool VisitUnaryAddrOf(const UnaryOperator *E);
3262};
3263} // end anonymous namespace
3264
3265static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3266 EvalInfo &Info) {
3267 assert(E->isRValue() && E->getType()->isMemberPointerType());
3268 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3269}
3270
3271bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3272 switch (E->getCastKind()) {
3273 default:
3274 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3275
3276 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003277 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003278
3279 case CK_BaseToDerivedMemberPointer: {
3280 if (!Visit(E->getSubExpr()))
3281 return false;
3282 if (E->path_empty())
3283 return true;
3284 // Base-to-derived member pointer casts store the path in derived-to-base
3285 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3286 // the wrong end of the derived->base arc, so stagger the path by one class.
3287 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3288 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3289 PathI != PathE; ++PathI) {
3290 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3291 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3292 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003293 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003294 }
3295 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3296 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003297 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003298 return true;
3299 }
3300
3301 case CK_DerivedToBaseMemberPointer:
3302 if (!Visit(E->getSubExpr()))
3303 return false;
3304 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3305 PathE = E->path_end(); PathI != PathE; ++PathI) {
3306 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3307 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3308 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003309 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003310 }
3311 return true;
3312 }
3313}
3314
3315bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3316 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3317 // member can be formed.
3318 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3319}
3320
3321//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003322// Record Evaluation
3323//===----------------------------------------------------------------------===//
3324
3325namespace {
3326 class RecordExprEvaluator
3327 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3328 const LValue &This;
3329 APValue &Result;
3330 public:
3331
3332 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3333 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3334
Richard Smith1aa0be82012-03-03 22:46:17 +00003335 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003336 Result = V;
3337 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003338 }
Richard Smith51201882011-12-30 21:15:51 +00003339 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003340
Richard Smith59efe262011-11-11 04:05:33 +00003341 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003342 bool VisitInitListExpr(const InitListExpr *E);
3343 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3344 };
3345}
3346
Richard Smith51201882011-12-30 21:15:51 +00003347/// Perform zero-initialization on an object of non-union class type.
3348/// C++11 [dcl.init]p5:
3349/// To zero-initialize an object or reference of type T means:
3350/// [...]
3351/// -- if T is a (possibly cv-qualified) non-union class type,
3352/// each non-static data member and each base-class subobject is
3353/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003354static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3355 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003356 const LValue &This, APValue &Result) {
3357 assert(!RD->isUnion() && "Expected non-union class type");
3358 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3359 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3360 std::distance(RD->field_begin(), RD->field_end()));
3361
3362 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3363
3364 if (CD) {
3365 unsigned Index = 0;
3366 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003367 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003368 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3369 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003370 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3371 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003372 Result.getStructBase(Index)))
3373 return false;
3374 }
3375 }
3376
Richard Smithb4e85ed2012-01-06 16:39:00 +00003377 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3378 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003379 // -- if T is a reference type, no initialization is performed.
3380 if ((*I)->getType()->isReferenceType())
3381 continue;
3382
3383 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003384 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003385
3386 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003387 if (!EvaluateInPlace(
Richard Smith51201882011-12-30 21:15:51 +00003388 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3389 return false;
3390 }
3391
3392 return true;
3393}
3394
3395bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3396 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3397 if (RD->isUnion()) {
3398 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3399 // object's first non-static named data member is zero-initialized
3400 RecordDecl::field_iterator I = RD->field_begin();
3401 if (I == RD->field_end()) {
3402 Result = APValue((const FieldDecl*)0);
3403 return true;
3404 }
3405
3406 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003407 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003408 Result = APValue(*I);
3409 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003410 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003411 }
3412
Richard Smithce582fe2012-02-17 00:44:16 +00003413 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003414 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003415 return false;
3416 }
3417
Richard Smithb4e85ed2012-01-06 16:39:00 +00003418 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003419}
3420
Richard Smith59efe262011-11-11 04:05:33 +00003421bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3422 switch (E->getCastKind()) {
3423 default:
3424 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3425
3426 case CK_ConstructorConversion:
3427 return Visit(E->getSubExpr());
3428
3429 case CK_DerivedToBase:
3430 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003431 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003432 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003433 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003434 if (!DerivedObject.isStruct())
3435 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003436
3437 // Derived-to-base rvalue conversion: just slice off the derived part.
3438 APValue *Value = &DerivedObject;
3439 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3440 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3441 PathE = E->path_end(); PathI != PathE; ++PathI) {
3442 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3443 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3444 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3445 RD = Base;
3446 }
3447 Result = *Value;
3448 return true;
3449 }
3450 }
3451}
3452
Richard Smith180f4792011-11-10 06:34:14 +00003453bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003454 // Cannot constant-evaluate std::initializer_list inits.
3455 if (E->initializesStdInitializerList())
3456 return false;
3457
Richard Smith180f4792011-11-10 06:34:14 +00003458 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3459 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3460
3461 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003462 const FieldDecl *Field = E->getInitializedFieldInUnion();
3463 Result = APValue(Field);
3464 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003465 return true;
Richard Smithec789162012-01-12 18:54:33 +00003466
3467 // If the initializer list for a union does not contain any elements, the
3468 // first element of the union is value-initialized.
3469 ImplicitValueInitExpr VIE(Field->getType());
3470 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3471
Richard Smith180f4792011-11-10 06:34:14 +00003472 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003473 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith83587db2012-02-15 02:18:13 +00003474 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003475 }
3476
3477 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3478 "initializer list for class with base classes");
3479 Result = APValue(APValue::UninitStruct(), 0,
3480 std::distance(RD->field_begin(), RD->field_end()));
3481 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003482 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003483 for (RecordDecl::field_iterator Field = RD->field_begin(),
3484 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3485 // Anonymous bit-fields are not considered members of the class for
3486 // purposes of aggregate initialization.
3487 if (Field->isUnnamedBitfield())
3488 continue;
3489
3490 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003491
Richard Smith745f5142012-01-27 01:14:48 +00003492 bool HaveInit = ElementNo < E->getNumInits();
3493
3494 // FIXME: Diagnostics here should point to the end of the initializer
3495 // list, not the start.
3496 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3497 *Field, &Layout);
3498
3499 // Perform an implicit value-initialization for members beyond the end of
3500 // the initializer list.
3501 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3502
Richard Smith83587db2012-02-15 02:18:13 +00003503 if (!EvaluateInPlace(
Richard Smith745f5142012-01-27 01:14:48 +00003504 Result.getStructField((*Field)->getFieldIndex()),
3505 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3506 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003507 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003508 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003509 }
3510 }
3511
Richard Smith745f5142012-01-27 01:14:48 +00003512 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003513}
3514
3515bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3516 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003517 bool ZeroInit = E->requiresZeroInitialization();
3518 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003519 // If we've already performed zero-initialization, we're already done.
3520 if (!Result.isUninit())
3521 return true;
3522
Richard Smith51201882011-12-30 21:15:51 +00003523 if (ZeroInit)
3524 return ZeroInitialization(E);
3525
Richard Smith61802452011-12-22 02:22:31 +00003526 const CXXRecordDecl *RD = FD->getParent();
3527 if (RD->isUnion())
3528 Result = APValue((FieldDecl*)0);
3529 else
3530 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3531 std::distance(RD->field_begin(), RD->field_end()));
3532 return true;
3533 }
3534
Richard Smith180f4792011-11-10 06:34:14 +00003535 const FunctionDecl *Definition = 0;
3536 FD->getBody(Definition);
3537
Richard Smithc1c5f272011-12-13 06:39:58 +00003538 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3539 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003540
Richard Smith610a60c2012-01-10 04:32:03 +00003541 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003542 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003543 if (const MaterializeTemporaryExpr *ME
3544 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3545 return Visit(ME->GetTemporaryExpr());
3546
Richard Smith51201882011-12-30 21:15:51 +00003547 if (ZeroInit && !ZeroInitialization(E))
3548 return false;
3549
Richard Smith180f4792011-11-10 06:34:14 +00003550 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003551 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003552 cast<CXXConstructorDecl>(Definition), Info,
3553 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003554}
3555
3556static bool EvaluateRecord(const Expr *E, const LValue &This,
3557 APValue &Result, EvalInfo &Info) {
3558 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003559 "can't evaluate expression as a record rvalue");
3560 return RecordExprEvaluator(Info, This, Result).Visit(E);
3561}
3562
3563//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003564// Temporary Evaluation
3565//
3566// Temporaries are represented in the AST as rvalues, but generally behave like
3567// lvalues. The full-object of which the temporary is a subobject is implicitly
3568// materialized so that a reference can bind to it.
3569//===----------------------------------------------------------------------===//
3570namespace {
3571class TemporaryExprEvaluator
3572 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3573public:
3574 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3575 LValueExprEvaluatorBaseTy(Info, Result) {}
3576
3577 /// Visit an expression which constructs the value of this temporary.
3578 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003579 Result.set(E, Info.CurrentCall->Index);
3580 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003581 }
3582
3583 bool VisitCastExpr(const CastExpr *E) {
3584 switch (E->getCastKind()) {
3585 default:
3586 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3587
3588 case CK_ConstructorConversion:
3589 return VisitConstructExpr(E->getSubExpr());
3590 }
3591 }
3592 bool VisitInitListExpr(const InitListExpr *E) {
3593 return VisitConstructExpr(E);
3594 }
3595 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3596 return VisitConstructExpr(E);
3597 }
3598 bool VisitCallExpr(const CallExpr *E) {
3599 return VisitConstructExpr(E);
3600 }
3601};
3602} // end anonymous namespace
3603
3604/// Evaluate an expression of record type as a temporary.
3605static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003606 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003607 return TemporaryExprEvaluator(Info, Result).Visit(E);
3608}
3609
3610//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003611// Vector Evaluation
3612//===----------------------------------------------------------------------===//
3613
3614namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003615 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003616 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3617 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003618 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003619
Richard Smith07fc6572011-10-22 21:10:00 +00003620 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3621 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Richard Smith07fc6572011-10-22 21:10:00 +00003623 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3624 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3625 // FIXME: remove this APValue copy.
3626 Result = APValue(V.data(), V.size());
3627 return true;
3628 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003629 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003630 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003631 Result = V;
3632 return true;
3633 }
Richard Smith51201882011-12-30 21:15:51 +00003634 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003635
Richard Smith07fc6572011-10-22 21:10:00 +00003636 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003637 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003638 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003639 bool VisitInitListExpr(const InitListExpr *E);
3640 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003641 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003642 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003643 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003644 };
3645} // end anonymous namespace
3646
3647static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003648 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003649 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003650}
3651
Richard Smith07fc6572011-10-22 21:10:00 +00003652bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3653 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003654 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003655
Richard Smithd62ca372011-12-06 22:44:34 +00003656 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003657 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003658
Eli Friedman46a52322011-03-25 00:43:55 +00003659 switch (E->getCastKind()) {
3660 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003661 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003662 if (SETy->isIntegerType()) {
3663 APSInt IntResult;
3664 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003665 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003666 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003667 } else if (SETy->isRealFloatingType()) {
3668 APFloat F(0.0);
3669 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003670 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003671 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003672 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003673 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003674 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003675
3676 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003677 SmallVector<APValue, 4> Elts(NElts, Val);
3678 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003679 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003680 case CK_BitCast: {
3681 // Evaluate the operand into an APInt we can extract from.
3682 llvm::APInt SValInt;
3683 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3684 return false;
3685 // Extract the elements
3686 QualType EltTy = VTy->getElementType();
3687 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3688 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3689 SmallVector<APValue, 4> Elts;
3690 if (EltTy->isRealFloatingType()) {
3691 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3692 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3693 unsigned FloatEltSize = EltSize;
3694 if (&Sem == &APFloat::x87DoubleExtended)
3695 FloatEltSize = 80;
3696 for (unsigned i = 0; i < NElts; i++) {
3697 llvm::APInt Elt;
3698 if (BigEndian)
3699 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3700 else
3701 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3702 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3703 }
3704 } else if (EltTy->isIntegerType()) {
3705 for (unsigned i = 0; i < NElts; i++) {
3706 llvm::APInt Elt;
3707 if (BigEndian)
3708 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3709 else
3710 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3711 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3712 }
3713 } else {
3714 return Error(E);
3715 }
3716 return Success(Elts, E);
3717 }
Eli Friedman46a52322011-03-25 00:43:55 +00003718 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003719 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003720 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003721}
3722
Richard Smith07fc6572011-10-22 21:10:00 +00003723bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003724VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003725 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003726 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003727 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003728
Nate Begeman59b5da62009-01-18 03:20:47 +00003729 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003730 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003731
Eli Friedman3edd5a92012-01-03 23:24:20 +00003732 // The number of initializers can be less than the number of
3733 // vector elements. For OpenCL, this can be due to nested vector
3734 // initialization. For GCC compatibility, missing trailing elements
3735 // should be initialized with zeroes.
3736 unsigned CountInits = 0, CountElts = 0;
3737 while (CountElts < NumElements) {
3738 // Handle nested vector initialization.
3739 if (CountInits < NumInits
3740 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3741 APValue v;
3742 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3743 return Error(E);
3744 unsigned vlen = v.getVectorLength();
3745 for (unsigned j = 0; j < vlen; j++)
3746 Elements.push_back(v.getVectorElt(j));
3747 CountElts += vlen;
3748 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003749 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003750 if (CountInits < NumInits) {
3751 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003752 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003753 } else // trailing integer zero.
3754 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3755 Elements.push_back(APValue(sInt));
3756 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003757 } else {
3758 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003759 if (CountInits < NumInits) {
3760 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003761 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003762 } else // trailing float zero.
3763 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3764 Elements.push_back(APValue(f));
3765 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003766 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003767 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003768 }
Richard Smith07fc6572011-10-22 21:10:00 +00003769 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003770}
3771
Richard Smith07fc6572011-10-22 21:10:00 +00003772bool
Richard Smith51201882011-12-30 21:15:51 +00003773VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003774 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003775 QualType EltTy = VT->getElementType();
3776 APValue ZeroElement;
3777 if (EltTy->isIntegerType())
3778 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3779 else
3780 ZeroElement =
3781 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3782
Chris Lattner5f9e2722011-07-23 10:55:15 +00003783 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003784 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003785}
3786
Richard Smith07fc6572011-10-22 21:10:00 +00003787bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003788 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003789 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003790}
3791
Nate Begeman59b5da62009-01-18 03:20:47 +00003792//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003793// Array Evaluation
3794//===----------------------------------------------------------------------===//
3795
3796namespace {
3797 class ArrayExprEvaluator
3798 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003799 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003800 APValue &Result;
3801 public:
3802
Richard Smith180f4792011-11-10 06:34:14 +00003803 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3804 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003805
3806 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003807 assert((V.isArray() || V.isLValue()) &&
3808 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003809 Result = V;
3810 return true;
3811 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003812
Richard Smith51201882011-12-30 21:15:51 +00003813 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003814 const ConstantArrayType *CAT =
3815 Info.Ctx.getAsConstantArrayType(E->getType());
3816 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003817 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003818
3819 Result = APValue(APValue::UninitArray(), 0,
3820 CAT->getSize().getZExtValue());
3821 if (!Result.hasArrayFiller()) return true;
3822
Richard Smith51201882011-12-30 21:15:51 +00003823 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003824 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003825 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003826 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003827 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003828 }
3829
Richard Smithcc5d4f62011-11-07 09:22:26 +00003830 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003831 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003832 };
3833} // end anonymous namespace
3834
Richard Smith180f4792011-11-10 06:34:14 +00003835static bool EvaluateArray(const Expr *E, const LValue &This,
3836 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003837 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003838 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003839}
3840
3841bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3842 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3843 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003844 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003845
Richard Smith974c5f92011-12-22 01:07:19 +00003846 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3847 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003848 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003849 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3850 LValue LV;
3851 if (!EvaluateLValue(E->getInit(0), LV, Info))
3852 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003853 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003854 LV.moveInto(Val);
3855 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003856 }
3857
Richard Smith745f5142012-01-27 01:14:48 +00003858 bool Success = true;
3859
Richard Smithcc5d4f62011-11-07 09:22:26 +00003860 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3861 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003862 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003863 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003864 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003865 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003866 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003867 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3868 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003869 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3870 CAT->getElementType(), 1)) {
3871 if (!Info.keepEvaluatingAfterFailure())
3872 return false;
3873 Success = false;
3874 }
Richard Smith180f4792011-11-10 06:34:14 +00003875 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003876
Richard Smith745f5142012-01-27 01:14:48 +00003877 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003878 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003879 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3880 // but sometimes does:
3881 // struct S { constexpr S() : p(&p) {} void *p; };
3882 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003883 return EvaluateInPlace(Result.getArrayFiller(), Info,
3884 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003885}
3886
Richard Smithe24f5fc2011-11-17 22:56:20 +00003887bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3888 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3889 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003890 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003891
Richard Smithec789162012-01-12 18:54:33 +00003892 bool HadZeroInit = !Result.isUninit();
3893 if (!HadZeroInit)
3894 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003895 if (!Result.hasArrayFiller())
3896 return true;
3897
3898 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003899
Richard Smith51201882011-12-30 21:15:51 +00003900 bool ZeroInit = E->requiresZeroInitialization();
3901 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003902 if (HadZeroInit)
3903 return true;
3904
Richard Smith51201882011-12-30 21:15:51 +00003905 if (ZeroInit) {
3906 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003907 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003908 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003909 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003910 }
3911
Richard Smith61802452011-12-22 02:22:31 +00003912 const CXXRecordDecl *RD = FD->getParent();
3913 if (RD->isUnion())
3914 Result.getArrayFiller() = APValue((FieldDecl*)0);
3915 else
3916 Result.getArrayFiller() =
3917 APValue(APValue::UninitStruct(), RD->getNumBases(),
3918 std::distance(RD->field_begin(), RD->field_end()));
3919 return true;
3920 }
3921
Richard Smithe24f5fc2011-11-17 22:56:20 +00003922 const FunctionDecl *Definition = 0;
3923 FD->getBody(Definition);
3924
Richard Smithc1c5f272011-12-13 06:39:58 +00003925 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3926 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003927
3928 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3929 // but sometimes does:
3930 // struct S { constexpr S() : p(&p) {} void *p; };
3931 // S s[10];
3932 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003933 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003934
Richard Smithec789162012-01-12 18:54:33 +00003935 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003936 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003937 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003938 return false;
3939 }
3940
Richard Smithe24f5fc2011-11-17 22:56:20 +00003941 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003942 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003943 cast<CXXConstructorDecl>(Definition),
3944 Info, Result.getArrayFiller());
3945}
3946
Richard Smithcc5d4f62011-11-07 09:22:26 +00003947//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003948// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003949//
3950// As a GNU extension, we support casting pointers to sufficiently-wide integer
3951// types and back in constant folding. Integer values are thus represented
3952// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003953//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003954
3955namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003956class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003957 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003958 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003959public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003960 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003961 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003962
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003963 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003964 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003965 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003966 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003967 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003968 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003969 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003970 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003971 return true;
3972 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003973 bool Success(const llvm::APSInt &SI, const Expr *E) {
3974 return Success(SI, E, Result);
3975 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003976
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003977 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003978 assert(E->getType()->isIntegralOrEnumerationType() &&
3979 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003980 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003981 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003982 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003983 Result.getInt().setIsUnsigned(
3984 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003985 return true;
3986 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003987 bool Success(const llvm::APInt &I, const Expr *E) {
3988 return Success(I, E, Result);
3989 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00003990
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003991 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003992 assert(E->getType()->isIntegralOrEnumerationType() &&
3993 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003994 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003995 return true;
3996 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003997 bool Success(uint64_t Value, const Expr *E) {
3998 return Success(Value, E, Result);
3999 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00004000
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004001 bool Success(CharUnits Size, const Expr *E) {
4002 return Success(Size.getQuantity(), E);
4003 }
4004
Richard Smith1aa0be82012-03-03 22:46:17 +00004005 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00004006 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00004007 Result = V;
4008 return true;
4009 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004010 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00004011 }
Mike Stump1eb44332009-09-09 15:08:12 +00004012
Richard Smith51201882011-12-30 21:15:51 +00004013 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00004014
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004015 //===--------------------------------------------------------------------===//
4016 // Visitor Methods
4017 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004018
Chris Lattner4c4867e2008-07-12 00:38:25 +00004019 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004020 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004021 }
4022 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004023 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004024 }
Eli Friedman04309752009-11-24 05:28:59 +00004025
4026 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4027 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004028 if (CheckReferencedDecl(E, E->getDecl()))
4029 return true;
4030
4031 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004032 }
4033 bool VisitMemberExpr(const MemberExpr *E) {
4034 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004035 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004036 return true;
4037 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004038
4039 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004040 }
4041
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004042 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004043 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004044 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004045 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004046
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004047 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004048 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004049
Anders Carlsson3068d112008-11-16 19:01:22 +00004050 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004051 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004052 }
Mike Stump1eb44332009-09-09 15:08:12 +00004053
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004054 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4055 return Success(E->getValue(), E);
4056 }
4057
Richard Smithf10d9172011-10-11 21:43:33 +00004058 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004059 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004060 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004061 }
4062
Sebastian Redl64b45f72009-01-05 20:52:13 +00004063 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004064 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004065 }
4066
Francois Pichet6ad6f282010-12-07 00:08:36 +00004067 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4068 return Success(E->getValue(), E);
4069 }
4070
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004071 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4072 return Success(E->getValue(), E);
4073 }
4074
John Wiegley21ff2e52011-04-28 00:16:57 +00004075 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4076 return Success(E->getValue(), E);
4077 }
4078
John Wiegley55262202011-04-25 06:54:41 +00004079 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4080 return Success(E->getValue(), E);
4081 }
4082
Eli Friedman722c7172009-02-28 03:59:05 +00004083 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004084 bool VisitUnaryImag(const UnaryOperator *E);
4085
Sebastian Redl295995c2010-09-10 20:55:47 +00004086 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004087 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004088
Chris Lattnerfcee0012008-07-11 21:24:13 +00004089private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004090 CharUnits GetAlignOfExpr(const Expr *E);
4091 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004092 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004093 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004094 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004095};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004096} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004097
Richard Smithc49bd112011-10-28 17:51:58 +00004098/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4099/// produce either the integer value or a pointer.
4100///
4101/// GCC has a heinous extension which folds casts between pointer types and
4102/// pointer-sized integral types. We support this by allowing the evaluation of
4103/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4104/// Some simple arithmetic on such values is supported (they are treated much
4105/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004106static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004107 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004108 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004109 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004110}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004111
Richard Smithf48fdb02011-12-09 22:58:01 +00004112static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004113 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004114 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004115 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004116 if (!Val.isInt()) {
4117 // FIXME: It would be better to produce the diagnostic for casting
4118 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004119 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004120 return false;
4121 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004122 Result = Val.getInt();
4123 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004124}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004125
Richard Smithf48fdb02011-12-09 22:58:01 +00004126/// Check whether the given declaration can be directly converted to an integral
4127/// rvalue. If not, no diagnostic is produced; there are other things we can
4128/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004129bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004130 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004132 // Check for signedness/width mismatches between E type and ECD value.
4133 bool SameSign = (ECD->getInitVal().isSigned()
4134 == E->getType()->isSignedIntegerOrEnumerationType());
4135 bool SameWidth = (ECD->getInitVal().getBitWidth()
4136 == Info.Ctx.getIntWidth(E->getType()));
4137 if (SameSign && SameWidth)
4138 return Success(ECD->getInitVal(), E);
4139 else {
4140 // Get rid of mismatch (otherwise Success assertions will fail)
4141 // by computing a new value matching the type of E.
4142 llvm::APSInt Val = ECD->getInitVal();
4143 if (!SameSign)
4144 Val.setIsSigned(!ECD->getInitVal().isSigned());
4145 if (!SameWidth)
4146 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4147 return Success(Val, E);
4148 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004149 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004150 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004151}
4152
Chris Lattnera4d55d82008-10-06 06:40:35 +00004153/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4154/// as GCC.
4155static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4156 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004157 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004158 enum gcc_type_class {
4159 no_type_class = -1,
4160 void_type_class, integer_type_class, char_type_class,
4161 enumeral_type_class, boolean_type_class,
4162 pointer_type_class, reference_type_class, offset_type_class,
4163 real_type_class, complex_type_class,
4164 function_type_class, method_type_class,
4165 record_type_class, union_type_class,
4166 array_type_class, string_type_class,
4167 lang_type_class
4168 };
Mike Stump1eb44332009-09-09 15:08:12 +00004169
4170 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004171 // ideal, however it is what gcc does.
4172 if (E->getNumArgs() == 0)
4173 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004174
Chris Lattnera4d55d82008-10-06 06:40:35 +00004175 QualType ArgTy = E->getArg(0)->getType();
4176 if (ArgTy->isVoidType())
4177 return void_type_class;
4178 else if (ArgTy->isEnumeralType())
4179 return enumeral_type_class;
4180 else if (ArgTy->isBooleanType())
4181 return boolean_type_class;
4182 else if (ArgTy->isCharType())
4183 return string_type_class; // gcc doesn't appear to use char_type_class
4184 else if (ArgTy->isIntegerType())
4185 return integer_type_class;
4186 else if (ArgTy->isPointerType())
4187 return pointer_type_class;
4188 else if (ArgTy->isReferenceType())
4189 return reference_type_class;
4190 else if (ArgTy->isRealType())
4191 return real_type_class;
4192 else if (ArgTy->isComplexType())
4193 return complex_type_class;
4194 else if (ArgTy->isFunctionType())
4195 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004196 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004197 return record_type_class;
4198 else if (ArgTy->isUnionType())
4199 return union_type_class;
4200 else if (ArgTy->isArrayType())
4201 return array_type_class;
4202 else if (ArgTy->isUnionType())
4203 return union_type_class;
4204 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004205 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004206}
4207
Richard Smith80d4b552011-12-28 19:48:30 +00004208/// EvaluateBuiltinConstantPForLValue - Determine the result of
4209/// __builtin_constant_p when applied to the given lvalue.
4210///
4211/// An lvalue is only "constant" if it is a pointer or reference to the first
4212/// character of a string literal.
4213template<typename LValue>
4214static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004215 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004216 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4217}
4218
4219/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4220/// GCC as we can manage.
4221static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4222 QualType ArgType = Arg->getType();
4223
4224 // __builtin_constant_p always has one operand. The rules which gcc follows
4225 // are not precisely documented, but are as follows:
4226 //
4227 // - If the operand is of integral, floating, complex or enumeration type,
4228 // and can be folded to a known value of that type, it returns 1.
4229 // - If the operand and can be folded to a pointer to the first character
4230 // of a string literal (or such a pointer cast to an integral type), it
4231 // returns 1.
4232 //
4233 // Otherwise, it returns 0.
4234 //
4235 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4236 // its support for this does not currently work.
4237 if (ArgType->isIntegralOrEnumerationType()) {
4238 Expr::EvalResult Result;
4239 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4240 return false;
4241
4242 APValue &V = Result.Val;
4243 if (V.getKind() == APValue::Int)
4244 return true;
4245
4246 return EvaluateBuiltinConstantPForLValue(V);
4247 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4248 return Arg->isEvaluatable(Ctx);
4249 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4250 LValue LV;
4251 Expr::EvalStatus Status;
4252 EvalInfo Info(Ctx, Status);
4253 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4254 : EvaluatePointer(Arg, LV, Info)) &&
4255 !Status.HasSideEffects)
4256 return EvaluateBuiltinConstantPForLValue(LV);
4257 }
4258
4259 // Anything else isn't considered to be sufficiently constant.
4260 return false;
4261}
4262
John McCall42c8f872010-05-10 23:27:23 +00004263/// Retrieves the "underlying object type" of the given expression,
4264/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004265QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4266 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4267 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004268 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004269 } else if (const Expr *E = B.get<const Expr*>()) {
4270 if (isa<CompoundLiteralExpr>(E))
4271 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004272 }
4273
4274 return QualType();
4275}
4276
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004277bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004278 // TODO: Perhaps we should let LLVM lower this?
4279 LValue Base;
4280 if (!EvaluatePointer(E->getArg(0), Base, Info))
4281 return false;
4282
4283 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004284 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004285
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004286 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004287 if (T.isNull() ||
4288 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004289 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004290 T->isVariablyModifiedType() ||
4291 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004292 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004293
4294 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4295 CharUnits Offset = Base.getLValueOffset();
4296
4297 if (!Offset.isNegative() && Offset <= Size)
4298 Size -= Offset;
4299 else
4300 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004301 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004302}
4303
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004304bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004305 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004306 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004307 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004308
4309 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004310 if (TryEvaluateBuiltinObjectSize(E))
4311 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004312
Eric Christopherb2aaf512010-01-19 22:58:35 +00004313 // If evaluating the argument has side-effects we can't determine
4314 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004315 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004316 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004317 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004318 return Success(0, E);
4319 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004320
Richard Smithf48fdb02011-12-09 22:58:01 +00004321 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004322 }
4323
Chris Lattner019f4e82008-10-06 05:28:25 +00004324 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004325 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004326
Richard Smith80d4b552011-12-28 19:48:30 +00004327 case Builtin::BI__builtin_constant_p:
4328 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004329
Chris Lattner21fb98e2009-09-23 06:06:36 +00004330 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004331 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004332 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004333 return Success(Operand, E);
4334 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004335
4336 case Builtin::BI__builtin_expect:
4337 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004338
Douglas Gregor5726d402010-09-10 06:27:15 +00004339 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004340 // A call to strlen is not a constant expression.
4341 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004342 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004343 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4344 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004345 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004346 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004347 case Builtin::BI__builtin_strlen:
4348 // As an extension, we support strlen() and __builtin_strlen() as constant
4349 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004350 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004351 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4352 // The string literal may have embedded null characters. Find the first
4353 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004354 StringRef Str = S->getString();
4355 StringRef::size_type Pos = Str.find(0);
4356 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004357 Str = Str.substr(0, Pos);
4358
4359 return Success(Str.size(), E);
4360 }
4361
Richard Smithf48fdb02011-12-09 22:58:01 +00004362 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004363
4364 case Builtin::BI__atomic_is_lock_free: {
4365 APSInt SizeVal;
4366 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4367 return false;
4368
4369 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4370 // of two less than the maximum inline atomic width, we know it is
4371 // lock-free. If the size isn't a power of two, or greater than the
4372 // maximum alignment where we promote atomics, we know it is not lock-free
4373 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4374 // the answer can only be determined at runtime; for example, 16-byte
4375 // atomics have lock-free implementations on some, but not all,
4376 // x86-64 processors.
4377
4378 // Check power-of-two.
4379 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4380 if (!Size.isPowerOfTwo())
4381#if 0
4382 // FIXME: Suppress this folding until the ABI for the promotion width
4383 // settles.
4384 return Success(0, E);
4385#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004386 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004387#endif
4388
4389#if 0
4390 // Check against promotion width.
4391 // FIXME: Suppress this folding until the ABI for the promotion width
4392 // settles.
4393 unsigned PromoteWidthBits =
4394 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4395 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4396 return Success(0, E);
4397#endif
4398
4399 // Check against inlining width.
4400 unsigned InlineWidthBits =
4401 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4402 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4403 return Success(1, E);
4404
Richard Smithf48fdb02011-12-09 22:58:01 +00004405 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004406 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004407 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004408}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004409
Richard Smith625b8072011-10-31 01:37:14 +00004410static bool HasSameBase(const LValue &A, const LValue &B) {
4411 if (!A.getLValueBase())
4412 return !B.getLValueBase();
4413 if (!B.getLValueBase())
4414 return false;
4415
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004416 if (A.getLValueBase().getOpaqueValue() !=
4417 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004418 const Decl *ADecl = GetLValueBaseDecl(A);
4419 if (!ADecl)
4420 return false;
4421 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004422 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004423 return false;
4424 }
4425
4426 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004427 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004428}
4429
Richard Smith7b48a292012-02-01 05:53:12 +00004430/// Perform the given integer operation, which is known to need at most BitWidth
4431/// bits, and check for overflow in the original type (if that type was not an
4432/// unsigned type).
4433template<typename Operation>
4434static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4435 const APSInt &LHS, const APSInt &RHS,
4436 unsigned BitWidth, Operation Op) {
4437 if (LHS.isUnsigned())
4438 return Op(LHS, RHS);
4439
4440 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4441 APSInt Result = Value.trunc(LHS.getBitWidth());
4442 if (Result.extend(BitWidth) != Value)
4443 HandleOverflow(Info, E, Value, E->getType());
4444 return Result;
4445}
4446
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004447namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00004448
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004449/// \brief Data recursive integer evaluator of certain binary operators.
4450///
4451/// We use a data recursive algorithm for binary operators so that we are able
4452/// to handle extreme cases of chained binary operators without causing stack
4453/// overflow.
4454class DataRecursiveIntBinOpEvaluator {
4455 struct EvalResult {
4456 APValue Val;
4457 bool Failed;
4458
4459 EvalResult() : Failed(false) { }
4460
4461 void swap(EvalResult &RHS) {
4462 Val.swap(RHS.Val);
4463 Failed = RHS.Failed;
4464 RHS.Failed = false;
4465 }
4466 };
4467
4468 struct Job {
4469 const Expr *E;
4470 EvalResult LHSResult; // meaningful only for binary operator expression.
4471 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4472
4473 Job() : StoredInfo(0) { }
4474 void startSpeculativeEval(EvalInfo &Info) {
4475 OldEvalStatus = Info.EvalStatus;
4476 Info.EvalStatus.Diag = 0;
4477 StoredInfo = &Info;
4478 }
4479 ~Job() {
4480 if (StoredInfo) {
4481 StoredInfo->EvalStatus = OldEvalStatus;
4482 }
4483 }
4484 private:
4485 EvalInfo *StoredInfo; // non-null if status changed.
4486 Expr::EvalStatus OldEvalStatus;
4487 };
4488
4489 SmallVector<Job, 16> Queue;
4490
4491 IntExprEvaluator &IntEval;
4492 EvalInfo &Info;
4493 APValue &FinalResult;
4494
4495public:
4496 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4497 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4498
4499 /// \brief True if \param E is a binary operator that we are going to handle
4500 /// data recursively.
4501 /// We handle binary operators that are comma, logical, or that have operands
4502 /// with integral or enumeration type.
4503 static bool shouldEnqueue(const BinaryOperator *E) {
4504 return E->getOpcode() == BO_Comma ||
4505 E->isLogicalOp() ||
4506 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4507 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00004508 }
4509
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004510 bool Traverse(const BinaryOperator *E) {
4511 enqueue(E);
4512 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00004513 while (!Queue.empty())
4514 process(PrevResult);
4515
4516 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004517
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004518 FinalResult.swap(PrevResult.Val);
4519 return true;
4520 }
4521
4522private:
4523 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4524 return IntEval.Success(Value, E, Result);
4525 }
4526 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4527 return IntEval.Success(Value, E, Result);
4528 }
4529 bool Error(const Expr *E) {
4530 return IntEval.Error(E);
4531 }
4532 bool Error(const Expr *E, diag::kind D) {
4533 return IntEval.Error(E, D);
4534 }
4535
4536 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4537 return Info.CCEDiag(E, D);
4538 }
4539
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004540 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4541 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004542 bool &SuppressRHSDiags);
4543
4544 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4545 const BinaryOperator *E, APValue &Result);
4546
4547 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4548 Result.Failed = !Evaluate(Result.Val, Info, E);
4549 if (Result.Failed)
4550 Result.Val = APValue();
4551 }
4552
Richard Trieub7783052012-03-21 23:30:30 +00004553 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004554
4555 void enqueue(const Expr *E) {
4556 E = E->IgnoreParens();
4557 Queue.resize(Queue.size()+1);
4558 Queue.back().E = E;
4559 Queue.back().Kind = Job::AnyExprKind;
4560 }
4561};
4562
4563}
4564
4565bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004566 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004567 bool &SuppressRHSDiags) {
4568 if (E->getOpcode() == BO_Comma) {
4569 // Ignore LHS but note if we could not evaluate it.
4570 if (LHSResult.Failed)
4571 Info.EvalStatus.HasSideEffects = true;
4572 return true;
4573 }
4574
4575 if (E->isLogicalOp()) {
4576 bool lhsResult;
4577 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004578 // We were able to evaluate the LHS, see if we can get away with not
4579 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004580 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004581 Success(lhsResult, E, LHSResult.Val);
4582 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004583 }
4584 } else {
4585 // Since we weren't able to evaluate the left hand side, it
4586 // must have had side effects.
4587 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004588
4589 // We can't evaluate the LHS; however, sometimes the result
4590 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4591 // Don't ignore RHS and suppress diagnostics from this arm.
4592 SuppressRHSDiags = true;
4593 }
4594
4595 return true;
4596 }
4597
4598 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4599 E->getRHS()->getType()->isIntegralOrEnumerationType());
4600
4601 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004602 return false; // Ignore RHS;
4603
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004604 return true;
4605}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004606
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004607bool DataRecursiveIntBinOpEvaluator::
4608 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4609 const BinaryOperator *E, APValue &Result) {
4610 if (E->getOpcode() == BO_Comma) {
4611 if (RHSResult.Failed)
4612 return false;
4613 Result = RHSResult.Val;
4614 return true;
4615 }
4616
4617 if (E->isLogicalOp()) {
4618 bool lhsResult, rhsResult;
4619 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4620 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4621
4622 if (LHSIsOK) {
4623 if (RHSIsOK) {
4624 if (E->getOpcode() == BO_LOr)
4625 return Success(lhsResult || rhsResult, E, Result);
4626 else
4627 return Success(lhsResult && rhsResult, E, Result);
4628 }
4629 } else {
4630 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004631 // We can't evaluate the LHS; however, sometimes the result
4632 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4633 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004634 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004635 }
4636 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004637
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004638 return false;
4639 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004640
4641 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4642 E->getRHS()->getType()->isIntegralOrEnumerationType());
4643
4644 if (LHSResult.Failed || RHSResult.Failed)
4645 return false;
4646
4647 const APValue &LHSVal = LHSResult.Val;
4648 const APValue &RHSVal = RHSResult.Val;
4649
4650 // Handle cases like (unsigned long)&a + 4.
4651 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4652 Result = LHSVal;
4653 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4654 RHSVal.getInt().getZExtValue());
4655 if (E->getOpcode() == BO_Add)
4656 Result.getLValueOffset() += AdditionalOffset;
4657 else
4658 Result.getLValueOffset() -= AdditionalOffset;
4659 return true;
4660 }
4661
4662 // Handle cases like 4 + (unsigned long)&a
4663 if (E->getOpcode() == BO_Add &&
4664 RHSVal.isLValue() && LHSVal.isInt()) {
4665 Result = RHSVal;
4666 Result.getLValueOffset() += CharUnits::fromQuantity(
4667 LHSVal.getInt().getZExtValue());
4668 return true;
4669 }
4670
4671 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4672 // Handle (intptr_t)&&A - (intptr_t)&&B.
4673 if (!LHSVal.getLValueOffset().isZero() ||
4674 !RHSVal.getLValueOffset().isZero())
4675 return false;
4676 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4677 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4678 if (!LHSExpr || !RHSExpr)
4679 return false;
4680 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4681 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4682 if (!LHSAddrExpr || !RHSAddrExpr)
4683 return false;
4684 // Make sure both labels come from the same function.
4685 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4686 RHSAddrExpr->getLabel()->getDeclContext())
4687 return false;
4688 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4689 return true;
4690 }
4691
4692 // All the following cases expect both operands to be an integer
4693 if (!LHSVal.isInt() || !RHSVal.isInt())
4694 return Error(E);
4695
4696 const APSInt &LHS = LHSVal.getInt();
4697 APSInt RHS = RHSVal.getInt();
4698
4699 switch (E->getOpcode()) {
4700 default:
4701 return Error(E);
4702 case BO_Mul:
4703 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4704 LHS.getBitWidth() * 2,
4705 std::multiplies<APSInt>()), E,
4706 Result);
4707 case BO_Add:
4708 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4709 LHS.getBitWidth() + 1,
4710 std::plus<APSInt>()), E, Result);
4711 case BO_Sub:
4712 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4713 LHS.getBitWidth() + 1,
4714 std::minus<APSInt>()), E, Result);
4715 case BO_And: return Success(LHS & RHS, E, Result);
4716 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4717 case BO_Or: return Success(LHS | RHS, E, Result);
4718 case BO_Div:
4719 case BO_Rem:
4720 if (RHS == 0)
4721 return Error(E, diag::note_expr_divide_by_zero);
4722 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4723 // not actually undefined behavior in C++11 due to a language defect.
4724 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4725 LHS.isSigned() && LHS.isMinSignedValue())
4726 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4727 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4728 Result);
4729 case BO_Shl: {
4730 // During constant-folding, a negative shift is an opposite shift. Such
4731 // a shift is not a constant expression.
4732 if (RHS.isSigned() && RHS.isNegative()) {
4733 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4734 RHS = -RHS;
4735 goto shift_right;
4736 }
4737
4738 shift_left:
4739 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4740 // the shifted type.
4741 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4742 if (SA != RHS) {
4743 CCEDiag(E, diag::note_constexpr_large_shift)
4744 << RHS << E->getType() << LHS.getBitWidth();
4745 } else if (LHS.isSigned()) {
4746 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4747 // operand, and must not overflow the corresponding unsigned type.
4748 if (LHS.isNegative())
4749 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4750 else if (LHS.countLeadingZeros() < SA)
4751 CCEDiag(E, diag::note_constexpr_lshift_discards);
4752 }
4753
4754 return Success(LHS << SA, E, Result);
4755 }
4756 case BO_Shr: {
4757 // During constant-folding, a negative shift is an opposite shift. Such a
4758 // shift is not a constant expression.
4759 if (RHS.isSigned() && RHS.isNegative()) {
4760 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4761 RHS = -RHS;
4762 goto shift_left;
4763 }
4764
4765 shift_right:
4766 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4767 // shifted type.
4768 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4769 if (SA != RHS)
4770 CCEDiag(E, diag::note_constexpr_large_shift)
4771 << RHS << E->getType() << LHS.getBitWidth();
4772
4773 return Success(LHS >> SA, E, Result);
4774 }
4775
4776 case BO_LT: return Success(LHS < RHS, E, Result);
4777 case BO_GT: return Success(LHS > RHS, E, Result);
4778 case BO_LE: return Success(LHS <= RHS, E, Result);
4779 case BO_GE: return Success(LHS >= RHS, E, Result);
4780 case BO_EQ: return Success(LHS == RHS, E, Result);
4781 case BO_NE: return Success(LHS != RHS, E, Result);
4782 }
4783}
4784
Richard Trieub7783052012-03-21 23:30:30 +00004785void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004786 Job &job = Queue.back();
4787
4788 switch (job.Kind) {
4789 case Job::AnyExprKind: {
4790 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4791 if (shouldEnqueue(Bop)) {
4792 job.Kind = Job::BinOpKind;
4793 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00004794 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004795 }
4796 }
4797
4798 EvaluateExpr(job.E, Result);
4799 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004800 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004801 }
4802
4803 case Job::BinOpKind: {
4804 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004805 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004806 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004807 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004808 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004809 }
4810 if (SuppressRHSDiags)
4811 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004812 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004813 job.Kind = Job::BinOpVisitedLHSKind;
4814 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00004815 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004816 }
4817
4818 case Job::BinOpVisitedLHSKind: {
4819 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4820 EvalResult RHS;
4821 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00004822 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004823 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004824 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004825 }
4826 }
4827
4828 llvm_unreachable("Invalid Job::Kind!");
4829}
4830
4831bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4832 if (E->isAssignmentOp())
4833 return Error(E);
4834
4835 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4836 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004837
Anders Carlsson286f85e2008-11-16 07:17:21 +00004838 QualType LHSTy = E->getLHS()->getType();
4839 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004840
4841 if (LHSTy->isAnyComplexType()) {
4842 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004843 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004844
Richard Smith745f5142012-01-27 01:14:48 +00004845 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4846 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004847 return false;
4848
Richard Smith745f5142012-01-27 01:14:48 +00004849 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004850 return false;
4851
4852 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004853 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004854 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004855 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004856 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4857
John McCall2de56d12010-08-25 11:45:40 +00004858 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004859 return Success((CR_r == APFloat::cmpEqual &&
4860 CR_i == APFloat::cmpEqual), E);
4861 else {
John McCall2de56d12010-08-25 11:45:40 +00004862 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004863 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004864 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004865 CR_r == APFloat::cmpLessThan ||
4866 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004867 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004868 CR_i == APFloat::cmpLessThan ||
4869 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004870 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004871 } else {
John McCall2de56d12010-08-25 11:45:40 +00004872 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004873 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4874 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4875 else {
John McCall2de56d12010-08-25 11:45:40 +00004876 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004877 "Invalid compex comparison.");
4878 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4879 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4880 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004881 }
4882 }
Mike Stump1eb44332009-09-09 15:08:12 +00004883
Anders Carlsson286f85e2008-11-16 07:17:21 +00004884 if (LHSTy->isRealFloatingType() &&
4885 RHSTy->isRealFloatingType()) {
4886 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004887
Richard Smith745f5142012-01-27 01:14:48 +00004888 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4889 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004890 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004891
Richard Smith745f5142012-01-27 01:14:48 +00004892 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004893 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004894
Anders Carlsson286f85e2008-11-16 07:17:21 +00004895 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004896
Anders Carlsson286f85e2008-11-16 07:17:21 +00004897 switch (E->getOpcode()) {
4898 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004899 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004900 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004901 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004902 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004903 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004904 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004905 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004906 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004907 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004908 E);
John McCall2de56d12010-08-25 11:45:40 +00004909 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004910 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004911 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004912 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004913 || CR == APFloat::cmpLessThan
4914 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004915 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004916 }
Mike Stump1eb44332009-09-09 15:08:12 +00004917
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004918 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004919 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004920 LValue LHSValue, RHSValue;
4921
4922 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4923 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004924 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004925
Richard Smith745f5142012-01-27 01:14:48 +00004926 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004927 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004928
Richard Smith625b8072011-10-31 01:37:14 +00004929 // Reject differing bases from the normal codepath; we special-case
4930 // comparisons to null.
4931 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004932 if (E->getOpcode() == BO_Sub) {
4933 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004934 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4935 return false;
4936 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4937 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4938 if (!LHSExpr || !RHSExpr)
4939 return false;
4940 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4941 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4942 if (!LHSAddrExpr || !RHSAddrExpr)
4943 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004944 // Make sure both labels come from the same function.
4945 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4946 RHSAddrExpr->getLabel()->getDeclContext())
4947 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004948 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004949 return true;
4950 }
Richard Smith9e36b532011-10-31 05:11:32 +00004951 // Inequalities and subtractions between unrelated pointers have
4952 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004953 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004954 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004955 // A constant address may compare equal to the address of a symbol.
4956 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004957 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004958 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4959 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004960 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004961 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004962 // distinct addresses. In clang, the result of such a comparison is
4963 // unspecified, so it is not a constant expression. However, we do know
4964 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004965 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4966 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004967 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004968 // We can't tell whether weak symbols will end up pointing to the same
4969 // object.
4970 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004971 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004972 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004973 // (Note that clang defaults to -fmerge-all-constants, which can
4974 // lead to inconsistent results for comparisons involving the address
4975 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004976 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004977 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004978
Richard Smith15efc4d2012-02-01 08:10:20 +00004979 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4980 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4981
Richard Smithf15fda02012-02-02 01:16:57 +00004982 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4983 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4984
John McCall2de56d12010-08-25 11:45:40 +00004985 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004986 // C++11 [expr.add]p6:
4987 // Unless both pointers point to elements of the same array object, or
4988 // one past the last element of the array object, the behavior is
4989 // undefined.
4990 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4991 !AreElementsOfSameArray(getType(LHSValue.Base),
4992 LHSDesignator, RHSDesignator))
4993 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4994
Chris Lattner4992bdd2010-04-20 17:13:14 +00004995 QualType Type = E->getLHS()->getType();
4996 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004997
Richard Smith180f4792011-11-10 06:34:14 +00004998 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004999 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00005000 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00005001
Richard Smith15efc4d2012-02-01 08:10:20 +00005002 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5003 // and produce incorrect results when it overflows. Such behavior
5004 // appears to be non-conforming, but is common, so perhaps we should
5005 // assume the standard intended for such cases to be undefined behavior
5006 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00005007
Richard Smith15efc4d2012-02-01 08:10:20 +00005008 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5009 // overflow in the final conversion to ptrdiff_t.
5010 APSInt LHS(
5011 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5012 APSInt RHS(
5013 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5014 APSInt ElemSize(
5015 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5016 APSInt TrueResult = (LHS - RHS) / ElemSize;
5017 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5018
5019 if (Result.extend(65) != TrueResult)
5020 HandleOverflow(Info, E, TrueResult, E->getType());
5021 return Success(Result, E);
5022 }
Richard Smith82f28582012-01-31 06:41:30 +00005023
5024 // C++11 [expr.rel]p3:
5025 // Pointers to void (after pointer conversions) can be compared, with a
5026 // result defined as follows: If both pointers represent the same
5027 // address or are both the null pointer value, the result is true if the
5028 // operator is <= or >= and false otherwise; otherwise the result is
5029 // unspecified.
5030 // We interpret this as applying to pointers to *cv* void.
5031 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00005032 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00005033 CCEDiag(E, diag::note_constexpr_void_comparison);
5034
Richard Smithf15fda02012-02-02 01:16:57 +00005035 // C++11 [expr.rel]p2:
5036 // - If two pointers point to non-static data members of the same object,
5037 // or to subobjects or array elements fo such members, recursively, the
5038 // pointer to the later declared member compares greater provided the
5039 // two members have the same access control and provided their class is
5040 // not a union.
5041 // [...]
5042 // - Otherwise pointer comparisons are unspecified.
5043 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5044 E->isRelationalOp()) {
5045 bool WasArrayIndex;
5046 unsigned Mismatch =
5047 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5048 RHSDesignator, WasArrayIndex);
5049 // At the point where the designators diverge, the comparison has a
5050 // specified value if:
5051 // - we are comparing array indices
5052 // - we are comparing fields of a union, or fields with the same access
5053 // Otherwise, the result is unspecified and thus the comparison is not a
5054 // constant expression.
5055 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5056 Mismatch < RHSDesignator.Entries.size()) {
5057 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5058 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5059 if (!LF && !RF)
5060 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5061 else if (!LF)
5062 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5063 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5064 << RF->getParent() << RF;
5065 else if (!RF)
5066 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5067 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5068 << LF->getParent() << LF;
5069 else if (!LF->getParent()->isUnion() &&
5070 LF->getAccess() != RF->getAccess())
5071 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5072 << LF << LF->getAccess() << RF << RF->getAccess()
5073 << LF->getParent();
5074 }
5075 }
5076
Richard Smith625b8072011-10-31 01:37:14 +00005077 switch (E->getOpcode()) {
5078 default: llvm_unreachable("missing comparison operator");
5079 case BO_LT: return Success(LHSOffset < RHSOffset, E);
5080 case BO_GT: return Success(LHSOffset > RHSOffset, E);
5081 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
5082 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
5083 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
5084 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00005085 }
Anders Carlsson3068d112008-11-16 19:01:22 +00005086 }
5087 }
Richard Smithb02e4622012-02-01 01:42:44 +00005088
5089 if (LHSTy->isMemberPointerType()) {
5090 assert(E->isEqualityOp() && "unexpected member pointer operation");
5091 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5092
5093 MemberPtr LHSValue, RHSValue;
5094
5095 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5096 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5097 return false;
5098
5099 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5100 return false;
5101
5102 // C++11 [expr.eq]p2:
5103 // If both operands are null, they compare equal. Otherwise if only one is
5104 // null, they compare unequal.
5105 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5106 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5107 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5108 }
5109
5110 // Otherwise if either is a pointer to a virtual member function, the
5111 // result is unspecified.
5112 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5113 if (MD->isVirtual())
5114 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5115 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5116 if (MD->isVirtual())
5117 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5118
5119 // Otherwise they compare equal if and only if they would refer to the
5120 // same member of the same most derived object or the same subobject if
5121 // they were dereferenced with a hypothetical object of the associated
5122 // class type.
5123 bool Equal = LHSValue == RHSValue;
5124 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5125 }
5126
Richard Smith26f2cac2012-02-14 22:35:28 +00005127 if (LHSTy->isNullPtrType()) {
5128 assert(E->isComparisonOp() && "unexpected nullptr operation");
5129 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5130 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5131 // are compared, the result is true of the operator is <=, >= or ==, and
5132 // false otherwise.
5133 BinaryOperator::Opcode Opcode = E->getOpcode();
5134 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5135 }
5136
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005137 assert((!LHSTy->isIntegralOrEnumerationType() ||
5138 !RHSTy->isIntegralOrEnumerationType()) &&
5139 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5140 // We can't continue from here for non-integral types.
5141 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005142}
5143
Ken Dyck8b752f12010-01-27 17:10:57 +00005144CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005145 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5146 // result shall be the alignment of the referenced type."
5147 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5148 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005149
5150 // __alignof is defined to return the preferred alignment.
5151 return Info.Ctx.toCharUnitsFromBits(
5152 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005153}
5154
Ken Dyck8b752f12010-01-27 17:10:57 +00005155CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005156 E = E->IgnoreParens();
5157
5158 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005159 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005160 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005161 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5162 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005163
Chris Lattneraf707ab2009-01-24 21:53:27 +00005164 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005165 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5166 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005167
Chris Lattnere9feb472009-01-24 21:09:06 +00005168 return GetAlignOfType(E->getType());
5169}
5170
5171
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005172/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5173/// a result as the expression's type.
5174bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5175 const UnaryExprOrTypeTraitExpr *E) {
5176 switch(E->getKind()) {
5177 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005178 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005179 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005180 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005181 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005182 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005183
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005184 case UETT_VecStep: {
5185 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005186
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005187 if (Ty->isVectorType()) {
5188 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005189
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005190 // The vec_step built-in functions that take a 3-component
5191 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5192 if (n == 3)
5193 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005194
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005195 return Success(n, E);
5196 } else
5197 return Success(1, E);
5198 }
5199
5200 case UETT_SizeOf: {
5201 QualType SrcTy = E->getTypeOfArgument();
5202 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5203 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005204 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5205 SrcTy = Ref->getPointeeType();
5206
Richard Smith180f4792011-11-10 06:34:14 +00005207 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005208 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005209 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005210 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005211 }
5212 }
5213
5214 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005215}
5216
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005217bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005218 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005219 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005220 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005221 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005222 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005223 for (unsigned i = 0; i != n; ++i) {
5224 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5225 switch (ON.getKind()) {
5226 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005227 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005228 APSInt IdxResult;
5229 if (!EvaluateInteger(Idx, IdxResult, Info))
5230 return false;
5231 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5232 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005233 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005234 CurrentType = AT->getElementType();
5235 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5236 Result += IdxResult.getSExtValue() * ElementSize;
5237 break;
5238 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005239
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005240 case OffsetOfExpr::OffsetOfNode::Field: {
5241 FieldDecl *MemberDecl = ON.getField();
5242 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005243 if (!RT)
5244 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005245 RecordDecl *RD = RT->getDecl();
5246 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005247 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005248 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005249 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005250 CurrentType = MemberDecl->getType().getNonReferenceType();
5251 break;
5252 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005253
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005254 case OffsetOfExpr::OffsetOfNode::Identifier:
5255 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005256
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005257 case OffsetOfExpr::OffsetOfNode::Base: {
5258 CXXBaseSpecifier *BaseSpec = ON.getBase();
5259 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005260 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005261
5262 // Find the layout of the class whose base we are looking into.
5263 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005264 if (!RT)
5265 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005266 RecordDecl *RD = RT->getDecl();
5267 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5268
5269 // Find the base class itself.
5270 CurrentType = BaseSpec->getType();
5271 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5272 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005273 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005274
5275 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005276 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005277 break;
5278 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005279 }
5280 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005281 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005282}
5283
Chris Lattnerb542afe2008-07-11 19:10:17 +00005284bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005285 switch (E->getOpcode()) {
5286 default:
5287 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5288 // See C99 6.6p3.
5289 return Error(E);
5290 case UO_Extension:
5291 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5292 // If so, we could clear the diagnostic ID.
5293 return Visit(E->getSubExpr());
5294 case UO_Plus:
5295 // The result is just the value.
5296 return Visit(E->getSubExpr());
5297 case UO_Minus: {
5298 if (!Visit(E->getSubExpr()))
5299 return false;
5300 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005301 const APSInt &Value = Result.getInt();
5302 if (Value.isSigned() && Value.isMinSignedValue())
5303 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5304 E->getType());
5305 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005306 }
5307 case UO_Not: {
5308 if (!Visit(E->getSubExpr()))
5309 return false;
5310 if (!Result.isInt()) return Error(E);
5311 return Success(~Result.getInt(), E);
5312 }
5313 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005314 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005315 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005316 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005317 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005318 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005319 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005320}
Mike Stump1eb44332009-09-09 15:08:12 +00005321
Chris Lattner732b2232008-07-12 01:15:53 +00005322/// HandleCast - This is used to evaluate implicit or explicit casts where the
5323/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005324bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5325 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005326 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005327 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005328
Eli Friedman46a52322011-03-25 00:43:55 +00005329 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005330 case CK_BaseToDerived:
5331 case CK_DerivedToBase:
5332 case CK_UncheckedDerivedToBase:
5333 case CK_Dynamic:
5334 case CK_ToUnion:
5335 case CK_ArrayToPointerDecay:
5336 case CK_FunctionToPointerDecay:
5337 case CK_NullToPointer:
5338 case CK_NullToMemberPointer:
5339 case CK_BaseToDerivedMemberPointer:
5340 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005341 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005342 case CK_ConstructorConversion:
5343 case CK_IntegralToPointer:
5344 case CK_ToVoid:
5345 case CK_VectorSplat:
5346 case CK_IntegralToFloating:
5347 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005348 case CK_CPointerToObjCPointerCast:
5349 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005350 case CK_AnyPointerToBlockPointerCast:
5351 case CK_ObjCObjectLValueCast:
5352 case CK_FloatingRealToComplex:
5353 case CK_FloatingComplexToReal:
5354 case CK_FloatingComplexCast:
5355 case CK_FloatingComplexToIntegralComplex:
5356 case CK_IntegralRealToComplex:
5357 case CK_IntegralComplexCast:
5358 case CK_IntegralComplexToFloatingComplex:
5359 llvm_unreachable("invalid cast kind for integral value");
5360
Eli Friedmane50c2972011-03-25 19:07:11 +00005361 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005362 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005363 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005364 case CK_ARCProduceObject:
5365 case CK_ARCConsumeObject:
5366 case CK_ARCReclaimReturnedObject:
5367 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005368 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005369 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005370
Richard Smith7d580a42012-01-17 21:17:26 +00005371 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005372 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005373 case CK_AtomicToNonAtomic:
5374 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005375 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005376 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005377
5378 case CK_MemberPointerToBoolean:
5379 case CK_PointerToBoolean:
5380 case CK_IntegralToBoolean:
5381 case CK_FloatingToBoolean:
5382 case CK_FloatingComplexToBoolean:
5383 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005384 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005385 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005386 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005387 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005388 }
5389
Eli Friedman46a52322011-03-25 00:43:55 +00005390 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005391 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005392 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005393
Eli Friedmanbe265702009-02-20 01:15:07 +00005394 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005395 // Allow casts of address-of-label differences if they are no-ops
5396 // or narrowing. (The narrowing case isn't actually guaranteed to
5397 // be constant-evaluatable except in some narrow cases which are hard
5398 // to detect here. We let it through on the assumption the user knows
5399 // what they are doing.)
5400 if (Result.isAddrLabelDiff())
5401 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005402 // Only allow casts of lvalues if they are lossless.
5403 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5404 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005405
Richard Smithf72fccf2012-01-30 22:27:01 +00005406 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5407 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005408 }
Mike Stump1eb44332009-09-09 15:08:12 +00005409
Eli Friedman46a52322011-03-25 00:43:55 +00005410 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005411 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5412
John McCallefdb83e2010-05-07 21:00:08 +00005413 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005414 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005415 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005416
Daniel Dunbardd211642009-02-19 22:24:01 +00005417 if (LV.getLValueBase()) {
5418 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005419 // FIXME: Allow a larger integer size than the pointer size, and allow
5420 // narrowing back down to pointer width in subsequent integral casts.
5421 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005422 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005423 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005424
Richard Smithb755a9d2011-11-16 07:18:12 +00005425 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005426 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005427 return true;
5428 }
5429
Ken Dycka7305832010-01-15 12:37:54 +00005430 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5431 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005432 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005433 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005434
Eli Friedman46a52322011-03-25 00:43:55 +00005435 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005436 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005437 if (!EvaluateComplex(SubExpr, C, Info))
5438 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005439 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005440 }
Eli Friedman2217c872009-02-22 11:46:18 +00005441
Eli Friedman46a52322011-03-25 00:43:55 +00005442 case CK_FloatingToIntegral: {
5443 APFloat F(0.0);
5444 if (!EvaluateFloat(SubExpr, F, Info))
5445 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005446
Richard Smithc1c5f272011-12-13 06:39:58 +00005447 APSInt Value;
5448 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5449 return false;
5450 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005451 }
5452 }
Mike Stump1eb44332009-09-09 15:08:12 +00005453
Eli Friedman46a52322011-03-25 00:43:55 +00005454 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005455}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005456
Eli Friedman722c7172009-02-28 03:59:05 +00005457bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5458 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005459 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005460 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5461 return false;
5462 if (!LV.isComplexInt())
5463 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005464 return Success(LV.getComplexIntReal(), E);
5465 }
5466
5467 return Visit(E->getSubExpr());
5468}
5469
Eli Friedman664a1042009-02-27 04:45:43 +00005470bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005471 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005472 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005473 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5474 return false;
5475 if (!LV.isComplexInt())
5476 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005477 return Success(LV.getComplexIntImag(), E);
5478 }
5479
Richard Smith8327fad2011-10-24 18:44:57 +00005480 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005481 return Success(0, E);
5482}
5483
Douglas Gregoree8aff02011-01-04 17:33:58 +00005484bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5485 return Success(E->getPackLength(), E);
5486}
5487
Sebastian Redl295995c2010-09-10 20:55:47 +00005488bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5489 return Success(E->getValue(), E);
5490}
5491
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005492//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005493// Float Evaluation
5494//===----------------------------------------------------------------------===//
5495
5496namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005497class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005498 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005499 APFloat &Result;
5500public:
5501 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005502 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005503
Richard Smith1aa0be82012-03-03 22:46:17 +00005504 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005505 Result = V.getFloat();
5506 return true;
5507 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005508
Richard Smith51201882011-12-30 21:15:51 +00005509 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005510 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5511 return true;
5512 }
5513
Chris Lattner019f4e82008-10-06 05:28:25 +00005514 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005515
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005516 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005517 bool VisitBinaryOperator(const BinaryOperator *E);
5518 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005519 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005520
John McCallabd3a852010-05-07 22:08:54 +00005521 bool VisitUnaryReal(const UnaryOperator *E);
5522 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005523
Richard Smith51201882011-12-30 21:15:51 +00005524 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005525};
5526} // end anonymous namespace
5527
5528static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005529 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005530 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005531}
5532
Jay Foad4ba2a172011-01-12 09:06:06 +00005533static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005534 QualType ResultTy,
5535 const Expr *Arg,
5536 bool SNaN,
5537 llvm::APFloat &Result) {
5538 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5539 if (!S) return false;
5540
5541 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5542
5543 llvm::APInt fill;
5544
5545 // Treat empty strings as if they were zero.
5546 if (S->getString().empty())
5547 fill = llvm::APInt(32, 0);
5548 else if (S->getString().getAsInteger(0, fill))
5549 return false;
5550
5551 if (SNaN)
5552 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5553 else
5554 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5555 return true;
5556}
5557
Chris Lattner019f4e82008-10-06 05:28:25 +00005558bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005559 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005560 default:
5561 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5562
Chris Lattner019f4e82008-10-06 05:28:25 +00005563 case Builtin::BI__builtin_huge_val:
5564 case Builtin::BI__builtin_huge_valf:
5565 case Builtin::BI__builtin_huge_vall:
5566 case Builtin::BI__builtin_inf:
5567 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005568 case Builtin::BI__builtin_infl: {
5569 const llvm::fltSemantics &Sem =
5570 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005571 Result = llvm::APFloat::getInf(Sem);
5572 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005573 }
Mike Stump1eb44332009-09-09 15:08:12 +00005574
John McCalldb7b72a2010-02-28 13:00:19 +00005575 case Builtin::BI__builtin_nans:
5576 case Builtin::BI__builtin_nansf:
5577 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005578 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5579 true, Result))
5580 return Error(E);
5581 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005582
Chris Lattner9e621712008-10-06 06:31:58 +00005583 case Builtin::BI__builtin_nan:
5584 case Builtin::BI__builtin_nanf:
5585 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005586 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005587 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005588 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5589 false, Result))
5590 return Error(E);
5591 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005592
5593 case Builtin::BI__builtin_fabs:
5594 case Builtin::BI__builtin_fabsf:
5595 case Builtin::BI__builtin_fabsl:
5596 if (!EvaluateFloat(E->getArg(0), Result, Info))
5597 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005598
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005599 if (Result.isNegative())
5600 Result.changeSign();
5601 return true;
5602
Mike Stump1eb44332009-09-09 15:08:12 +00005603 case Builtin::BI__builtin_copysign:
5604 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005605 case Builtin::BI__builtin_copysignl: {
5606 APFloat RHS(0.);
5607 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5608 !EvaluateFloat(E->getArg(1), RHS, Info))
5609 return false;
5610 Result.copySign(RHS);
5611 return true;
5612 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005613 }
5614}
5615
John McCallabd3a852010-05-07 22:08:54 +00005616bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005617 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5618 ComplexValue CV;
5619 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5620 return false;
5621 Result = CV.FloatReal;
5622 return true;
5623 }
5624
5625 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005626}
5627
5628bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005629 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5630 ComplexValue CV;
5631 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5632 return false;
5633 Result = CV.FloatImag;
5634 return true;
5635 }
5636
Richard Smith8327fad2011-10-24 18:44:57 +00005637 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005638 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5639 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005640 return true;
5641}
5642
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005643bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005644 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005645 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005646 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005647 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005648 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005649 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5650 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005651 Result.changeSign();
5652 return true;
5653 }
5654}
Chris Lattner019f4e82008-10-06 05:28:25 +00005655
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005656bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005657 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5658 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005659
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005660 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005661 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5662 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005663 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005664 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005665 return false;
5666
5667 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005668 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005669 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005670 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005671 break;
John McCall2de56d12010-08-25 11:45:40 +00005672 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005673 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005674 break;
John McCall2de56d12010-08-25 11:45:40 +00005675 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005676 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005677 break;
John McCall2de56d12010-08-25 11:45:40 +00005678 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005679 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005680 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005681 }
Richard Smith7b48a292012-02-01 05:53:12 +00005682
5683 if (Result.isInfinity() || Result.isNaN())
5684 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5685 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005686}
5687
5688bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5689 Result = E->getValue();
5690 return true;
5691}
5692
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005693bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5694 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005695
Eli Friedman2a523ee2011-03-25 00:54:52 +00005696 switch (E->getCastKind()) {
5697 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005698 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005699
5700 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005701 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005702 return EvaluateInteger(SubExpr, IntResult, Info) &&
5703 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5704 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005705 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005706
5707 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005708 if (!Visit(SubExpr))
5709 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005710 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5711 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005712 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005713
Eli Friedman2a523ee2011-03-25 00:54:52 +00005714 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005715 ComplexValue V;
5716 if (!EvaluateComplex(SubExpr, V, Info))
5717 return false;
5718 Result = V.getComplexFloatReal();
5719 return true;
5720 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005721 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005722}
5723
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005724//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005725// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005726//===----------------------------------------------------------------------===//
5727
5728namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005729class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005730 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005731 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005732
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005733public:
John McCallf4cf1a12010-05-07 17:22:02 +00005734 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005735 : ExprEvaluatorBaseTy(info), Result(Result) {}
5736
Richard Smith1aa0be82012-03-03 22:46:17 +00005737 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005738 Result.setFrom(V);
5739 return true;
5740 }
Mike Stump1eb44332009-09-09 15:08:12 +00005741
Eli Friedman7ead5c72012-01-10 04:58:17 +00005742 bool ZeroInitialization(const Expr *E);
5743
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005744 //===--------------------------------------------------------------------===//
5745 // Visitor Methods
5746 //===--------------------------------------------------------------------===//
5747
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005748 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005749 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005750 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005751 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005752 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005753};
5754} // end anonymous namespace
5755
John McCallf4cf1a12010-05-07 17:22:02 +00005756static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5757 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005758 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005759 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005760}
5761
Eli Friedman7ead5c72012-01-10 04:58:17 +00005762bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005763 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005764 if (ElemTy->isRealFloatingType()) {
5765 Result.makeComplexFloat();
5766 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5767 Result.FloatReal = Zero;
5768 Result.FloatImag = Zero;
5769 } else {
5770 Result.makeComplexInt();
5771 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5772 Result.IntReal = Zero;
5773 Result.IntImag = Zero;
5774 }
5775 return true;
5776}
5777
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005778bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5779 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005780
5781 if (SubExpr->getType()->isRealFloatingType()) {
5782 Result.makeComplexFloat();
5783 APFloat &Imag = Result.FloatImag;
5784 if (!EvaluateFloat(SubExpr, Imag, Info))
5785 return false;
5786
5787 Result.FloatReal = APFloat(Imag.getSemantics());
5788 return true;
5789 } else {
5790 assert(SubExpr->getType()->isIntegerType() &&
5791 "Unexpected imaginary literal.");
5792
5793 Result.makeComplexInt();
5794 APSInt &Imag = Result.IntImag;
5795 if (!EvaluateInteger(SubExpr, Imag, Info))
5796 return false;
5797
5798 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5799 return true;
5800 }
5801}
5802
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005803bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005804
John McCall8786da72010-12-14 17:51:41 +00005805 switch (E->getCastKind()) {
5806 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005807 case CK_BaseToDerived:
5808 case CK_DerivedToBase:
5809 case CK_UncheckedDerivedToBase:
5810 case CK_Dynamic:
5811 case CK_ToUnion:
5812 case CK_ArrayToPointerDecay:
5813 case CK_FunctionToPointerDecay:
5814 case CK_NullToPointer:
5815 case CK_NullToMemberPointer:
5816 case CK_BaseToDerivedMemberPointer:
5817 case CK_DerivedToBaseMemberPointer:
5818 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005819 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005820 case CK_ConstructorConversion:
5821 case CK_IntegralToPointer:
5822 case CK_PointerToIntegral:
5823 case CK_PointerToBoolean:
5824 case CK_ToVoid:
5825 case CK_VectorSplat:
5826 case CK_IntegralCast:
5827 case CK_IntegralToBoolean:
5828 case CK_IntegralToFloating:
5829 case CK_FloatingToIntegral:
5830 case CK_FloatingToBoolean:
5831 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005832 case CK_CPointerToObjCPointerCast:
5833 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005834 case CK_AnyPointerToBlockPointerCast:
5835 case CK_ObjCObjectLValueCast:
5836 case CK_FloatingComplexToReal:
5837 case CK_FloatingComplexToBoolean:
5838 case CK_IntegralComplexToReal:
5839 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005840 case CK_ARCProduceObject:
5841 case CK_ARCConsumeObject:
5842 case CK_ARCReclaimReturnedObject:
5843 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005844 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005845 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005846
John McCall8786da72010-12-14 17:51:41 +00005847 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005848 case CK_AtomicToNonAtomic:
5849 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005850 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005851 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005852
5853 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005854 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005855 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005856 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005857
5858 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005859 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005860 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005861 return false;
5862
John McCall8786da72010-12-14 17:51:41 +00005863 Result.makeComplexFloat();
5864 Result.FloatImag = APFloat(Real.getSemantics());
5865 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005866 }
5867
John McCall8786da72010-12-14 17:51:41 +00005868 case CK_FloatingComplexCast: {
5869 if (!Visit(E->getSubExpr()))
5870 return false;
5871
5872 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5873 QualType From
5874 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5875
Richard Smithc1c5f272011-12-13 06:39:58 +00005876 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5877 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005878 }
5879
5880 case CK_FloatingComplexToIntegralComplex: {
5881 if (!Visit(E->getSubExpr()))
5882 return false;
5883
5884 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5885 QualType From
5886 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5887 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005888 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5889 To, Result.IntReal) &&
5890 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5891 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005892 }
5893
5894 case CK_IntegralRealToComplex: {
5895 APSInt &Real = Result.IntReal;
5896 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5897 return false;
5898
5899 Result.makeComplexInt();
5900 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5901 return true;
5902 }
5903
5904 case CK_IntegralComplexCast: {
5905 if (!Visit(E->getSubExpr()))
5906 return false;
5907
5908 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5909 QualType From
5910 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5911
Richard Smithf72fccf2012-01-30 22:27:01 +00005912 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5913 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005914 return true;
5915 }
5916
5917 case CK_IntegralComplexToFloatingComplex: {
5918 if (!Visit(E->getSubExpr()))
5919 return false;
5920
5921 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5922 QualType From
5923 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5924 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005925 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5926 To, Result.FloatReal) &&
5927 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5928 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005929 }
5930 }
5931
5932 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005933}
5934
John McCallf4cf1a12010-05-07 17:22:02 +00005935bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005936 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005937 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5938
Richard Smith745f5142012-01-27 01:14:48 +00005939 bool LHSOK = Visit(E->getLHS());
5940 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005941 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005942
John McCallf4cf1a12010-05-07 17:22:02 +00005943 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005944 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005945 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005946
Daniel Dunbar3f279872009-01-29 01:32:56 +00005947 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5948 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005949 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005950 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005951 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005952 if (Result.isComplexFloat()) {
5953 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5954 APFloat::rmNearestTiesToEven);
5955 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5956 APFloat::rmNearestTiesToEven);
5957 } else {
5958 Result.getComplexIntReal() += RHS.getComplexIntReal();
5959 Result.getComplexIntImag() += RHS.getComplexIntImag();
5960 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005961 break;
John McCall2de56d12010-08-25 11:45:40 +00005962 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005963 if (Result.isComplexFloat()) {
5964 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5965 APFloat::rmNearestTiesToEven);
5966 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5967 APFloat::rmNearestTiesToEven);
5968 } else {
5969 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5970 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5971 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005972 break;
John McCall2de56d12010-08-25 11:45:40 +00005973 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005974 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005975 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005976 APFloat &LHS_r = LHS.getComplexFloatReal();
5977 APFloat &LHS_i = LHS.getComplexFloatImag();
5978 APFloat &RHS_r = RHS.getComplexFloatReal();
5979 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005980
Daniel Dunbar3f279872009-01-29 01:32:56 +00005981 APFloat Tmp = LHS_r;
5982 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5983 Result.getComplexFloatReal() = Tmp;
5984 Tmp = LHS_i;
5985 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5986 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5987
5988 Tmp = LHS_r;
5989 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5990 Result.getComplexFloatImag() = Tmp;
5991 Tmp = LHS_i;
5992 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5993 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5994 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005995 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005996 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005997 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5998 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005999 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006000 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6001 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6002 }
6003 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006004 case BO_Div:
6005 if (Result.isComplexFloat()) {
6006 ComplexValue LHS = Result;
6007 APFloat &LHS_r = LHS.getComplexFloatReal();
6008 APFloat &LHS_i = LHS.getComplexFloatImag();
6009 APFloat &RHS_r = RHS.getComplexFloatReal();
6010 APFloat &RHS_i = RHS.getComplexFloatImag();
6011 APFloat &Res_r = Result.getComplexFloatReal();
6012 APFloat &Res_i = Result.getComplexFloatImag();
6013
6014 APFloat Den = RHS_r;
6015 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6016 APFloat Tmp = RHS_i;
6017 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6018 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6019
6020 Res_r = LHS_r;
6021 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6022 Tmp = LHS_i;
6023 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6024 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6025 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6026
6027 Res_i = LHS_i;
6028 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6029 Tmp = LHS_r;
6030 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6031 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6032 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6033 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00006034 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6035 return Error(E, diag::note_expr_divide_by_zero);
6036
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006037 ComplexValue LHS = Result;
6038 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6039 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6040 Result.getComplexIntReal() =
6041 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6042 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6043 Result.getComplexIntImag() =
6044 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6045 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6046 }
6047 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006048 }
6049
John McCallf4cf1a12010-05-07 17:22:02 +00006050 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006051}
6052
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006053bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6054 // Get the operand value into 'Result'.
6055 if (!Visit(E->getSubExpr()))
6056 return false;
6057
6058 switch (E->getOpcode()) {
6059 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00006060 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006061 case UO_Extension:
6062 return true;
6063 case UO_Plus:
6064 // The result is always just the subexpr.
6065 return true;
6066 case UO_Minus:
6067 if (Result.isComplexFloat()) {
6068 Result.getComplexFloatReal().changeSign();
6069 Result.getComplexFloatImag().changeSign();
6070 }
6071 else {
6072 Result.getComplexIntReal() = -Result.getComplexIntReal();
6073 Result.getComplexIntImag() = -Result.getComplexIntImag();
6074 }
6075 return true;
6076 case UO_Not:
6077 if (Result.isComplexFloat())
6078 Result.getComplexFloatImag().changeSign();
6079 else
6080 Result.getComplexIntImag() = -Result.getComplexIntImag();
6081 return true;
6082 }
6083}
6084
Eli Friedman7ead5c72012-01-10 04:58:17 +00006085bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6086 if (E->getNumInits() == 2) {
6087 if (E->getType()->isComplexType()) {
6088 Result.makeComplexFloat();
6089 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6090 return false;
6091 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6092 return false;
6093 } else {
6094 Result.makeComplexInt();
6095 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6096 return false;
6097 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6098 return false;
6099 }
6100 return true;
6101 }
6102 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6103}
6104
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00006105//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00006106// Void expression evaluation, primarily for a cast to void on the LHS of a
6107// comma operator
6108//===----------------------------------------------------------------------===//
6109
6110namespace {
6111class VoidExprEvaluator
6112 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6113public:
6114 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6115
Richard Smith1aa0be82012-03-03 22:46:17 +00006116 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00006117
6118 bool VisitCastExpr(const CastExpr *E) {
6119 switch (E->getCastKind()) {
6120 default:
6121 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6122 case CK_ToVoid:
6123 VisitIgnoredValue(E->getSubExpr());
6124 return true;
6125 }
6126 }
6127};
6128} // end anonymous namespace
6129
6130static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6131 assert(E->isRValue() && E->getType()->isVoidType());
6132 return VoidExprEvaluator(Info).Visit(E);
6133}
6134
6135//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006136// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006137//===----------------------------------------------------------------------===//
6138
Richard Smith1aa0be82012-03-03 22:46:17 +00006139static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006140 // In C, function designators are not lvalues, but we evaluate them as if they
6141 // are.
6142 if (E->isGLValue() || E->getType()->isFunctionType()) {
6143 LValue LV;
6144 if (!EvaluateLValue(E, LV, Info))
6145 return false;
6146 LV.moveInto(Result);
6147 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006148 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006149 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006150 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006151 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006152 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006153 } else if (E->getType()->hasPointerRepresentation()) {
6154 LValue LV;
6155 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006156 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006157 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006158 } else if (E->getType()->isRealFloatingType()) {
6159 llvm::APFloat F(0.0);
6160 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006161 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006162 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006163 } else if (E->getType()->isAnyComplexType()) {
6164 ComplexValue C;
6165 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006166 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006167 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006168 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006169 MemberPtr P;
6170 if (!EvaluateMemberPointer(E, P, Info))
6171 return false;
6172 P.moveInto(Result);
6173 return true;
Richard Smith51201882011-12-30 21:15:51 +00006174 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006175 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006176 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006177 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006178 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006179 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006180 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006181 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006182 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006183 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6184 return false;
6185 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006186 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00006187 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006188 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00006189 << E->getType();
6190 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00006191 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00006192 if (!EvaluateVoid(E, Info))
6193 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006194 } else if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006195 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006196 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006197 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006198 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006199 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006200 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006201
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006202 return true;
6203}
6204
Richard Smith83587db2012-02-15 02:18:13 +00006205/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6206/// cases, the in-place evaluation is essential, since later initializers for
6207/// an object can indirectly refer to subobjects which were initialized earlier.
6208static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6209 const Expr *E, CheckConstantExpressionKind CCEK,
6210 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006211 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006212 return false;
6213
6214 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006215 // Evaluate arrays and record types in-place, so that later initializers can
6216 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006217 if (E->getType()->isArrayType())
6218 return EvaluateArray(E, This, Result, Info);
6219 else if (E->getType()->isRecordType())
6220 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006221 }
6222
6223 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006224 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006225}
6226
Richard Smithf48fdb02011-12-09 22:58:01 +00006227/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6228/// lvalue-to-rvalue cast if it is an lvalue.
6229static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006230 if (!CheckLiteralType(Info, E))
6231 return false;
6232
Richard Smith1aa0be82012-03-03 22:46:17 +00006233 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006234 return false;
6235
6236 if (E->isGLValue()) {
6237 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006238 LV.setFrom(Info.Ctx, Result);
6239 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006240 return false;
6241 }
6242
Richard Smith1aa0be82012-03-03 22:46:17 +00006243 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006244 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006245}
Richard Smithc49bd112011-10-28 17:51:58 +00006246
Richard Smith51f47082011-10-29 00:50:52 +00006247/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006248/// any crazy technique (that has nothing to do with language standards) that
6249/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006250/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6251/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006252bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006253 // Fast-path evaluations of integer literals, since we sometimes see files
6254 // containing vast quantities of these.
6255 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6256 Result.Val = APValue(APSInt(L->getValue(),
6257 L->getType()->isUnsignedIntegerType()));
6258 return true;
6259 }
6260
Richard Smith2d6a5672012-01-14 04:30:29 +00006261 // FIXME: Evaluating values of large array and record types can cause
6262 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006263 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006264 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006265 return false;
6266
Richard Smithf48fdb02011-12-09 22:58:01 +00006267 EvalInfo Info(Ctx, Result);
6268 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006269}
6270
Jay Foad4ba2a172011-01-12 09:06:06 +00006271bool Expr::EvaluateAsBooleanCondition(bool &Result,
6272 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006273 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006274 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006275 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006276}
6277
Richard Smith80d4b552011-12-28 19:48:30 +00006278bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6279 SideEffectsKind AllowSideEffects) const {
6280 if (!getType()->isIntegralOrEnumerationType())
6281 return false;
6282
Richard Smithc49bd112011-10-28 17:51:58 +00006283 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006284 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6285 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006286 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006287
Richard Smithc49bd112011-10-28 17:51:58 +00006288 Result = ExprResult.Val.getInt();
6289 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006290}
6291
Jay Foad4ba2a172011-01-12 09:06:06 +00006292bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006293 EvalInfo Info(Ctx, Result);
6294
John McCallefdb83e2010-05-07 21:00:08 +00006295 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006296 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6297 !CheckLValueConstantExpression(Info, getExprLoc(),
6298 Ctx.getLValueReferenceType(getType()), LV))
6299 return false;
6300
Richard Smith1aa0be82012-03-03 22:46:17 +00006301 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006302 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006303}
6304
Richard Smith099e7f62011-12-19 06:19:21 +00006305bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6306 const VarDecl *VD,
6307 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006308 // FIXME: Evaluating initializers for large array and record types can cause
6309 // performance problems. Only do so in C++11 for now.
6310 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006311 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith2d6a5672012-01-14 04:30:29 +00006312 return false;
6313
Richard Smith099e7f62011-12-19 06:19:21 +00006314 Expr::EvalStatus EStatus;
6315 EStatus.Diag = &Notes;
6316
6317 EvalInfo InitInfo(Ctx, EStatus);
6318 InitInfo.setEvaluatingDecl(VD, Value);
6319
6320 LValue LVal;
6321 LVal.set(VD);
6322
Richard Smith51201882011-12-30 21:15:51 +00006323 // C++11 [basic.start.init]p2:
6324 // Variables with static storage duration or thread storage duration shall be
6325 // zero-initialized before any other initialization takes place.
6326 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006327 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006328 !VD->getType()->isReferenceType()) {
6329 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006330 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6331 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006332 return false;
6333 }
6334
Richard Smith83587db2012-02-15 02:18:13 +00006335 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6336 /*AllowNonLiteralTypes=*/true) ||
6337 EStatus.HasSideEffects)
6338 return false;
6339
6340 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6341 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006342}
6343
Richard Smith51f47082011-10-29 00:50:52 +00006344/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6345/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006346bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006347 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006348 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006349}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006350
Jay Foad4ba2a172011-01-12 09:06:06 +00006351bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006352 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006353}
6354
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006355APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006356 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006357 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006358 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006359 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006360 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006361
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006362 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006363}
John McCalld905f5a2010-05-07 05:32:02 +00006364
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006365 bool Expr::EvalResult::isGlobalLValue() const {
6366 assert(Val.isLValue());
6367 return IsGlobalLValue(Val.getLValueBase());
6368 }
6369
6370
John McCalld905f5a2010-05-07 05:32:02 +00006371/// isIntegerConstantExpr - this recursive routine will test if an expression is
6372/// an integer constant expression.
6373
6374/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6375/// comma, etc
6376///
6377/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6378/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6379/// cast+dereference.
6380
6381// CheckICE - This function does the fundamental ICE checking: the returned
6382// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6383// Note that to reduce code duplication, this helper does no evaluation
6384// itself; the caller checks whether the expression is evaluatable, and
6385// in the rare cases where CheckICE actually cares about the evaluated
6386// value, it calls into Evalute.
6387//
6388// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006389// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006390// 1: This expression is not an ICE, but if it isn't evaluated, it's
6391// a legal subexpression for an ICE. This return value is used to handle
6392// the comma operator in C99 mode.
6393// 2: This expression is not an ICE, and is not a legal subexpression for one.
6394
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006395namespace {
6396
John McCalld905f5a2010-05-07 05:32:02 +00006397struct ICEDiag {
6398 unsigned Val;
6399 SourceLocation Loc;
6400
6401 public:
6402 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6403 ICEDiag() : Val(0) {}
6404};
6405
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006406}
6407
6408static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006409
6410static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6411 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006412 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006413 !EVResult.Val.isInt()) {
6414 return ICEDiag(2, E->getLocStart());
6415 }
6416 return NoDiag();
6417}
6418
6419static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6420 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006421 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006422 return ICEDiag(2, E->getLocStart());
6423 }
6424
6425 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006426#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006427#define STMT(Node, Base) case Expr::Node##Class:
6428#define EXPR(Node, Base)
6429#include "clang/AST/StmtNodes.inc"
6430 case Expr::PredefinedExprClass:
6431 case Expr::FloatingLiteralClass:
6432 case Expr::ImaginaryLiteralClass:
6433 case Expr::StringLiteralClass:
6434 case Expr::ArraySubscriptExprClass:
6435 case Expr::MemberExprClass:
6436 case Expr::CompoundAssignOperatorClass:
6437 case Expr::CompoundLiteralExprClass:
6438 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006439 case Expr::DesignatedInitExprClass:
6440 case Expr::ImplicitValueInitExprClass:
6441 case Expr::ParenListExprClass:
6442 case Expr::VAArgExprClass:
6443 case Expr::AddrLabelExprClass:
6444 case Expr::StmtExprClass:
6445 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006446 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006447 case Expr::CXXDynamicCastExprClass:
6448 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006449 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006450 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006451 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006452 case Expr::CXXThisExprClass:
6453 case Expr::CXXThrowExprClass:
6454 case Expr::CXXNewExprClass:
6455 case Expr::CXXDeleteExprClass:
6456 case Expr::CXXPseudoDestructorExprClass:
6457 case Expr::UnresolvedLookupExprClass:
6458 case Expr::DependentScopeDeclRefExprClass:
6459 case Expr::CXXConstructExprClass:
6460 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006461 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006462 case Expr::CXXTemporaryObjectExprClass:
6463 case Expr::CXXUnresolvedConstructExprClass:
6464 case Expr::CXXDependentScopeMemberExprClass:
6465 case Expr::UnresolvedMemberExprClass:
6466 case Expr::ObjCStringLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006467 case Expr::ObjCNumericLiteralClass:
6468 case Expr::ObjCArrayLiteralClass:
6469 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006470 case Expr::ObjCEncodeExprClass:
6471 case Expr::ObjCMessageExprClass:
6472 case Expr::ObjCSelectorExprClass:
6473 case Expr::ObjCProtocolExprClass:
6474 case Expr::ObjCIvarRefExprClass:
6475 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006476 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006477 case Expr::ObjCIsaExprClass:
6478 case Expr::ShuffleVectorExprClass:
6479 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006480 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006481 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006482 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006483 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006484 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006485 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006486 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006487 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006488 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006489 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006490 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006491 return ICEDiag(2, E->getLocStart());
6492
Douglas Gregoree8aff02011-01-04 17:33:58 +00006493 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006494 case Expr::GNUNullExprClass:
6495 // GCC considers the GNU __null value to be an integral constant expression.
6496 return NoDiag();
6497
John McCall91a57552011-07-15 05:09:51 +00006498 case Expr::SubstNonTypeTemplateParmExprClass:
6499 return
6500 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6501
John McCalld905f5a2010-05-07 05:32:02 +00006502 case Expr::ParenExprClass:
6503 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006504 case Expr::GenericSelectionExprClass:
6505 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006506 case Expr::IntegerLiteralClass:
6507 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006508 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006509 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006510 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006511 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006512 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006513 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006514 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006515 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006516 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006517 return NoDiag();
6518 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006519 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006520 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6521 // constant expressions, but they can never be ICEs because an ICE cannot
6522 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006523 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006524 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006525 return CheckEvalInICE(E, Ctx);
6526 return ICEDiag(2, E->getLocStart());
6527 }
Richard Smith359c89d2012-02-24 22:12:32 +00006528 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006529 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6530 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006531 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006532 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006533 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006534 // Parameter variables are never constants. Without this check,
6535 // getAnyInitializer() can find a default argument, which leads
6536 // to chaos.
6537 if (isa<ParmVarDecl>(D))
6538 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6539
6540 // C++ 7.1.5.1p2
6541 // A variable of non-volatile const-qualified integral or enumeration
6542 // type initialized by an ICE can be used in ICEs.
6543 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006544 if (!Dcl->getType()->isIntegralOrEnumerationType())
6545 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6546
Richard Smith099e7f62011-12-19 06:19:21 +00006547 const VarDecl *VD;
6548 // Look for a declaration of this variable that has an initializer, and
6549 // check whether it is an ICE.
6550 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6551 return NoDiag();
6552 else
6553 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006554 }
6555 }
6556 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006557 }
John McCalld905f5a2010-05-07 05:32:02 +00006558 case Expr::UnaryOperatorClass: {
6559 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6560 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006561 case UO_PostInc:
6562 case UO_PostDec:
6563 case UO_PreInc:
6564 case UO_PreDec:
6565 case UO_AddrOf:
6566 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006567 // C99 6.6/3 allows increment and decrement within unevaluated
6568 // subexpressions of constant expressions, but they can never be ICEs
6569 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006570 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006571 case UO_Extension:
6572 case UO_LNot:
6573 case UO_Plus:
6574 case UO_Minus:
6575 case UO_Not:
6576 case UO_Real:
6577 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006578 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006579 }
6580
6581 // OffsetOf falls through here.
6582 }
6583 case Expr::OffsetOfExprClass: {
6584 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006585 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006586 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006587 // compliance: we should warn earlier for offsetof expressions with
6588 // array subscripts that aren't ICEs, and if the array subscripts
6589 // are ICEs, the value of the offsetof must be an integer constant.
6590 return CheckEvalInICE(E, Ctx);
6591 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006592 case Expr::UnaryExprOrTypeTraitExprClass: {
6593 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6594 if ((Exp->getKind() == UETT_SizeOf) &&
6595 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006596 return ICEDiag(2, E->getLocStart());
6597 return NoDiag();
6598 }
6599 case Expr::BinaryOperatorClass: {
6600 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6601 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006602 case BO_PtrMemD:
6603 case BO_PtrMemI:
6604 case BO_Assign:
6605 case BO_MulAssign:
6606 case BO_DivAssign:
6607 case BO_RemAssign:
6608 case BO_AddAssign:
6609 case BO_SubAssign:
6610 case BO_ShlAssign:
6611 case BO_ShrAssign:
6612 case BO_AndAssign:
6613 case BO_XorAssign:
6614 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006615 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6616 // constant expressions, but they can never be ICEs because an ICE cannot
6617 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006618 return ICEDiag(2, E->getLocStart());
6619
John McCall2de56d12010-08-25 11:45:40 +00006620 case BO_Mul:
6621 case BO_Div:
6622 case BO_Rem:
6623 case BO_Add:
6624 case BO_Sub:
6625 case BO_Shl:
6626 case BO_Shr:
6627 case BO_LT:
6628 case BO_GT:
6629 case BO_LE:
6630 case BO_GE:
6631 case BO_EQ:
6632 case BO_NE:
6633 case BO_And:
6634 case BO_Xor:
6635 case BO_Or:
6636 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006637 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6638 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006639 if (Exp->getOpcode() == BO_Div ||
6640 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006641 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006642 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006643 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006644 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006645 if (REval == 0)
6646 return ICEDiag(1, E->getLocStart());
6647 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006648 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006649 if (LEval.isMinSignedValue())
6650 return ICEDiag(1, E->getLocStart());
6651 }
6652 }
6653 }
John McCall2de56d12010-08-25 11:45:40 +00006654 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006655 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006656 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6657 // if it isn't evaluated.
6658 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6659 return ICEDiag(1, E->getLocStart());
6660 } else {
6661 // In both C89 and C++, commas in ICEs are illegal.
6662 return ICEDiag(2, E->getLocStart());
6663 }
6664 }
6665 if (LHSResult.Val >= RHSResult.Val)
6666 return LHSResult;
6667 return RHSResult;
6668 }
John McCall2de56d12010-08-25 11:45:40 +00006669 case BO_LAnd:
6670 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006671 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6672 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6673 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6674 // Rare case where the RHS has a comma "side-effect"; we need
6675 // to actually check the condition to see whether the side
6676 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006677 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006678 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006679 return RHSResult;
6680 return NoDiag();
6681 }
6682
6683 if (LHSResult.Val >= RHSResult.Val)
6684 return LHSResult;
6685 return RHSResult;
6686 }
6687 }
6688 }
6689 case Expr::ImplicitCastExprClass:
6690 case Expr::CStyleCastExprClass:
6691 case Expr::CXXFunctionalCastExprClass:
6692 case Expr::CXXStaticCastExprClass:
6693 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006694 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006695 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006696 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006697 if (isa<ExplicitCastExpr>(E)) {
6698 if (const FloatingLiteral *FL
6699 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6700 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6701 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6702 APSInt IgnoredVal(DestWidth, !DestSigned);
6703 bool Ignored;
6704 // If the value does not fit in the destination type, the behavior is
6705 // undefined, so we are not required to treat it as a constant
6706 // expression.
6707 if (FL->getValue().convertToInteger(IgnoredVal,
6708 llvm::APFloat::rmTowardZero,
6709 &Ignored) & APFloat::opInvalidOp)
6710 return ICEDiag(2, E->getLocStart());
6711 return NoDiag();
6712 }
6713 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006714 switch (cast<CastExpr>(E)->getCastKind()) {
6715 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006716 case CK_AtomicToNonAtomic:
6717 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006718 case CK_NoOp:
6719 case CK_IntegralToBoolean:
6720 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006721 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006722 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006723 return ICEDiag(2, E->getLocStart());
6724 }
John McCalld905f5a2010-05-07 05:32:02 +00006725 }
John McCall56ca35d2011-02-17 10:25:35 +00006726 case Expr::BinaryConditionalOperatorClass: {
6727 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6728 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6729 if (CommonResult.Val == 2) return CommonResult;
6730 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6731 if (FalseResult.Val == 2) return FalseResult;
6732 if (CommonResult.Val == 1) return CommonResult;
6733 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006734 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006735 return FalseResult;
6736 }
John McCalld905f5a2010-05-07 05:32:02 +00006737 case Expr::ConditionalOperatorClass: {
6738 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6739 // If the condition (ignoring parens) is a __builtin_constant_p call,
6740 // then only the true side is actually considered in an integer constant
6741 // expression, and it is fully evaluated. This is an important GNU
6742 // extension. See GCC PR38377 for discussion.
6743 if (const CallExpr *CallCE
6744 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006745 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6746 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006747 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006748 if (CondResult.Val == 2)
6749 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006750
Richard Smithf48fdb02011-12-09 22:58:01 +00006751 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6752 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006753
John McCalld905f5a2010-05-07 05:32:02 +00006754 if (TrueResult.Val == 2)
6755 return TrueResult;
6756 if (FalseResult.Val == 2)
6757 return FalseResult;
6758 if (CondResult.Val == 1)
6759 return CondResult;
6760 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6761 return NoDiag();
6762 // Rare case where the diagnostics depend on which side is evaluated
6763 // Note that if we get here, CondResult is 0, and at least one of
6764 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006765 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006766 return FalseResult;
6767 }
6768 return TrueResult;
6769 }
6770 case Expr::CXXDefaultArgExprClass:
6771 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6772 case Expr::ChooseExprClass: {
6773 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6774 }
6775 }
6776
David Blaikie30263482012-01-20 21:50:17 +00006777 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006778}
6779
Richard Smithf48fdb02011-12-09 22:58:01 +00006780/// Evaluate an expression as a C++11 integral constant expression.
6781static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6782 const Expr *E,
6783 llvm::APSInt *Value,
6784 SourceLocation *Loc) {
6785 if (!E->getType()->isIntegralOrEnumerationType()) {
6786 if (Loc) *Loc = E->getExprLoc();
6787 return false;
6788 }
6789
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006790 APValue Result;
6791 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006792 return false;
6793
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006794 assert(Result.isInt() && "pointer cast to int is not an ICE");
6795 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006796 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006797}
6798
Richard Smithdd1f29b2011-12-12 09:28:41 +00006799bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006800 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006801 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6802
John McCalld905f5a2010-05-07 05:32:02 +00006803 ICEDiag d = CheckICE(this, Ctx);
6804 if (d.Val != 0) {
6805 if (Loc) *Loc = d.Loc;
6806 return false;
6807 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006808 return true;
6809}
6810
6811bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6812 SourceLocation *Loc, bool isEvaluated) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006813 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006814 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6815
6816 if (!isIntegerConstantExpr(Ctx, Loc))
6817 return false;
6818 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006819 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006820 return true;
6821}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006822
Richard Smith70488e22012-02-14 21:38:30 +00006823bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6824 return CheckICE(this, Ctx).Val == 0;
6825}
6826
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006827bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6828 SourceLocation *Loc) const {
6829 // We support this checking in C++98 mode in order to diagnose compatibility
6830 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006831 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006832
Richard Smith70488e22012-02-14 21:38:30 +00006833 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006834 Expr::EvalStatus Status;
6835 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6836 Status.Diag = &Diags;
6837 EvalInfo Info(Ctx, Status);
6838
6839 APValue Scratch;
6840 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6841
6842 if (!Diags.empty()) {
6843 IsConstExpr = false;
6844 if (Loc) *Loc = Diags[0].first;
6845 } else if (!IsConstExpr) {
6846 // FIXME: This shouldn't happen.
6847 if (Loc) *Loc = getExprLoc();
6848 }
6849
6850 return IsConstExpr;
6851}
Richard Smith745f5142012-01-27 01:14:48 +00006852
6853bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6854 llvm::SmallVectorImpl<
6855 PartialDiagnosticAt> &Diags) {
6856 // FIXME: It would be useful to check constexpr function templates, but at the
6857 // moment the constant expression evaluator cannot cope with the non-rigorous
6858 // ASTs which we build for dependent expressions.
6859 if (FD->isDependentContext())
6860 return true;
6861
6862 Expr::EvalStatus Status;
6863 Status.Diag = &Diags;
6864
6865 EvalInfo Info(FD->getASTContext(), Status);
6866 Info.CheckingPotentialConstantExpression = true;
6867
6868 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6869 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6870
6871 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6872 // is a temporary being used as the 'this' pointer.
6873 LValue This;
6874 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006875 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006876
Richard Smith745f5142012-01-27 01:14:48 +00006877 ArrayRef<const Expr*> Args;
6878
6879 SourceLocation Loc = FD->getLocation();
6880
Richard Smith1aa0be82012-03-03 22:46:17 +00006881 APValue Scratch;
6882 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006883 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006884 else
Richard Smith745f5142012-01-27 01:14:48 +00006885 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6886 Args, FD->getBody(), Info, Scratch);
6887
6888 return Diags.empty();
6889}