blob: a472951ab6734f3836a13e6531db29dba84d8914 [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"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.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"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump4572bab2009-05-30 03:56:50 +000048#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000049#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000050
Anders Carlssonc44eec62008-07-03 04:20:39 +000051using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000054
Richard Smith83587db2012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCallf4cf1a12010-05-07 17:22:02 +000057namespace {
Richard Smith180f4792011-11-10 06:34:14 +000058 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000061
Richard Smith83587db2012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
66 return B.get<const Expr*>()->getType();
67 }
68
Richard Smith180f4792011-11-10 06:34:14 +000069 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000070 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000071 static
Richard Smithf15fda02012-02-02 01:16:57 +000072 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000073 APValue::BaseOrMemberType Value;
74 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000075 return Value;
76 }
77
78 /// Get an LValue path entry, which is known to not be an array index, as a
79 /// field declaration.
Richard Smith83587db2012-02-15 02:18:13 +000080 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000081 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000082 }
83 /// Get an LValue path entry, which is known to not be an array index, as a
84 /// base class declaration.
Richard Smith83587db2012-02-15 02:18:13 +000085 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000086 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000087 }
88 /// Determine whether this LValue path entry for a base class names a virtual
89 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +000090 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000091 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +000092 }
93
Richard Smithb4e85ed2012-01-06 16:39:00 +000094 /// Find the path length and type of the most-derived subobject in the given
95 /// path, and find the size of the containing array, if any.
96 static
97 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
98 ArrayRef<APValue::LValuePathEntry> Path,
99 uint64_t &ArraySize, QualType &Type) {
100 unsigned MostDerivedLength = 0;
101 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000102 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000103 if (Type->isArrayType()) {
104 const ConstantArrayType *CAT =
105 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
106 Type = CAT->getElementType();
107 ArraySize = CAT->getSize().getZExtValue();
108 MostDerivedLength = I + 1;
Richard Smith86024012012-02-18 22:04:06 +0000109 } else if (Type->isAnyComplexType()) {
110 const ComplexType *CT = Type->castAs<ComplexType>();
111 Type = CT->getElementType();
112 ArraySize = 2;
113 MostDerivedLength = I + 1;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000114 } else if (const FieldDecl *FD = getAsField(Path[I])) {
115 Type = FD->getType();
116 ArraySize = 0;
117 MostDerivedLength = I + 1;
118 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000119 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000120 ArraySize = 0;
121 }
Richard Smith9a17a682011-11-07 05:07:52 +0000122 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000123 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000124 }
125
Richard Smithb4e85ed2012-01-06 16:39:00 +0000126 // The order of this enum is important for diagnostics.
127 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000128 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith86024012012-02-18 22:04:06 +0000129 CSK_This, CSK_Real, CSK_Imag
Richard Smithb4e85ed2012-01-06 16:39:00 +0000130 };
131
Richard Smith0a3bdb62011-11-04 02:25:55 +0000132 /// A path from a glvalue to a subobject of that glvalue.
133 struct SubobjectDesignator {
134 /// True if the subobject was named in a manner not supported by C++11. Such
135 /// lvalues can still be folded, but they are not core constant expressions
136 /// and we cannot perform lvalue-to-rvalue conversions on them.
137 bool Invalid : 1;
138
Richard Smithb4e85ed2012-01-06 16:39:00 +0000139 /// Is this a pointer one past the end of an object?
140 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000141
Richard Smithb4e85ed2012-01-06 16:39:00 +0000142 /// The length of the path to the most-derived object of which this is a
143 /// subobject.
144 unsigned MostDerivedPathLength : 30;
145
146 /// The size of the array of which the most-derived object is an element, or
147 /// 0 if the most-derived object is not an array element.
148 uint64_t MostDerivedArraySize;
149
150 /// The type of the most derived object referred to by this address.
151 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000152
Richard Smith9a17a682011-11-07 05:07:52 +0000153 typedef APValue::LValuePathEntry PathEntry;
154
Richard Smith0a3bdb62011-11-04 02:25:55 +0000155 /// The entries on the path from the glvalue to the designated subobject.
156 SmallVector<PathEntry, 8> Entries;
157
Richard Smithb4e85ed2012-01-06 16:39:00 +0000158 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000159
Richard Smithb4e85ed2012-01-06 16:39:00 +0000160 explicit SubobjectDesignator(QualType T)
161 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
162 MostDerivedArraySize(0), MostDerivedType(T) {}
163
164 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
165 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
166 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000167 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000168 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000169 ArrayRef<PathEntry> VEntries = V.getLValuePath();
170 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
171 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000172 MostDerivedPathLength =
173 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
174 V.getLValuePath(), MostDerivedArraySize,
175 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000176 }
177 }
178
Richard Smith0a3bdb62011-11-04 02:25:55 +0000179 void setInvalid() {
180 Invalid = true;
181 Entries.clear();
182 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000183
184 /// Determine whether this is a one-past-the-end pointer.
185 bool isOnePastTheEnd() const {
186 if (IsOnePastTheEnd)
187 return true;
188 if (MostDerivedArraySize &&
189 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
190 return true;
191 return false;
192 }
193
194 /// Check that this refers to a valid subobject.
195 bool isValidSubobject() const {
196 if (Invalid)
197 return false;
198 return !isOnePastTheEnd();
199 }
200 /// Check that this refers to a valid subobject, and if not, produce a
201 /// relevant diagnostic and set the designator as invalid.
202 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
203
204 /// Update this designator to refer to the first element within this array.
205 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000206 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000207 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000208 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000209
210 // This is a most-derived object.
211 MostDerivedType = CAT->getElementType();
212 MostDerivedArraySize = CAT->getSize().getZExtValue();
213 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000214 }
215 /// Update this designator to refer to the given base or member of this
216 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000217 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000218 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000219 APValue::BaseOrMemberType Value(D, Virtual);
220 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000221 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000222
223 // If this isn't a base class, it's a new most-derived object.
224 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
225 MostDerivedType = FD->getType();
226 MostDerivedArraySize = 0;
227 MostDerivedPathLength = Entries.size();
228 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000229 }
Richard Smith86024012012-02-18 22:04:06 +0000230 /// Update this designator to refer to the given complex component.
231 void addComplexUnchecked(QualType EltTy, bool Imag) {
232 PathEntry Entry;
233 Entry.ArrayIndex = Imag;
234 Entries.push_back(Entry);
235
236 // This is technically a most-derived object, though in practice this
237 // is unlikely to matter.
238 MostDerivedType = EltTy;
239 MostDerivedArraySize = 2;
240 MostDerivedPathLength = Entries.size();
241 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000242 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000243 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000244 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000245 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000246 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000247 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000248 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
249 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
250 setInvalid();
251 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000252 return;
253 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000254 // [expr.add]p4: For the purposes of these operators, a pointer to a
255 // nonarray object behaves the same as a pointer to the first element of
256 // an array of length one with the type of the object as its element type.
257 if (IsOnePastTheEnd && N == (uint64_t)-1)
258 IsOnePastTheEnd = false;
259 else if (!IsOnePastTheEnd && N == 1)
260 IsOnePastTheEnd = true;
261 else if (N != 0) {
262 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000263 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000264 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000265 }
266 };
267
Richard Smithd0dccea2011-10-28 22:34:42 +0000268 /// A stack frame in the constexpr call stack.
269 struct CallStackFrame {
270 EvalInfo &Info;
271
272 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000273 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000274
Richard Smith08d6e032011-12-16 19:06:07 +0000275 /// CallLoc - The location of the call expression for this call.
276 SourceLocation CallLoc;
277
278 /// Callee - The function which was called.
279 const FunctionDecl *Callee;
280
Richard Smith83587db2012-02-15 02:18:13 +0000281 /// Index - The call index of this call.
282 unsigned Index;
283
Richard Smith180f4792011-11-10 06:34:14 +0000284 /// This - The binding for the this pointer in this call, if any.
285 const LValue *This;
286
Richard Smithd0dccea2011-10-28 22:34:42 +0000287 /// ParmBindings - Parameter bindings for this function call, indexed by
288 /// parameters' function scope indices.
Richard Smith1aa0be82012-03-03 22:46:17 +0000289 const APValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000290
Eli Friedmanf6172ae2012-06-25 21:21:08 +0000291 // Note that we intentionally use std::map here so that references to
292 // values are stable.
293 typedef std::map<const Expr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000294 typedef MapTy::const_iterator temp_iterator;
295 /// Temporaries - Temporary lvalues materialized within this stack frame.
296 MapTy Temporaries;
297
Richard Smith08d6e032011-12-16 19:06:07 +0000298 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
299 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000300 const APValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000301 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000302 };
303
Richard Smithdd1f29b2011-12-12 09:28:41 +0000304 /// A partial diagnostic which we might know in advance that we are not going
305 /// to emit.
306 class OptionalDiagnostic {
307 PartialDiagnostic *Diag;
308
309 public:
310 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
311
312 template<typename T>
313 OptionalDiagnostic &operator<<(const T &v) {
314 if (Diag)
315 *Diag << v;
316 return *this;
317 }
Richard Smith789f9b62012-01-31 04:08:20 +0000318
319 OptionalDiagnostic &operator<<(const APSInt &I) {
320 if (Diag) {
321 llvm::SmallVector<char, 32> Buffer;
322 I.toString(Buffer);
323 *Diag << StringRef(Buffer.data(), Buffer.size());
324 }
325 return *this;
326 }
327
328 OptionalDiagnostic &operator<<(const APFloat &F) {
329 if (Diag) {
330 llvm::SmallVector<char, 32> Buffer;
331 F.toString(Buffer);
332 *Diag << StringRef(Buffer.data(), Buffer.size());
333 }
334 return *this;
335 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000336 };
337
Richard Smith83587db2012-02-15 02:18:13 +0000338 /// EvalInfo - This is a private struct used by the evaluator to capture
339 /// information about a subexpression as it is folded. It retains information
340 /// about the AST context, but also maintains information about the folded
341 /// expression.
342 ///
343 /// If an expression could be evaluated, it is still possible it is not a C
344 /// "integer constant expression" or constant expression. If not, this struct
345 /// captures information about how and why not.
346 ///
347 /// One bit of information passed *into* the request for constant folding
348 /// indicates whether the subexpression is "evaluated" or not according to C
349 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
350 /// evaluate the expression regardless of what the RHS is, but C only allows
351 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000352 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000353 ASTContext &Ctx;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000354
Richard Smithbd552ef2011-10-31 05:52:43 +0000355 /// EvalStatus - Contains information about the evaluation.
356 Expr::EvalStatus &EvalStatus;
357
358 /// CurrentCall - The top of the constexpr call stack.
359 CallStackFrame *CurrentCall;
360
Richard Smithbd552ef2011-10-31 05:52:43 +0000361 /// CallStackDepth - The number of calls in the call stack right now.
362 unsigned CallStackDepth;
363
Richard Smith83587db2012-02-15 02:18:13 +0000364 /// NextCallIndex - The next call index to assign.
365 unsigned NextCallIndex;
366
Richard Smithbd552ef2011-10-31 05:52:43 +0000367 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000368 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000369 CallStackFrame BottomFrame;
370
Richard Smith180f4792011-11-10 06:34:14 +0000371 /// EvaluatingDecl - This is the declaration whose initializer is being
372 /// evaluated, if any.
373 const VarDecl *EvaluatingDecl;
374
375 /// EvaluatingDeclValue - This is the value being constructed for the
376 /// declaration whose initializer is being evaluated, if any.
377 APValue *EvaluatingDeclValue;
378
Richard Smithc1c5f272011-12-13 06:39:58 +0000379 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
380 /// notes attached to it will also be stored, otherwise they will not be.
381 bool HasActiveDiagnostic;
382
Richard Smith745f5142012-01-27 01:14:48 +0000383 /// CheckingPotentialConstantExpression - Are we checking whether the
384 /// expression is a potential constant expression? If so, some diagnostics
385 /// are suppressed.
386 bool CheckingPotentialConstantExpression;
387
Richard Smithbd552ef2011-10-31 05:52:43 +0000388 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000389 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000390 CallStackDepth(0), NextCallIndex(1),
391 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000392 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Argyrios Kyrtzidis649dfbc2012-03-15 18:07:13 +0000393 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000394
Richard Smith180f4792011-11-10 06:34:14 +0000395 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
396 EvaluatingDecl = VD;
397 EvaluatingDeclValue = &Value;
398 }
399
David Blaikie4e4d0842012-03-11 07:00:24 +0000400 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000401
Richard Smithc1c5f272011-12-13 06:39:58 +0000402 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000403 // Don't perform any constexpr calls (other than the call we're checking)
404 // when checking a potential constant expression.
405 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
406 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000407 if (NextCallIndex == 0) {
408 // NextCallIndex has wrapped around.
409 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
410 return false;
411 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000412 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
413 return true;
414 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
415 << getLangOpts().ConstexprCallDepth;
416 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000417 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000418
Richard Smith83587db2012-02-15 02:18:13 +0000419 CallStackFrame *getCallFrame(unsigned CallIndex) {
420 assert(CallIndex && "no call index in getCallFrame");
421 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
422 // be null in this loop.
423 CallStackFrame *Frame = CurrentCall;
424 while (Frame->Index > CallIndex)
425 Frame = Frame->Caller;
426 return (Frame->Index == CallIndex) ? Frame : 0;
427 }
428
Richard Smithc1c5f272011-12-13 06:39:58 +0000429 private:
430 /// Add a diagnostic to the diagnostics list.
431 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
432 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
433 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
434 return EvalStatus.Diag->back().second;
435 }
436
Richard Smith08d6e032011-12-16 19:06:07 +0000437 /// Add notes containing a call stack to the current point of evaluation.
438 void addCallStack(unsigned Limit);
439
Richard Smithc1c5f272011-12-13 06:39:58 +0000440 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000441 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000442 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
443 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000444 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000445 // If we have a prior diagnostic, it will be noting that the expression
446 // isn't a constant expression. This diagnostic is more important.
447 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000448 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000449 unsigned CallStackNotes = CallStackDepth - 1;
450 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
451 if (Limit)
452 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000453 if (CheckingPotentialConstantExpression)
454 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000455
Richard Smithc1c5f272011-12-13 06:39:58 +0000456 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000457 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000458 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
459 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000460 if (!CheckingPotentialConstantExpression)
461 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000462 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000463 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000464 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000465 return OptionalDiagnostic();
466 }
467
Richard Smith5cfc7d82012-03-15 04:53:45 +0000468 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
469 = diag::note_invalid_subexpr_in_const_expr,
470 unsigned ExtraNotes = 0) {
471 if (EvalStatus.Diag)
472 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
473 HasActiveDiagnostic = false;
474 return OptionalDiagnostic();
475 }
476
Richard Smithdd1f29b2011-12-12 09:28:41 +0000477 /// Diagnose that the evaluation does not produce a C++11 core constant
478 /// expression.
Richard Smith5cfc7d82012-03-15 04:53:45 +0000479 template<typename LocArg>
480 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000481 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000482 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000483 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000484 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
485 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000486 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000487 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000488 return Diag(Loc, DiagId, ExtraNotes);
489 }
490
491 /// Add a note to a prior diagnostic.
492 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
493 if (!HasActiveDiagnostic)
494 return OptionalDiagnostic();
495 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000496 }
Richard Smith099e7f62011-12-19 06:19:21 +0000497
498 /// Add a stack of notes to a prior diagnostic.
499 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
500 if (HasActiveDiagnostic) {
501 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
502 Diags.begin(), Diags.end());
503 }
504 }
Richard Smith745f5142012-01-27 01:14:48 +0000505
506 /// Should we continue evaluation as much as possible after encountering a
507 /// construct which can't be folded?
508 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000509 return CheckingPotentialConstantExpression &&
510 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000511 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000512 };
Richard Smithf15fda02012-02-02 01:16:57 +0000513
514 /// Object used to treat all foldable expressions as constant expressions.
515 struct FoldConstant {
516 bool Enabled;
517
518 explicit FoldConstant(EvalInfo &Info)
519 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
520 !Info.EvalStatus.HasSideEffects) {
521 }
522 // Treat the value we've computed since this object was created as constant.
523 void Fold(EvalInfo &Info) {
524 if (Enabled && !Info.EvalStatus.Diag->empty() &&
525 !Info.EvalStatus.HasSideEffects)
526 Info.EvalStatus.Diag->clear();
527 }
528 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000529
530 /// RAII object used to suppress diagnostics and side-effects from a
531 /// speculative evaluation.
532 class SpeculativeEvaluationRAII {
533 EvalInfo &Info;
534 Expr::EvalStatus Old;
535
536 public:
537 SpeculativeEvaluationRAII(EvalInfo &Info,
538 llvm::SmallVectorImpl<PartialDiagnosticAt>
539 *NewDiag = 0)
540 : Info(Info), Old(Info.EvalStatus) {
541 Info.EvalStatus.Diag = NewDiag;
542 }
543 ~SpeculativeEvaluationRAII() {
544 Info.EvalStatus = Old;
545 }
546 };
Richard Smith08d6e032011-12-16 19:06:07 +0000547}
Richard Smithbd552ef2011-10-31 05:52:43 +0000548
Richard Smithb4e85ed2012-01-06 16:39:00 +0000549bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
550 CheckSubobjectKind CSK) {
551 if (Invalid)
552 return false;
553 if (isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000554 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000555 << CSK;
556 setInvalid();
557 return false;
558 }
559 return true;
560}
561
562void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
563 const Expr *E, uint64_t N) {
564 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000565 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000566 << static_cast<int>(N) << /*array*/ 0
567 << static_cast<unsigned>(MostDerivedArraySize);
568 else
Richard Smith5cfc7d82012-03-15 04:53:45 +0000569 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000570 << static_cast<int>(N) << /*non-array*/ 1;
571 setInvalid();
572}
573
Richard Smith08d6e032011-12-16 19:06:07 +0000574CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
575 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000576 const APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000577 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000578 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000579 Info.CurrentCall = this;
580 ++Info.CallStackDepth;
581}
582
583CallStackFrame::~CallStackFrame() {
584 assert(Info.CurrentCall == this && "calls retired out of order");
585 --Info.CallStackDepth;
586 Info.CurrentCall = Caller;
587}
588
589/// Produce a string describing the given constexpr call.
590static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
591 unsigned ArgIndex = 0;
592 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000593 !isa<CXXConstructorDecl>(Frame->Callee) &&
594 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000595
596 if (!IsMemberCall)
597 Out << *Frame->Callee << '(';
598
599 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
600 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000601 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000602 Out << ", ";
603
604 const ParmVarDecl *Param = *I;
Richard Smith1aa0be82012-03-03 22:46:17 +0000605 const APValue &Arg = Frame->Arguments[ArgIndex];
606 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smith08d6e032011-12-16 19:06:07 +0000607
608 if (ArgIndex == 0 && IsMemberCall)
609 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000610 }
611
Richard Smith08d6e032011-12-16 19:06:07 +0000612 Out << ')';
613}
614
615void EvalInfo::addCallStack(unsigned Limit) {
616 // Determine which calls to skip, if any.
617 unsigned ActiveCalls = CallStackDepth - 1;
618 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
619 if (Limit && Limit < ActiveCalls) {
620 SkipStart = Limit / 2 + Limit % 2;
621 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000622 }
623
Richard Smith08d6e032011-12-16 19:06:07 +0000624 // Walk the call stack and add the diagnostics.
625 unsigned CallIdx = 0;
626 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
627 Frame = Frame->Caller, ++CallIdx) {
628 // Skip this call?
629 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
630 if (CallIdx == SkipStart) {
631 // Note that we're skipping calls.
632 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
633 << unsigned(ActiveCalls - Limit);
634 }
635 continue;
636 }
637
638 llvm::SmallVector<char, 128> Buffer;
639 llvm::raw_svector_ostream Out(Buffer);
640 describeCall(Frame, Out);
641 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
642 }
643}
644
645namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000646 struct ComplexValue {
647 private:
648 bool IsInt;
649
650 public:
651 APSInt IntReal, IntImag;
652 APFloat FloatReal, FloatImag;
653
654 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
655
656 void makeComplexFloat() { IsInt = false; }
657 bool isComplexFloat() const { return !IsInt; }
658 APFloat &getComplexFloatReal() { return FloatReal; }
659 APFloat &getComplexFloatImag() { return FloatImag; }
660
661 void makeComplexInt() { IsInt = true; }
662 bool isComplexInt() const { return IsInt; }
663 APSInt &getComplexIntReal() { return IntReal; }
664 APSInt &getComplexIntImag() { return IntImag; }
665
Richard Smith1aa0be82012-03-03 22:46:17 +0000666 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000667 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000668 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000669 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000670 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000671 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000672 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000673 assert(v.isComplexFloat() || v.isComplexInt());
674 if (v.isComplexFloat()) {
675 makeComplexFloat();
676 FloatReal = v.getComplexFloatReal();
677 FloatImag = v.getComplexFloatImag();
678 } else {
679 makeComplexInt();
680 IntReal = v.getComplexIntReal();
681 IntImag = v.getComplexIntImag();
682 }
683 }
John McCallf4cf1a12010-05-07 17:22:02 +0000684 };
John McCallefdb83e2010-05-07 21:00:08 +0000685
686 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000687 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000688 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000689 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000690 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000691
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000692 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000693 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000694 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000695 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000696 SubobjectDesignator &getLValueDesignator() { return Designator; }
697 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000698
Richard Smith1aa0be82012-03-03 22:46:17 +0000699 void moveInto(APValue &V) const {
700 if (Designator.Invalid)
701 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
702 else
703 V = APValue(Base, Offset, Designator.Entries,
704 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000705 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000706 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000707 assert(V.isLValue());
708 Base = V.getLValueBase();
709 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000710 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000711 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000712 }
713
Richard Smith83587db2012-02-15 02:18:13 +0000714 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000715 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000716 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000717 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000718 Designator = SubobjectDesignator(getType(B));
719 }
720
721 // Check that this LValue is not based on a null pointer. If it is, produce
722 // a diagnostic and mark the designator as invalid.
723 bool checkNullPointer(EvalInfo &Info, const Expr *E,
724 CheckSubobjectKind CSK) {
725 if (Designator.Invalid)
726 return false;
727 if (!Base) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000728 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000729 << CSK;
730 Designator.setInvalid();
731 return false;
732 }
733 return true;
734 }
735
736 // Check this LValue refers to an object. If not, set the designator to be
737 // invalid and emit a diagnostic.
738 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000739 // Outside C++11, do not build a designator referring to a subobject of
740 // any object: we won't use such a designator for anything.
Richard Smith80ad52f2013-01-02 11:42:31 +0000741 if (!Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000742 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000743 return checkNullPointer(Info, E, CSK) &&
744 Designator.checkSubobject(Info, E, CSK);
745 }
746
747 void addDecl(EvalInfo &Info, const Expr *E,
748 const Decl *D, bool Virtual = false) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000749 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
750 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000751 }
752 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000753 if (checkSubobject(Info, E, CSK_ArrayToPointer))
754 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000755 }
Richard Smith86024012012-02-18 22:04:06 +0000756 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000757 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
758 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000759 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000760 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000761 if (checkNullPointer(Info, E, CSK_ArrayIndex))
762 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000763 }
John McCallefdb83e2010-05-07 21:00:08 +0000764 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000765
766 struct MemberPtr {
767 MemberPtr() {}
768 explicit MemberPtr(const ValueDecl *Decl) :
769 DeclAndIsDerivedMember(Decl, false), Path() {}
770
771 /// The member or (direct or indirect) field referred to by this member
772 /// pointer, or 0 if this is a null member pointer.
773 const ValueDecl *getDecl() const {
774 return DeclAndIsDerivedMember.getPointer();
775 }
776 /// Is this actually a member of some type derived from the relevant class?
777 bool isDerivedMember() const {
778 return DeclAndIsDerivedMember.getInt();
779 }
780 /// Get the class which the declaration actually lives in.
781 const CXXRecordDecl *getContainingRecord() const {
782 return cast<CXXRecordDecl>(
783 DeclAndIsDerivedMember.getPointer()->getDeclContext());
784 }
785
Richard Smith1aa0be82012-03-03 22:46:17 +0000786 void moveInto(APValue &V) const {
787 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000788 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000789 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000790 assert(V.isMemberPointer());
791 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
792 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
793 Path.clear();
794 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
795 Path.insert(Path.end(), P.begin(), P.end());
796 }
797
798 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
799 /// whether the member is a member of some class derived from the class type
800 /// of the member pointer.
801 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
802 /// Path - The path of base/derived classes from the member declaration's
803 /// class (exclusive) to the class type of the member pointer (inclusive).
804 SmallVector<const CXXRecordDecl*, 4> Path;
805
806 /// Perform a cast towards the class of the Decl (either up or down the
807 /// hierarchy).
808 bool castBack(const CXXRecordDecl *Class) {
809 assert(!Path.empty());
810 const CXXRecordDecl *Expected;
811 if (Path.size() >= 2)
812 Expected = Path[Path.size() - 2];
813 else
814 Expected = getContainingRecord();
815 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
816 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
817 // if B does not contain the original member and is not a base or
818 // derived class of the class containing the original member, the result
819 // of the cast is undefined.
820 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
821 // (D::*). We consider that to be a language defect.
822 return false;
823 }
824 Path.pop_back();
825 return true;
826 }
827 /// Perform a base-to-derived member pointer cast.
828 bool castToDerived(const CXXRecordDecl *Derived) {
829 if (!getDecl())
830 return true;
831 if (!isDerivedMember()) {
832 Path.push_back(Derived);
833 return true;
834 }
835 if (!castBack(Derived))
836 return false;
837 if (Path.empty())
838 DeclAndIsDerivedMember.setInt(false);
839 return true;
840 }
841 /// Perform a derived-to-base member pointer cast.
842 bool castToBase(const CXXRecordDecl *Base) {
843 if (!getDecl())
844 return true;
845 if (Path.empty())
846 DeclAndIsDerivedMember.setInt(true);
847 if (isDerivedMember()) {
848 Path.push_back(Base);
849 return true;
850 }
851 return castBack(Base);
852 }
853 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000854
Richard Smithb02e4622012-02-01 01:42:44 +0000855 /// Compare two member pointers, which are assumed to be of the same type.
856 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
857 if (!LHS.getDecl() || !RHS.getDecl())
858 return !LHS.getDecl() && !RHS.getDecl();
859 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
860 return false;
861 return LHS.Path == RHS.Path;
862 }
863
Richard Smithc1c5f272011-12-13 06:39:58 +0000864 /// Kinds of constant expression checking, for diagnostics.
865 enum CheckConstantExpressionKind {
866 CCEK_Constant, ///< A normal constant.
867 CCEK_ReturnValue, ///< A constexpr function return value.
868 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
869 };
John McCallf4cf1a12010-05-07 17:22:02 +0000870}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000871
Richard Smith1aa0be82012-03-03 22:46:17 +0000872static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000873static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
874 const LValue &This, const Expr *E,
875 CheckConstantExpressionKind CCEK = CCEK_Constant,
876 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000877static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
878static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000879static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
880 EvalInfo &Info);
881static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000882static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000883static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000884 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000885static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000886static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000887
888//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000889// Misc utilities
890//===----------------------------------------------------------------------===//
891
Richard Smith180f4792011-11-10 06:34:14 +0000892/// Should this call expression be treated as a string literal?
893static bool IsStringLiteralCall(const CallExpr *E) {
894 unsigned Builtin = E->isBuiltinCall();
895 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
896 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
897}
898
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000899static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000900 // C++11 [expr.const]p3 An address constant expression is a prvalue core
901 // constant expression of pointer type that evaluates to...
902
903 // ... a null pointer value, or a prvalue core constant expression of type
904 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000905 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000906
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000907 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
908 // ... the address of an object with static storage duration,
909 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
910 return VD->hasGlobalStorage();
911 // ... the address of a function,
912 return isa<FunctionDecl>(D);
913 }
914
915 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000916 switch (E->getStmtClass()) {
917 default:
918 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000919 case Expr::CompoundLiteralExprClass: {
920 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
921 return CLE->isFileScope() && CLE->isLValue();
922 }
Richard Smith180f4792011-11-10 06:34:14 +0000923 // A string literal has static storage duration.
924 case Expr::StringLiteralClass:
925 case Expr::PredefinedExprClass:
926 case Expr::ObjCStringLiteralClass:
927 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000928 case Expr::CXXTypeidExprClass:
Francois Pichete275a182012-04-16 04:08:35 +0000929 case Expr::CXXUuidofExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000930 return true;
931 case Expr::CallExprClass:
932 return IsStringLiteralCall(cast<CallExpr>(E));
933 // For GCC compatibility, &&label has static storage duration.
934 case Expr::AddrLabelExprClass:
935 return true;
936 // A Block literal expression may be used as the initialization value for
937 // Block variables at global or local static scope.
938 case Expr::BlockExprClass:
939 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000940 case Expr::ImplicitValueInitExprClass:
941 // FIXME:
942 // We can never form an lvalue with an implicit value initialization as its
943 // base through expression evaluation, so these only appear in one case: the
944 // implicit variable declaration we invent when checking whether a constexpr
945 // constructor can produce a constant expression. We must assume that such
946 // an expression might be a global lvalue.
947 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000948 }
John McCall42c8f872010-05-10 23:27:23 +0000949}
950
Richard Smith83587db2012-02-15 02:18:13 +0000951static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
952 assert(Base && "no location for a null lvalue");
953 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
954 if (VD)
955 Info.Note(VD->getLocation(), diag::note_declared_at);
956 else
Ted Kremenek890f0f12012-08-23 20:46:57 +0000957 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smith83587db2012-02-15 02:18:13 +0000958 diag::note_constexpr_temporary_here);
959}
960
Richard Smith9a17a682011-11-07 05:07:52 +0000961/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000962/// value for an address or reference constant expression. Return true if we
963/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000964static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
965 QualType Type, const LValue &LVal) {
966 bool IsReferenceType = Type->isReferenceType();
967
Richard Smithc1c5f272011-12-13 06:39:58 +0000968 APValue::LValueBase Base = LVal.getLValueBase();
969 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
970
Richard Smithb78ae972012-02-18 04:58:18 +0000971 // Check that the object is a global. Note that the fake 'this' object we
972 // manufacture when checking potential constant expressions is conservatively
973 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000974 if (!IsGlobalLValue(Base)) {
Richard Smith80ad52f2013-01-02 11:42:31 +0000975 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000976 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000977 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
978 << IsReferenceType << !Designator.Entries.empty()
979 << !!VD << VD;
980 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000981 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000982 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000983 }
Richard Smith61e61622012-01-12 06:08:57 +0000984 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000985 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000986 }
Richard Smith83587db2012-02-15 02:18:13 +0000987 assert((Info.CheckingPotentialConstantExpression ||
988 LVal.getLValueCallIndex() == 0) &&
989 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +0000990
Hans Wennborg48def652012-08-29 18:27:29 +0000991 // Check if this is a thread-local variable.
992 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
993 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
994 if (Var->isThreadSpecified())
995 return false;
996 }
997 }
998
Richard Smithb4e85ed2012-01-06 16:39:00 +0000999 // Allow address constant expressions to be past-the-end pointers. This is
1000 // an extension: the standard requires them to point to an object.
1001 if (!IsReferenceType)
1002 return true;
1003
1004 // A reference constant expression must refer to an object.
1005 if (!Base) {
1006 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001007 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001008 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001009 }
1010
Richard Smithc1c5f272011-12-13 06:39:58 +00001011 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001012 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001013 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001014 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001015 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001016 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001017 }
1018
Richard Smith9a17a682011-11-07 05:07:52 +00001019 return true;
1020}
1021
Richard Smith51201882011-12-30 21:15:51 +00001022/// Check that this core constant expression is of literal type, and if not,
1023/// produce an appropriate diagnostic.
1024static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1025 if (!E->isRValue() || E->getType()->isLiteralType())
1026 return true;
1027
1028 // Prvalue constant expressions must be of literal types.
Richard Smith80ad52f2013-01-02 11:42:31 +00001029 if (Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001030 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001031 << E->getType();
1032 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001033 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001034 return false;
1035}
1036
Richard Smith47a1eed2011-10-29 20:57:55 +00001037/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001038/// constant expression. If not, report an appropriate diagnostic. Does not
1039/// check that the expression is of literal type.
1040static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1041 QualType Type, const APValue &Value) {
1042 // Core issue 1454: For a literal constant expression of array or class type,
1043 // each subobject of its value shall have been initialized by a constant
1044 // expression.
1045 if (Value.isArray()) {
1046 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1047 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1048 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1049 Value.getArrayInitializedElt(I)))
1050 return false;
1051 }
1052 if (!Value.hasArrayFiller())
1053 return true;
1054 return CheckConstantExpression(Info, DiagLoc, EltTy,
1055 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001056 }
Richard Smith83587db2012-02-15 02:18:13 +00001057 if (Value.isUnion() && Value.getUnionField()) {
1058 return CheckConstantExpression(Info, DiagLoc,
1059 Value.getUnionField()->getType(),
1060 Value.getUnionValue());
1061 }
1062 if (Value.isStruct()) {
1063 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1064 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1065 unsigned BaseIndex = 0;
1066 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1067 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1068 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1069 Value.getStructBase(BaseIndex)))
1070 return false;
1071 }
1072 }
1073 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1074 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001075 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1076 Value.getStructField(I->getFieldIndex())))
Richard Smith83587db2012-02-15 02:18:13 +00001077 return false;
1078 }
1079 }
1080
1081 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001082 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001083 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001084 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1085 }
1086
1087 // Everything else is fine.
1088 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001089}
1090
Richard Smith9e36b532011-10-31 05:11:32 +00001091const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001092 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001093}
1094
1095static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001096 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001097}
1098
Richard Smith65ac5982011-11-01 21:06:14 +00001099static bool IsWeakLValue(const LValue &Value) {
1100 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001101 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001102}
1103
Richard Smith1aa0be82012-03-03 22:46:17 +00001104static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001105 // A null base expression indicates a null pointer. These are always
1106 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001107 if (!Value.getLValueBase()) {
1108 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001109 return true;
1110 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001111
Richard Smithe24f5fc2011-11-17 22:56:20 +00001112 // We have a non-null base. These are generally known to be true, but if it's
1113 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001114 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001115 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001116 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001117}
1118
Richard Smith1aa0be82012-03-03 22:46:17 +00001119static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001120 switch (Val.getKind()) {
1121 case APValue::Uninitialized:
1122 return false;
1123 case APValue::Int:
1124 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001125 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001126 case APValue::Float:
1127 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001128 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001129 case APValue::ComplexInt:
1130 Result = Val.getComplexIntReal().getBoolValue() ||
1131 Val.getComplexIntImag().getBoolValue();
1132 return true;
1133 case APValue::ComplexFloat:
1134 Result = !Val.getComplexFloatReal().isZero() ||
1135 !Val.getComplexFloatImag().isZero();
1136 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001137 case APValue::LValue:
1138 return EvalPointerValueAsBool(Val, Result);
1139 case APValue::MemberPointer:
1140 Result = Val.getMemberPointerDecl();
1141 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001142 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001143 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001144 case APValue::Struct:
1145 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001146 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001147 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001148 }
1149
Richard Smithc49bd112011-10-28 17:51:58 +00001150 llvm_unreachable("unknown APValue kind");
1151}
1152
1153static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1154 EvalInfo &Info) {
1155 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001156 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001157 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001158 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001159 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001160}
1161
Richard Smithc1c5f272011-12-13 06:39:58 +00001162template<typename T>
Eli Friedman26dc97c2012-07-17 21:03:05 +00001163static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +00001164 const T &SrcValue, QualType DestType) {
Eli Friedman26dc97c2012-07-17 21:03:05 +00001165 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001166 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001167}
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)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001180 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001181 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)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001192 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001193 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)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001215 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001216 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) {
John McCall8d59dee2012-05-01 00:38:49 +00001284 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001285 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1286 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001287 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001288 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001289 else
Richard Smith180f4792011-11-10 06:34:14 +00001290 Result.Offset -= Layout.getBaseClassOffset(Base);
1291 RD = Base;
1292 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001293 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001294 return true;
1295}
1296
John McCall8d59dee2012-05-01 00:38:49 +00001297static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001298 const CXXRecordDecl *Derived,
1299 const CXXRecordDecl *Base,
1300 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001301 if (!RL) {
1302 if (Derived->isInvalidDecl()) return false;
1303 RL = &Info.Ctx.getASTRecordLayout(Derived);
1304 }
1305
Richard Smith180f4792011-11-10 06:34:14 +00001306 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001307 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCall8d59dee2012-05-01 00:38:49 +00001308 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001309}
1310
Richard Smithb4e85ed2012-01-06 16:39:00 +00001311static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001312 const CXXRecordDecl *DerivedDecl,
1313 const CXXBaseSpecifier *Base) {
1314 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1315
John McCall8d59dee2012-05-01 00:38:49 +00001316 if (!Base->isVirtual())
1317 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001318
Richard Smithb4e85ed2012-01-06 16:39:00 +00001319 SubobjectDesignator &D = Obj.Designator;
1320 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001321 return false;
1322
Richard Smithb4e85ed2012-01-06 16:39:00 +00001323 // Extract most-derived object and corresponding type.
1324 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1325 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1326 return false;
1327
1328 // Find the virtual base class.
John McCall8d59dee2012-05-01 00:38:49 +00001329 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001330 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1331 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001332 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001333 return true;
1334}
1335
1336/// Update LVal to refer to the given field, which must be a member of the type
1337/// currently described by LVal.
John McCall8d59dee2012-05-01 00:38:49 +00001338static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001339 const FieldDecl *FD,
1340 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001341 if (!RL) {
1342 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001343 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCall8d59dee2012-05-01 00:38:49 +00001344 }
Richard Smith180f4792011-11-10 06:34:14 +00001345
1346 unsigned I = FD->getFieldIndex();
1347 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001348 LVal.addDecl(Info, E, FD);
John McCall8d59dee2012-05-01 00:38:49 +00001349 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001350}
1351
Richard Smithd9b02e72012-01-25 22:15:11 +00001352/// Update LVal to refer to the given indirect field.
John McCall8d59dee2012-05-01 00:38:49 +00001353static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smithd9b02e72012-01-25 22:15:11 +00001354 LValue &LVal,
1355 const IndirectFieldDecl *IFD) {
1356 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1357 CE = IFD->chain_end(); C != CE; ++C)
John McCall8d59dee2012-05-01 00:38:49 +00001358 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1359 return false;
1360 return true;
Richard Smithd9b02e72012-01-25 22:15:11 +00001361}
1362
Richard Smith180f4792011-11-10 06:34:14 +00001363/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001364static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1365 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001366 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1367 // extension.
1368 if (Type->isVoidType() || Type->isFunctionType()) {
1369 Size = CharUnits::One();
1370 return true;
1371 }
1372
1373 if (!Type->isConstantSizeType()) {
1374 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001375 // FIXME: Better diagnostic.
1376 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001377 return false;
1378 }
1379
1380 Size = Info.Ctx.getTypeSizeInChars(Type);
1381 return true;
1382}
1383
1384/// Update a pointer value to model pointer arithmetic.
1385/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001386/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001387/// \param LVal - The pointer value to be updated.
1388/// \param EltTy - The pointee type represented by LVal.
1389/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001390static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1391 LValue &LVal, QualType EltTy,
1392 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001393 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001394 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001395 return false;
1396
1397 // Compute the new offset in the appropriate width.
1398 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001399 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001400 return true;
1401}
1402
Richard Smith86024012012-02-18 22:04:06 +00001403/// Update an lvalue to refer to a component of a complex number.
1404/// \param Info - Information about the ongoing evaluation.
1405/// \param LVal - The lvalue to be updated.
1406/// \param EltTy - The complex number's component type.
1407/// \param Imag - False for the real component, true for the imaginary.
1408static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1409 LValue &LVal, QualType EltTy,
1410 bool Imag) {
1411 if (Imag) {
1412 CharUnits SizeOfComponent;
1413 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1414 return false;
1415 LVal.Offset += SizeOfComponent;
1416 }
1417 LVal.addComplex(Info, E, EltTy, Imag);
1418 return true;
1419}
1420
Richard Smith03f96112011-10-24 17:54:18 +00001421/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001422static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1423 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001424 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001425 // If this is a parameter to an active constexpr function call, perform
1426 // argument substitution.
1427 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001428 // Assume arguments of a potential constant expression are unknown
1429 // constant expressions.
1430 if (Info.CheckingPotentialConstantExpression)
1431 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001432 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001433 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001434 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001435 }
Richard Smith177dce72011-11-01 16:57:24 +00001436 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1437 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001438 }
Richard Smith03f96112011-10-24 17:54:18 +00001439
Richard Smith099e7f62011-12-19 06:19:21 +00001440 // Dig out the initializer, and use the declaration which it's attached to.
1441 const Expr *Init = VD->getAnyInitializer(VD);
1442 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001443 // If we're checking a potential constant expression, the variable could be
1444 // initialized later.
1445 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001446 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001447 return false;
1448 }
1449
Richard Smith180f4792011-11-10 06:34:14 +00001450 // If we're currently evaluating the initializer of this declaration, use that
1451 // in-flight value.
1452 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001453 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001454 return !Result.isUninit();
1455 }
1456
Richard Smith65ac5982011-11-01 21:06:14 +00001457 // Never evaluate the initializer of a weak variable. We can't be sure that
1458 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001459 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001460 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001461 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001462 }
Richard Smith65ac5982011-11-01 21:06:14 +00001463
Richard Smith099e7f62011-12-19 06:19:21 +00001464 // Check that we can fold the initializer. In C++, we will have already done
1465 // this in the cases where it matters for conformance.
1466 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1467 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001468 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001469 Notes.size() + 1) << VD;
1470 Info.Note(VD->getLocation(), diag::note_declared_at);
1471 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001472 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001473 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001474 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001475 Notes.size() + 1) << VD;
1476 Info.Note(VD->getLocation(), diag::note_declared_at);
1477 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001478 }
Richard Smith03f96112011-10-24 17:54:18 +00001479
Richard Smith1aa0be82012-03-03 22:46:17 +00001480 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001481 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001482}
1483
Richard Smithc49bd112011-10-28 17:51:58 +00001484static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001485 Qualifiers Quals = T.getQualifiers();
1486 return Quals.hasConst() && !Quals.hasVolatile();
1487}
1488
Richard Smith59efe262011-11-11 04:05:33 +00001489/// Get the base index of the given base class within an APValue representing
1490/// the given derived class.
1491static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1492 const CXXRecordDecl *Base) {
1493 Base = Base->getCanonicalDecl();
1494 unsigned Index = 0;
1495 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1496 E = Derived->bases_end(); I != E; ++I, ++Index) {
1497 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1498 return Index;
1499 }
1500
1501 llvm_unreachable("base class missing from derived class's bases list");
1502}
1503
Richard Smithfe587202012-04-15 02:50:59 +00001504/// Extract the value of a character from a string literal. CharType is used to
1505/// determine the expected signedness of the result -- a string literal used to
1506/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1507/// of the wrong signedness.
Richard Smithf3908f22012-02-17 03:35:37 +00001508static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smithfe587202012-04-15 02:50:59 +00001509 uint64_t Index, QualType CharType) {
Richard Smithf3908f22012-02-17 03:35:37 +00001510 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1511 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1512 assert(S && "unexpected string literal expression kind");
Richard Smithfe587202012-04-15 02:50:59 +00001513 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smithf3908f22012-02-17 03:35:37 +00001514
1515 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smithfe587202012-04-15 02:50:59 +00001516 CharType->isUnsignedIntegerType());
Richard Smithf3908f22012-02-17 03:35:37 +00001517 if (Index < S->getLength())
1518 Value = S->getCodeUnit(Index);
1519 return Value;
1520}
1521
Richard Smithcc5d4f62011-11-07 09:22:26 +00001522/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001523static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001524 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001525 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001526 if (Sub.Invalid)
1527 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001528 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001529 if (Sub.isOnePastTheEnd()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001530 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001531 (unsigned)diag::note_constexpr_read_past_end :
1532 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001533 return false;
1534 }
Richard Smithf64699e2011-11-11 08:28:03 +00001535 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001536 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001537 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1538 // This object might be initialized later.
1539 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001540
Richard Smith0069b842012-03-10 00:28:11 +00001541 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001542 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001543 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001544 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001545 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001546 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001547 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001548 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001549 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001550 // Note, it should not be possible to form a pointer with a valid
1551 // designator which points more than one past the end of the array.
Richard Smith80ad52f2013-01-02 11:42:31 +00001552 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001553 (unsigned)diag::note_constexpr_read_past_end :
1554 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001555 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001556 }
Richard Smithf3908f22012-02-17 03:35:37 +00001557 // An array object is represented as either an Array APValue or as an
1558 // LValue which refers to a string literal.
1559 if (O->isLValue()) {
1560 assert(I == N - 1 && "extracting subobject of character?");
1561 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001562 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithfe587202012-04-15 02:50:59 +00001563 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smithf3908f22012-02-17 03:35:37 +00001564 return true;
1565 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001566 O = &O->getArrayInitializedElt(Index);
1567 else
1568 O = &O->getArrayFiller();
1569 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001570 } else if (ObjType->isAnyComplexType()) {
1571 // Next subobject is a complex number.
1572 uint64_t Index = Sub.Entries[I].ArrayIndex;
1573 if (Index > 1) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001574 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Richard Smith86024012012-02-18 22:04:06 +00001575 (unsigned)diag::note_constexpr_read_past_end :
1576 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1577 return false;
1578 }
1579 assert(I == N - 1 && "extracting subobject of scalar?");
1580 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001581 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001582 : O->getComplexIntReal());
1583 } else {
1584 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001585 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001586 : O->getComplexFloatReal());
1587 }
1588 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001589 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001590 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001591 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001592 << Field;
1593 Info.Note(Field->getLocation(), diag::note_declared_at);
1594 return false;
1595 }
1596
Richard Smith180f4792011-11-10 06:34:14 +00001597 // Next subobject is a class, struct or union field.
1598 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1599 if (RD->isUnion()) {
1600 const FieldDecl *UnionField = O->getUnionField();
1601 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001602 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001603 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001604 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001605 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001606 }
Richard Smith180f4792011-11-10 06:34:14 +00001607 O = &O->getUnionValue();
1608 } else
1609 O = &O->getStructField(Field->getFieldIndex());
1610 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001611
1612 if (ObjType.isVolatileQualified()) {
1613 if (Info.getLangOpts().CPlusPlus) {
1614 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001615 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001616 << 2 << Field;
1617 Info.Note(Field->getLocation(), diag::note_declared_at);
1618 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001619 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001620 }
1621 return false;
1622 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001623 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001624 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001625 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1626 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1627 O = &O->getStructBase(getBaseIndex(Derived, Base));
1628 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001629 }
Richard Smith180f4792011-11-10 06:34:14 +00001630
Richard Smithf48fdb02011-12-09 22:58:01 +00001631 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001632 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001633 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001634 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001635 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001636 }
1637
Richard Smith0069b842012-03-10 00:28:11 +00001638 // This may look super-stupid, but it serves an important purpose: if we just
1639 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1640 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1641 // object, which is destroyed by Tmp's destructor.
1642 APValue Tmp;
1643 O->swap(Tmp);
1644 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001645 return true;
1646}
1647
Richard Smithf15fda02012-02-02 01:16:57 +00001648/// Find the position where two subobject designators diverge, or equivalently
1649/// the length of the common initial subsequence.
1650static unsigned FindDesignatorMismatch(QualType ObjType,
1651 const SubobjectDesignator &A,
1652 const SubobjectDesignator &B,
1653 bool &WasArrayIndex) {
1654 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1655 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001656 if (!ObjType.isNull() &&
1657 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001658 // Next subobject is an array element.
1659 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1660 WasArrayIndex = true;
1661 return I;
1662 }
Richard Smith86024012012-02-18 22:04:06 +00001663 if (ObjType->isAnyComplexType())
1664 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1665 else
1666 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001667 } else {
1668 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1669 WasArrayIndex = false;
1670 return I;
1671 }
1672 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1673 // Next subobject is a field.
1674 ObjType = FD->getType();
1675 else
1676 // Next subobject is a base class.
1677 ObjType = QualType();
1678 }
1679 }
1680 WasArrayIndex = false;
1681 return I;
1682}
1683
1684/// Determine whether the given subobject designators refer to elements of the
1685/// same array object.
1686static bool AreElementsOfSameArray(QualType ObjType,
1687 const SubobjectDesignator &A,
1688 const SubobjectDesignator &B) {
1689 if (A.Entries.size() != B.Entries.size())
1690 return false;
1691
1692 bool IsArray = A.MostDerivedArraySize != 0;
1693 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1694 // A is a subobject of the array element.
1695 return false;
1696
1697 // If A (and B) designates an array element, the last entry will be the array
1698 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1699 // of length 1' case, and the entire path must match.
1700 bool WasArrayIndex;
1701 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1702 return CommonLength >= A.Entries.size() - IsArray;
1703}
1704
Richard Smith180f4792011-11-10 06:34:14 +00001705/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1706/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1707/// for looking up the glvalue referred to by an entity of reference type.
1708///
1709/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001710/// \param Conv - The expression for which we are performing the conversion.
1711/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001712/// \param Type - The type we expect this conversion to produce, before
1713/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001714/// \param LVal - The glvalue on which we are attempting to perform this action.
1715/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001716static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1717 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001718 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001719 if (LVal.Designator.Invalid)
1720 // A diagnostic will have already been produced.
1721 return false;
1722
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001723 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001724
Richard Smithf48fdb02011-12-09 22:58:01 +00001725 if (!LVal.Base) {
1726 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001727 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001728 return false;
1729 }
1730
Richard Smith83587db2012-02-15 02:18:13 +00001731 CallStackFrame *Frame = 0;
1732 if (LVal.CallIndex) {
1733 Frame = Info.getCallFrame(LVal.CallIndex);
1734 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001735 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001736 NoteLValueLocation(Info, LVal.Base);
1737 return false;
1738 }
1739 }
1740
Richard Smith7098cbd2011-12-21 05:04:46 +00001741 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1742 // is not a constant expression (even if the object is non-volatile). We also
1743 // apply this rule to C++98, in order to conform to the expected 'volatile'
1744 // semantics.
1745 if (Type.isVolatileQualified()) {
1746 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001747 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001748 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001749 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001750 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001751 }
Richard Smithc49bd112011-10-28 17:51:58 +00001752
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001753 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001754 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1755 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001756 // expressions are constant expressions too. Inside constexpr functions,
1757 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001758 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001759 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregord2008e22012-04-06 22:40:38 +00001760 if (VD) {
1761 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1762 VD = VDef;
1763 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001764 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001765 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001766 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001767 }
1768
Richard Smith7098cbd2011-12-21 05:04:46 +00001769 // DR1313: If the object is volatile-qualified but the glvalue was not,
1770 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001771 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001772 if (VT.isVolatileQualified()) {
1773 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001774 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001775 Info.Note(VD->getLocation(), diag::note_declared_at);
1776 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001777 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001778 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001779 return false;
1780 }
1781
1782 if (!isa<ParmVarDecl>(VD)) {
1783 if (VD->isConstexpr()) {
1784 // OK, we can read this variable.
1785 } else if (VT->isIntegralOrEnumerationType()) {
1786 if (!VT.isConstQualified()) {
1787 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001788 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001789 Info.Note(VD->getLocation(), diag::note_declared_at);
1790 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001791 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001792 }
1793 return false;
1794 }
1795 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1796 // We support folding of const floating-point types, in order to make
1797 // static const data members of such types (supported as an extension)
1798 // more useful.
Richard Smith80ad52f2013-01-02 11:42:31 +00001799 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001800 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001801 Info.Note(VD->getLocation(), diag::note_declared_at);
1802 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001803 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001804 }
1805 } else {
1806 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smith80ad52f2013-01-02 11:42:31 +00001807 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001808 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001809 Info.Note(VD->getLocation(), diag::note_declared_at);
1810 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001811 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001812 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001813 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001814 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001815 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001816
Richard Smithf48fdb02011-12-09 22:58:01 +00001817 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001818 return false;
1819
Richard Smith47a1eed2011-10-29 20:57:55 +00001820 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001821 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001822
1823 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1824 // conversion. This happens when the declaration and the lvalue should be
1825 // considered synonymous, for instance when initializing an array of char
1826 // from a string literal. Continue as if the initializer lvalue was the
1827 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001828 assert(RVal.getLValueOffset().isZero() &&
1829 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001830 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001831
1832 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1833 Frame = Info.getCallFrame(CallIndex);
1834 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001835 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001836 NoteLValueLocation(Info, RVal.getLValueBase());
1837 return false;
1838 }
1839 } else {
1840 Frame = 0;
1841 }
Richard Smithc49bd112011-10-28 17:51:58 +00001842 }
1843
Richard Smith7098cbd2011-12-21 05:04:46 +00001844 // Volatile temporary objects cannot be read in constant expressions.
1845 if (Base->getType().isVolatileQualified()) {
1846 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001847 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001848 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1849 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001850 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001851 }
1852 return false;
1853 }
1854
Richard Smithcc5d4f62011-11-07 09:22:26 +00001855 if (Frame) {
1856 // If this is a temporary expression with a nontrivial initializer, grab the
1857 // value from the relevant stack frame.
1858 RVal = Frame->Temporaries[Base];
1859 } else if (const CompoundLiteralExpr *CLE
1860 = dyn_cast<CompoundLiteralExpr>(Base)) {
1861 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1862 // initializer until now for such expressions. Such an expression can't be
1863 // an ICE in C, so this only matters for fold.
1864 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1865 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1866 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001867 } else if (isa<StringLiteral>(Base)) {
1868 // We represent a string literal array as an lvalue pointing at the
1869 // corresponding expression, rather than building an array of chars.
1870 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001871 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001872 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001873 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001874 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001875 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001876
Richard Smithf48fdb02011-12-09 22:58:01 +00001877 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1878 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001879}
1880
Richard Smith59efe262011-11-11 04:05:33 +00001881/// Build an lvalue for the object argument of a member function call.
1882static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1883 LValue &This) {
1884 if (Object->getType()->isPointerType())
1885 return EvaluatePointer(Object, This, Info);
1886
1887 if (Object->isGLValue())
1888 return EvaluateLValue(Object, This, Info);
1889
Richard Smithe24f5fc2011-11-17 22:56:20 +00001890 if (Object->getType()->isLiteralType())
1891 return EvaluateTemporary(Object, This, Info);
1892
1893 return false;
1894}
1895
1896/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1897/// lvalue referring to the result.
1898///
1899/// \param Info - Information about the ongoing evaluation.
1900/// \param BO - The member pointer access operation.
1901/// \param LV - Filled in with a reference to the resulting object.
1902/// \param IncludeMember - Specifies whether the member itself is included in
1903/// the resulting LValue subobject designator. This is not possible when
1904/// creating a bound member function.
1905/// \return The field or method declaration to which the member pointer refers,
1906/// or 0 if evaluation fails.
1907static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1908 const BinaryOperator *BO,
1909 LValue &LV,
1910 bool IncludeMember = true) {
1911 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1912
Richard Smith745f5142012-01-27 01:14:48 +00001913 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1914 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001915 return 0;
1916
1917 MemberPtr MemPtr;
1918 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1919 return 0;
1920
1921 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1922 // member value, the behavior is undefined.
1923 if (!MemPtr.getDecl())
1924 return 0;
1925
Richard Smith745f5142012-01-27 01:14:48 +00001926 if (!EvalObjOK)
1927 return 0;
1928
Richard Smithe24f5fc2011-11-17 22:56:20 +00001929 if (MemPtr.isDerivedMember()) {
1930 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001931 // The end of the derived-to-base path for the base object must match the
1932 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001933 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001934 LV.Designator.Entries.size())
1935 return 0;
1936 unsigned PathLengthToMember =
1937 LV.Designator.Entries.size() - MemPtr.Path.size();
1938 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1939 const CXXRecordDecl *LVDecl = getAsBaseClass(
1940 LV.Designator.Entries[PathLengthToMember + I]);
1941 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1942 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1943 return 0;
1944 }
1945
1946 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001947 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1948 PathLengthToMember))
1949 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001950 } else if (!MemPtr.Path.empty()) {
1951 // Extend the LValue path with the member pointer's path.
1952 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1953 MemPtr.Path.size() + IncludeMember);
1954
1955 // Walk down to the appropriate base class.
1956 QualType LVType = BO->getLHS()->getType();
1957 if (const PointerType *PT = LVType->getAs<PointerType>())
1958 LVType = PT->getPointeeType();
1959 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1960 assert(RD && "member pointer access on non-class-type expression");
1961 // The first class in the path is that of the lvalue.
1962 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1963 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCall8d59dee2012-05-01 00:38:49 +00001964 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1965 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001966 RD = Base;
1967 }
1968 // Finally cast to the class containing the member.
John McCall8d59dee2012-05-01 00:38:49 +00001969 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1970 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001971 }
1972
1973 // Add the member. Note that we cannot build bound member functions here.
1974 if (IncludeMember) {
John McCall8d59dee2012-05-01 00:38:49 +00001975 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
1976 if (!HandleLValueMember(Info, BO, LV, FD))
1977 return 0;
1978 } else if (const IndirectFieldDecl *IFD =
1979 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
1980 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
1981 return 0;
1982 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00001983 llvm_unreachable("can't construct reference to bound member function");
John McCall8d59dee2012-05-01 00:38:49 +00001984 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001985 }
1986
1987 return MemPtr.getDecl();
1988}
1989
1990/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1991/// the provided lvalue, which currently refers to the base object.
1992static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1993 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001994 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001995 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001996 return false;
1997
Richard Smithb4e85ed2012-01-06 16:39:00 +00001998 QualType TargetQT = E->getType();
1999 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2000 TargetQT = PT->getPointeeType();
2001
2002 // Check this cast lands within the final derived-to-base subobject path.
2003 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002004 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002005 << D.MostDerivedType << TargetQT;
2006 return false;
2007 }
2008
Richard Smithe24f5fc2011-11-17 22:56:20 +00002009 // Check the type of the final cast. We don't need to check the path,
2010 // since a cast can only be formed if the path is unique.
2011 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002012 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2013 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002014 if (NewEntriesSize == D.MostDerivedPathLength)
2015 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2016 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002017 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002018 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002019 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002020 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002021 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002022 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002023
2024 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002025 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002026}
2027
Mike Stumpc4c90452009-10-27 22:09:17 +00002028namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002029enum EvalStmtResult {
2030 /// Evaluation failed.
2031 ESR_Failed,
2032 /// Hit a 'return' statement.
2033 ESR_Returned,
2034 /// Evaluation succeeded.
2035 ESR_Succeeded
2036};
2037}
2038
2039// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002040static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002041 const Stmt *S) {
2042 switch (S->getStmtClass()) {
2043 default:
2044 return ESR_Failed;
2045
2046 case Stmt::NullStmtClass:
2047 case Stmt::DeclStmtClass:
2048 return ESR_Succeeded;
2049
Richard Smithc1c5f272011-12-13 06:39:58 +00002050 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002051 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002052 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002053 return ESR_Failed;
2054 return ESR_Returned;
2055 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002056
2057 case Stmt::CompoundStmtClass: {
2058 const CompoundStmt *CS = cast<CompoundStmt>(S);
2059 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2060 BE = CS->body_end(); BI != BE; ++BI) {
2061 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2062 if (ESR != ESR_Succeeded)
2063 return ESR;
2064 }
2065 return ESR_Succeeded;
2066 }
2067 }
2068}
2069
Richard Smith61802452011-12-22 02:22:31 +00002070/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2071/// default constructor. If so, we'll fold it whether or not it's marked as
2072/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2073/// so we need special handling.
2074static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002075 const CXXConstructorDecl *CD,
2076 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002077 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2078 return false;
2079
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002080 // Value-initialization does not call a trivial default constructor, so such a
2081 // call is a core constant expression whether or not the constructor is
2082 // constexpr.
2083 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith80ad52f2013-01-02 11:42:31 +00002084 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002085 // FIXME: If DiagDecl is an implicitly-declared special member function,
2086 // we should be much more explicit about why it's not constexpr.
2087 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2088 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2089 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002090 } else {
2091 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2092 }
2093 }
2094 return true;
2095}
2096
Richard Smithc1c5f272011-12-13 06:39:58 +00002097/// CheckConstexprFunction - Check that a function can be called in a constant
2098/// expression.
2099static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2100 const FunctionDecl *Declaration,
2101 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002102 // Potential constant expressions can contain calls to declared, but not yet
2103 // defined, constexpr functions.
2104 if (Info.CheckingPotentialConstantExpression && !Definition &&
2105 Declaration->isConstexpr())
2106 return false;
2107
Richard Smithc1c5f272011-12-13 06:39:58 +00002108 // Can we evaluate this function call?
2109 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2110 return true;
2111
Richard Smith80ad52f2013-01-02 11:42:31 +00002112 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithc1c5f272011-12-13 06:39:58 +00002113 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002114 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2115 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002116 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2117 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2118 << DiagDecl;
2119 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2120 } else {
2121 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2122 }
2123 return false;
2124}
2125
Richard Smith180f4792011-11-10 06:34:14 +00002126namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002127typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002128}
2129
2130/// EvaluateArgs - Evaluate the arguments to a function call.
2131static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2132 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002133 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002134 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002135 I != E; ++I) {
2136 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2137 // If we're checking for a potential constant expression, evaluate all
2138 // initializers even if some of them fail.
2139 if (!Info.keepEvaluatingAfterFailure())
2140 return false;
2141 Success = false;
2142 }
2143 }
2144 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002145}
2146
Richard Smithd0dccea2011-10-28 22:34:42 +00002147/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002148static bool HandleFunctionCall(SourceLocation CallLoc,
2149 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002150 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002151 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002152 ArgVector ArgValues(Args.size());
2153 if (!EvaluateArgs(Args, ArgValues, Info))
2154 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002155
Richard Smith745f5142012-01-27 01:14:48 +00002156 if (!Info.CheckCallLimit(CallLoc))
2157 return false;
2158
2159 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002160 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2161}
2162
Richard Smith180f4792011-11-10 06:34:14 +00002163/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002164static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002165 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002166 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002167 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002168 ArgVector ArgValues(Args.size());
2169 if (!EvaluateArgs(Args, ArgValues, Info))
2170 return false;
2171
Richard Smith745f5142012-01-27 01:14:48 +00002172 if (!Info.CheckCallLimit(CallLoc))
2173 return false;
2174
Richard Smith86c3ae42012-02-13 03:54:03 +00002175 const CXXRecordDecl *RD = Definition->getParent();
2176 if (RD->getNumVBases()) {
2177 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2178 return false;
2179 }
2180
Richard Smith745f5142012-01-27 01:14:48 +00002181 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002182
2183 // If it's a delegating constructor, just delegate.
2184 if (Definition->isDelegatingConstructor()) {
2185 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002186 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002187 }
2188
Richard Smith610a60c2012-01-10 04:32:03 +00002189 // For a trivial copy or move constructor, perform an APValue copy. This is
2190 // essential for unions, where the operations performed by the constructor
2191 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002192 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002193 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2194 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002195 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002196 RHS.setFrom(Info.Ctx, ArgValues[0]);
2197 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2198 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002199 }
2200
2201 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002202 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002203 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2204 std::distance(RD->field_begin(), RD->field_end()));
2205
John McCall8d59dee2012-05-01 00:38:49 +00002206 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00002207 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2208
Richard Smith745f5142012-01-27 01:14:48 +00002209 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002210 unsigned BasesSeen = 0;
2211#ifndef NDEBUG
2212 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2213#endif
2214 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2215 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002216 LValue Subobject = This;
2217 APValue *Value = &Result;
2218
2219 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002220 if ((*I)->isBaseInitializer()) {
2221 QualType BaseType((*I)->getBaseClass(), 0);
2222#ifndef NDEBUG
2223 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002224 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002225 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2226 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2227 "base class initializers not in expected order");
2228 ++BaseIt;
2229#endif
John McCall8d59dee2012-05-01 00:38:49 +00002230 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2231 BaseType->getAsCXXRecordDecl(), &Layout))
2232 return false;
Richard Smith745f5142012-01-27 01:14:48 +00002233 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002234 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCall8d59dee2012-05-01 00:38:49 +00002235 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2236 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002237 if (RD->isUnion()) {
2238 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002239 Value = &Result.getUnionValue();
2240 } else {
2241 Value = &Result.getStructField(FD->getFieldIndex());
2242 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002243 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002244 // Walk the indirect field decl's chain to find the object to initialize,
2245 // and make sure we've initialized every step along it.
2246 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2247 CE = IFD->chain_end();
2248 C != CE; ++C) {
2249 FieldDecl *FD = cast<FieldDecl>(*C);
2250 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2251 // Switch the union field if it differs. This happens if we had
2252 // preceding zero-initialization, and we're now initializing a union
2253 // subobject other than the first.
2254 // FIXME: In this case, the values of the other subobjects are
2255 // specified, since zero-initialization sets all padding bits to zero.
2256 if (Value->isUninit() ||
2257 (Value->isUnion() && Value->getUnionField() != FD)) {
2258 if (CD->isUnion())
2259 *Value = APValue(FD);
2260 else
2261 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2262 std::distance(CD->field_begin(), CD->field_end()));
2263 }
John McCall8d59dee2012-05-01 00:38:49 +00002264 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2265 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002266 if (CD->isUnion())
2267 Value = &Value->getUnionValue();
2268 else
2269 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002270 }
Richard Smith180f4792011-11-10 06:34:14 +00002271 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002272 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002273 }
Richard Smith745f5142012-01-27 01:14:48 +00002274
Richard Smith83587db2012-02-15 02:18:13 +00002275 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2276 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002277 ? CCEK_Constant : CCEK_MemberInit)) {
2278 // If we're checking for a potential constant expression, evaluate all
2279 // initializers even if some of them fail.
2280 if (!Info.keepEvaluatingAfterFailure())
2281 return false;
2282 Success = false;
2283 }
Richard Smith180f4792011-11-10 06:34:14 +00002284 }
2285
Richard Smith745f5142012-01-27 01:14:48 +00002286 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002287}
2288
Eli Friedman4efaa272008-11-12 09:44:48 +00002289//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002290// Generic Evaluation
2291//===----------------------------------------------------------------------===//
2292namespace {
2293
Richard Smithf48fdb02011-12-09 22:58:01 +00002294// FIXME: RetTy is always bool. Remove it.
2295template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002296class ExprEvaluatorBase
2297 : public ConstStmtVisitor<Derived, RetTy> {
2298private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002299 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002300 return static_cast<Derived*>(this)->Success(V, E);
2301 }
Richard Smith51201882011-12-30 21:15:51 +00002302 RetTy DerivedZeroInitialization(const Expr *E) {
2303 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002304 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002305
Richard Smith74e1ad92012-02-16 02:46:34 +00002306 // Check whether a conditional operator with a non-constant condition is a
2307 // potential constant expression. If neither arm is a potential constant
2308 // expression, then the conditional operator is not either.
2309 template<typename ConditionalOperator>
2310 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2311 assert(Info.CheckingPotentialConstantExpression);
2312
2313 // Speculatively evaluate both arms.
2314 {
2315 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2316 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2317
2318 StmtVisitorTy::Visit(E->getFalseExpr());
2319 if (Diag.empty())
2320 return;
2321
2322 Diag.clear();
2323 StmtVisitorTy::Visit(E->getTrueExpr());
2324 if (Diag.empty())
2325 return;
2326 }
2327
2328 Error(E, diag::note_constexpr_conditional_never_const);
2329 }
2330
2331
2332 template<typename ConditionalOperator>
2333 bool HandleConditionalOperator(const ConditionalOperator *E) {
2334 bool BoolResult;
2335 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2336 if (Info.CheckingPotentialConstantExpression)
2337 CheckPotentialConstantConditional(E);
2338 return false;
2339 }
2340
2341 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2342 return StmtVisitorTy::Visit(EvalExpr);
2343 }
2344
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002345protected:
2346 EvalInfo &Info;
2347 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2348 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2349
Richard Smithdd1f29b2011-12-12 09:28:41 +00002350 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002351 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002352 }
2353
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00002354 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2355
2356public:
2357 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2358
2359 EvalInfo &getEvalInfo() { return Info; }
2360
Richard Smithf48fdb02011-12-09 22:58:01 +00002361 /// Report an evaluation error. This should only be called when an error is
2362 /// first discovered. When propagating an error, just return false.
2363 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002364 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002365 return false;
2366 }
2367 bool Error(const Expr *E) {
2368 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2369 }
2370
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002371 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002372 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002373 }
2374 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002375 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002376 }
2377
2378 RetTy VisitParenExpr(const ParenExpr *E)
2379 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2380 RetTy VisitUnaryExtension(const UnaryOperator *E)
2381 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2382 RetTy VisitUnaryPlus(const UnaryOperator *E)
2383 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2384 RetTy VisitChooseExpr(const ChooseExpr *E)
2385 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2386 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2387 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002388 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2389 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002390 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2391 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002392 // We cannot create any objects for which cleanups are required, so there is
2393 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2394 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2395 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002396
Richard Smithc216a012011-12-12 12:46:16 +00002397 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2398 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2399 return static_cast<Derived*>(this)->VisitCastExpr(E);
2400 }
2401 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2402 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2403 return static_cast<Derived*>(this)->VisitCastExpr(E);
2404 }
2405
Richard Smithe24f5fc2011-11-17 22:56:20 +00002406 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2407 switch (E->getOpcode()) {
2408 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002409 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002410
2411 case BO_Comma:
2412 VisitIgnoredValue(E->getLHS());
2413 return StmtVisitorTy::Visit(E->getRHS());
2414
2415 case BO_PtrMemD:
2416 case BO_PtrMemI: {
2417 LValue Obj;
2418 if (!HandleMemberPointerAccess(Info, E, Obj))
2419 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002420 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002421 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002422 return false;
2423 return DerivedSuccess(Result, E);
2424 }
2425 }
2426 }
2427
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002428 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002429 // Evaluate and cache the common expression. We treat it as a temporary,
2430 // even though it's not quite the same thing.
2431 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2432 Info, E->getCommon()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002433 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002434
Richard Smith74e1ad92012-02-16 02:46:34 +00002435 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002436 }
2437
2438 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002439 bool IsBcpCall = false;
2440 // If the condition (ignoring parens) is a __builtin_constant_p call,
2441 // the result is a constant expression if it can be folded without
2442 // side-effects. This is an important GNU extension. See GCC PR38377
2443 // for discussion.
2444 if (const CallExpr *CallCE =
2445 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2446 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2447 IsBcpCall = true;
2448
2449 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2450 // constant expression; we can't check whether it's potentially foldable.
2451 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2452 return false;
2453
2454 FoldConstant Fold(Info);
2455
Richard Smith74e1ad92012-02-16 02:46:34 +00002456 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002457 return false;
2458
2459 if (IsBcpCall)
2460 Fold.Fold(Info);
2461
2462 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002463 }
2464
2465 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002466 APValue &Value = Info.CurrentCall->Temporaries[E];
2467 if (Value.isUninit()) {
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002468 const Expr *Source = E->getSourceExpr();
2469 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002470 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002471 if (Source == E) { // sanity checking.
2472 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002473 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002474 }
2475 return StmtVisitorTy::Visit(Source);
2476 }
Richard Smithe92b1f42012-06-26 08:12:11 +00002477 return DerivedSuccess(Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002478 }
Richard Smithf10d9172011-10-11 21:43:33 +00002479
Richard Smithd0dccea2011-10-28 22:34:42 +00002480 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002481 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002482 QualType CalleeType = Callee->getType();
2483
Richard Smithd0dccea2011-10-28 22:34:42 +00002484 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002485 LValue *This = 0, ThisVal;
2486 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002487 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002488
Richard Smith59efe262011-11-11 04:05:33 +00002489 // Extract function decl and 'this' pointer from the callee.
2490 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002491 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002492 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2493 // Explicit bound member calls, such as x.f() or p->g();
2494 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002495 return false;
2496 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002497 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002498 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002499 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2500 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002501 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2502 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002503 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002504 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002505 return Error(Callee);
2506
2507 FD = dyn_cast<FunctionDecl>(Member);
2508 if (!FD)
2509 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002510 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002511 LValue Call;
2512 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002513 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002514
Richard Smithb4e85ed2012-01-06 16:39:00 +00002515 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002516 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002517 FD = dyn_cast_or_null<FunctionDecl>(
2518 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002519 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002520 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002521
2522 // Overloaded operator calls to member functions are represented as normal
2523 // calls with '*this' as the first argument.
2524 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2525 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002526 // FIXME: When selecting an implicit conversion for an overloaded
2527 // operator delete, we sometimes try to evaluate calls to conversion
2528 // operators without a 'this' parameter!
2529 if (Args.empty())
2530 return Error(E);
2531
Richard Smith59efe262011-11-11 04:05:33 +00002532 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2533 return false;
2534 This = &ThisVal;
2535 Args = Args.slice(1);
2536 }
2537
2538 // Don't call function pointers which have been cast to some other type.
2539 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002540 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002541 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002542 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002543
Richard Smithb04035a2012-02-01 02:39:43 +00002544 if (This && !This->checkSubobject(Info, E, CSK_This))
2545 return false;
2546
Richard Smith86c3ae42012-02-13 03:54:03 +00002547 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2548 // calls to such functions in constant expressions.
2549 if (This && !HasQualifier &&
2550 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2551 return Error(E, diag::note_constexpr_virtual_call);
2552
Richard Smithc1c5f272011-12-13 06:39:58 +00002553 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002554 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002555 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002556
Richard Smithc1c5f272011-12-13 06:39:58 +00002557 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002558 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2559 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002560 return false;
2561
Richard Smith83587db2012-02-15 02:18:13 +00002562 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002563 }
2564
Richard Smithc49bd112011-10-28 17:51:58 +00002565 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2566 return StmtVisitorTy::Visit(E->getInitializer());
2567 }
Richard Smithf10d9172011-10-11 21:43:33 +00002568 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002569 if (E->getNumInits() == 0)
2570 return DerivedZeroInitialization(E);
2571 if (E->getNumInits() == 1)
2572 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002573 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002574 }
2575 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002576 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002577 }
2578 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002579 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002580 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002581 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002582 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002583 }
Richard Smithf10d9172011-10-11 21:43:33 +00002584
Richard Smith180f4792011-11-10 06:34:14 +00002585 /// A member expression where the object is a prvalue is itself a prvalue.
2586 RetTy VisitMemberExpr(const MemberExpr *E) {
2587 assert(!E->isArrow() && "missing call to bound member function?");
2588
Richard Smith1aa0be82012-03-03 22:46:17 +00002589 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002590 if (!Evaluate(Val, Info, E->getBase()))
2591 return false;
2592
2593 QualType BaseTy = E->getBase()->getType();
2594
2595 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002596 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002597 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek890f0f12012-08-23 20:46:57 +00002598 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smith180f4792011-11-10 06:34:14 +00002599 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2600
Richard Smithb4e85ed2012-01-06 16:39:00 +00002601 SubobjectDesignator Designator(BaseTy);
2602 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002603
Richard Smithf48fdb02011-12-09 22:58:01 +00002604 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002605 DerivedSuccess(Val, E);
2606 }
2607
Richard Smithc49bd112011-10-28 17:51:58 +00002608 RetTy VisitCastExpr(const CastExpr *E) {
2609 switch (E->getCastKind()) {
2610 default:
2611 break;
2612
David Chisnall7a7ee302012-01-16 17:27:18 +00002613 case CK_AtomicToNonAtomic:
2614 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002615 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002616 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002617 return StmtVisitorTy::Visit(E->getSubExpr());
2618
2619 case CK_LValueToRValue: {
2620 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002621 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2622 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002623 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002624 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2625 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2626 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002627 return false;
2628 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002629 }
2630 }
2631
Richard Smithf48fdb02011-12-09 22:58:01 +00002632 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002633 }
2634
Richard Smith8327fad2011-10-24 18:44:57 +00002635 /// Visit a value which is evaluated, but whose value is ignored.
2636 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002637 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002638 if (!Evaluate(Scratch, Info, E))
2639 Info.EvalStatus.HasSideEffects = true;
2640 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002641};
2642
2643}
2644
2645//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002646// Common base class for lvalue and temporary evaluation.
2647//===----------------------------------------------------------------------===//
2648namespace {
2649template<class Derived>
2650class LValueExprEvaluatorBase
2651 : public ExprEvaluatorBase<Derived, bool> {
2652protected:
2653 LValue &Result;
2654 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2655 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2656
2657 bool Success(APValue::LValueBase B) {
2658 Result.set(B);
2659 return true;
2660 }
2661
2662public:
2663 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2664 ExprEvaluatorBaseTy(Info), Result(Result) {}
2665
Richard Smith1aa0be82012-03-03 22:46:17 +00002666 bool Success(const APValue &V, const Expr *E) {
2667 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002668 return true;
2669 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002670
Richard Smithe24f5fc2011-11-17 22:56:20 +00002671 bool VisitMemberExpr(const MemberExpr *E) {
2672 // Handle non-static data members.
2673 QualType BaseTy;
2674 if (E->isArrow()) {
2675 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2676 return false;
Ted Kremenek890f0f12012-08-23 20:46:57 +00002677 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002678 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002679 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002680 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2681 return false;
2682 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002683 } else {
2684 if (!this->Visit(E->getBase()))
2685 return false;
2686 BaseTy = E->getBase()->getType();
2687 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002688
Richard Smithd9b02e72012-01-25 22:15:11 +00002689 const ValueDecl *MD = E->getMemberDecl();
2690 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2691 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2692 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2693 (void)BaseTy;
John McCall8d59dee2012-05-01 00:38:49 +00002694 if (!HandleLValueMember(this->Info, E, Result, FD))
2695 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002696 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCall8d59dee2012-05-01 00:38:49 +00002697 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2698 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002699 } else
2700 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002701
Richard Smithd9b02e72012-01-25 22:15:11 +00002702 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002703 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002704 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002705 RefValue))
2706 return false;
2707 return Success(RefValue, E);
2708 }
2709 return true;
2710 }
2711
2712 bool VisitBinaryOperator(const BinaryOperator *E) {
2713 switch (E->getOpcode()) {
2714 default:
2715 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2716
2717 case BO_PtrMemD:
2718 case BO_PtrMemI:
2719 return HandleMemberPointerAccess(this->Info, E, Result);
2720 }
2721 }
2722
2723 bool VisitCastExpr(const CastExpr *E) {
2724 switch (E->getCastKind()) {
2725 default:
2726 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2727
2728 case CK_DerivedToBase:
2729 case CK_UncheckedDerivedToBase: {
2730 if (!this->Visit(E->getSubExpr()))
2731 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002732
2733 // Now figure out the necessary offset to add to the base LV to get from
2734 // the derived class to the base class.
2735 QualType Type = E->getSubExpr()->getType();
2736
2737 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2738 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002739 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002740 *PathI))
2741 return false;
2742 Type = (*PathI)->getType();
2743 }
2744
2745 return true;
2746 }
2747 }
2748 }
2749};
2750}
2751
2752//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002753// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002754//
2755// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2756// function designators (in C), decl references to void objects (in C), and
2757// temporaries (if building with -Wno-address-of-temporary).
2758//
2759// LValue evaluation produces values comprising a base expression of one of the
2760// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002761// - Declarations
2762// * VarDecl
2763// * FunctionDecl
2764// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002765// * CompoundLiteralExpr in C
2766// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002767// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002768// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002769// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002770// * ObjCEncodeExpr
2771// * AddrLabelExpr
2772// * BlockExpr
2773// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002774// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002775// * Any Expr, with a CallIndex indicating the function in which the temporary
2776// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002777// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002778//===----------------------------------------------------------------------===//
2779namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002780class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002781 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002782public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002783 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2784 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002785
Richard Smithc49bd112011-10-28 17:51:58 +00002786 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2787
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002788 bool VisitDeclRefExpr(const DeclRefExpr *E);
2789 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002790 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002791 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2792 bool VisitMemberExpr(const MemberExpr *E);
2793 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2794 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002795 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichete275a182012-04-16 04:08:35 +00002796 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002797 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2798 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002799 bool VisitUnaryReal(const UnaryOperator *E);
2800 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002801
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002802 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002803 switch (E->getCastKind()) {
2804 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002805 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002806
Eli Friedmandb924222011-10-11 00:13:24 +00002807 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002808 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002809 if (!Visit(E->getSubExpr()))
2810 return false;
2811 Result.Designator.setInvalid();
2812 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002813
Richard Smithe24f5fc2011-11-17 22:56:20 +00002814 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002815 if (!Visit(E->getSubExpr()))
2816 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002817 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002818 }
2819 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002820};
2821} // end anonymous namespace
2822
Richard Smithc49bd112011-10-28 17:51:58 +00002823/// Evaluate an expression as an lvalue. This can be legitimately called on
2824/// expressions which are not glvalues, in a few cases:
2825/// * function designators in C,
2826/// * "extern void" objects,
2827/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002828static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002829 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2830 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2831 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002832 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002833}
2834
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002835bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002836 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2837 return Success(FD);
2838 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002839 return VisitVarDecl(E, VD);
2840 return Error(E);
2841}
Richard Smith436c8892011-10-24 23:14:33 +00002842
Richard Smithc49bd112011-10-28 17:51:58 +00002843bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002844 if (!VD->getType()->isReferenceType()) {
2845 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002846 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002847 return true;
2848 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002849 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002850 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002851
Richard Smith1aa0be82012-03-03 22:46:17 +00002852 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002853 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2854 return false;
2855 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002856}
2857
Richard Smithbd552ef2011-10-31 05:52:43 +00002858bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2859 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002860 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002861 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002862 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2863
Richard Smith83587db2012-02-15 02:18:13 +00002864 Result.set(E, Info.CurrentCall->Index);
2865 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2866 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002867 }
2868
2869 // Materialization of an lvalue temporary occurs when we need to force a copy
2870 // (for instance, if it's a bitfield).
2871 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2872 if (!Visit(E->GetTemporaryExpr()))
2873 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002874 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002875 Info.CurrentCall->Temporaries[E]))
2876 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002877 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002878 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002879}
2880
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002881bool
2882LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002883 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2884 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2885 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002886 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002887}
2888
Richard Smith47d21452011-12-27 12:18:28 +00002889bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith9be36ab2012-10-17 23:52:07 +00002890 if (!E->isPotentiallyEvaluated())
Richard Smith47d21452011-12-27 12:18:28 +00002891 return Success(E);
Richard Smith9be36ab2012-10-17 23:52:07 +00002892
2893 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
2894 << E->getExprOperand()->getType()
2895 << E->getExprOperand()->getSourceRange();
2896 return false;
Richard Smith47d21452011-12-27 12:18:28 +00002897}
2898
Francois Pichete275a182012-04-16 04:08:35 +00002899bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2900 return Success(E);
2901}
2902
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002903bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002904 // Handle static data members.
2905 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2906 VisitIgnoredValue(E->getBase());
2907 return VisitVarDecl(E, VD);
2908 }
2909
Richard Smithd0dccea2011-10-28 22:34:42 +00002910 // Handle static member functions.
2911 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2912 if (MD->isStatic()) {
2913 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002914 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002915 }
2916 }
2917
Richard Smith180f4792011-11-10 06:34:14 +00002918 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002919 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002920}
2921
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002922bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002923 // FIXME: Deal with vectors as array subscript bases.
2924 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002925 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002926
Anders Carlsson3068d112008-11-16 19:01:22 +00002927 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002928 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002929
Anders Carlsson3068d112008-11-16 19:01:22 +00002930 APSInt Index;
2931 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002932 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002933 int64_t IndexValue
2934 = Index.isSigned() ? Index.getSExtValue()
2935 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002936
Richard Smithb4e85ed2012-01-06 16:39:00 +00002937 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002938}
Eli Friedman4efaa272008-11-12 09:44:48 +00002939
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002940bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002941 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002942}
2943
Richard Smith86024012012-02-18 22:04:06 +00002944bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2945 if (!Visit(E->getSubExpr()))
2946 return false;
2947 // __real is a no-op on scalar lvalues.
2948 if (E->getSubExpr()->getType()->isAnyComplexType())
2949 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
2950 return true;
2951}
2952
2953bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
2954 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
2955 "lvalue __imag__ on scalar?");
2956 if (!Visit(E->getSubExpr()))
2957 return false;
2958 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
2959 return true;
2960}
2961
Eli Friedman4efaa272008-11-12 09:44:48 +00002962//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002963// Pointer Evaluation
2964//===----------------------------------------------------------------------===//
2965
Anders Carlssonc754aa62008-07-08 05:13:58 +00002966namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002967class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002968 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002969 LValue &Result;
2970
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002971 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002972 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002973 return true;
2974 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002975public:
Mike Stump1eb44332009-09-09 15:08:12 +00002976
John McCallefdb83e2010-05-07 21:00:08 +00002977 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002978 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002979
Richard Smith1aa0be82012-03-03 22:46:17 +00002980 bool Success(const APValue &V, const Expr *E) {
2981 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002982 return true;
2983 }
Richard Smith51201882011-12-30 21:15:51 +00002984 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002985 return Success((Expr*)0);
2986 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002987
John McCallefdb83e2010-05-07 21:00:08 +00002988 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002989 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002990 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002991 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002992 { return Success(E); }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002993 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002994 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002995 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002996 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002997 bool VisitCallExpr(const CallExpr *E);
2998 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002999 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003000 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003001 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003002 }
Richard Smith180f4792011-11-10 06:34:14 +00003003 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3004 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003005 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003006 Result = *Info.CurrentCall->This;
3007 return true;
3008 }
John McCall56ca35d2011-02-17 10:25:35 +00003009
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003010 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003011};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003012} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003013
John McCallefdb83e2010-05-07 21:00:08 +00003014static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003015 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003016 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003017}
3018
John McCallefdb83e2010-05-07 21:00:08 +00003019bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003020 if (E->getOpcode() != BO_Add &&
3021 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003022 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003023
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003024 const Expr *PExp = E->getLHS();
3025 const Expr *IExp = E->getRHS();
3026 if (IExp->getType()->isPointerType())
3027 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003028
Richard Smith745f5142012-01-27 01:14:48 +00003029 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3030 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003031 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003032
John McCallefdb83e2010-05-07 21:00:08 +00003033 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003034 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003035 return false;
3036 int64_t AdditionalOffset
3037 = Offset.isSigned() ? Offset.getSExtValue()
3038 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003039 if (E->getOpcode() == BO_Sub)
3040 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003041
Ted Kremenek890f0f12012-08-23 20:46:57 +00003042 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003043 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3044 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003045}
Eli Friedman4efaa272008-11-12 09:44:48 +00003046
John McCallefdb83e2010-05-07 21:00:08 +00003047bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3048 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003049}
Mike Stump1eb44332009-09-09 15:08:12 +00003050
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003051bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3052 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003053
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003054 switch (E->getCastKind()) {
3055 default:
3056 break;
3057
John McCall2de56d12010-08-25 11:45:40 +00003058 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003059 case CK_CPointerToObjCPointerCast:
3060 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003061 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003062 if (!Visit(SubExpr))
3063 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003064 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3065 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3066 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003067 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003068 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003069 if (SubExpr->getType()->isVoidPointerType())
3070 CCEDiag(E, diag::note_constexpr_invalid_cast)
3071 << 3 << SubExpr->getType();
3072 else
3073 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3074 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003075 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003076
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003077 case CK_DerivedToBase:
3078 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003079 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003080 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003081 if (!Result.Base && Result.Offset.isZero())
3082 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003083
Richard Smith180f4792011-11-10 06:34:14 +00003084 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003085 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003086 QualType Type =
3087 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003088
Richard Smith180f4792011-11-10 06:34:14 +00003089 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003090 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003091 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3092 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003093 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003094 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003095 }
3096
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003097 return true;
3098 }
3099
Richard Smithe24f5fc2011-11-17 22:56:20 +00003100 case CK_BaseToDerived:
3101 if (!Visit(E->getSubExpr()))
3102 return false;
3103 if (!Result.Base && Result.Offset.isZero())
3104 return true;
3105 return HandleBaseToDerivedCast(Info, E, Result);
3106
Richard Smith47a1eed2011-10-29 20:57:55 +00003107 case CK_NullToPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003108 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003109 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003110
John McCall2de56d12010-08-25 11:45:40 +00003111 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003112 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3113
Richard Smith1aa0be82012-03-03 22:46:17 +00003114 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003115 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003116 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003117
John McCallefdb83e2010-05-07 21:00:08 +00003118 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003119 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3120 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003121 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003122 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003123 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003124 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003125 return true;
3126 } else {
3127 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003128 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003129 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003130 }
3131 }
John McCall2de56d12010-08-25 11:45:40 +00003132 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003133 if (SubExpr->isGLValue()) {
3134 if (!EvaluateLValue(SubExpr, Result, Info))
3135 return false;
3136 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003137 Result.set(SubExpr, Info.CurrentCall->Index);
3138 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3139 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003140 return false;
3141 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003142 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003143 if (const ConstantArrayType *CAT
3144 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3145 Result.addArray(Info, E, CAT);
3146 else
3147 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003148 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003149
John McCall2de56d12010-08-25 11:45:40 +00003150 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003151 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003152 }
3153
Richard Smithc49bd112011-10-28 17:51:58 +00003154 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003155}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003156
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003157bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003158 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003159 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003160
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003161 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003162}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003163
3164//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003165// Member Pointer Evaluation
3166//===----------------------------------------------------------------------===//
3167
3168namespace {
3169class MemberPointerExprEvaluator
3170 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3171 MemberPtr &Result;
3172
3173 bool Success(const ValueDecl *D) {
3174 Result = MemberPtr(D);
3175 return true;
3176 }
3177public:
3178
3179 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3180 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3181
Richard Smith1aa0be82012-03-03 22:46:17 +00003182 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003183 Result.setFrom(V);
3184 return true;
3185 }
Richard Smith51201882011-12-30 21:15:51 +00003186 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003187 return Success((const ValueDecl*)0);
3188 }
3189
3190 bool VisitCastExpr(const CastExpr *E);
3191 bool VisitUnaryAddrOf(const UnaryOperator *E);
3192};
3193} // end anonymous namespace
3194
3195static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3196 EvalInfo &Info) {
3197 assert(E->isRValue() && E->getType()->isMemberPointerType());
3198 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3199}
3200
3201bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3202 switch (E->getCastKind()) {
3203 default:
3204 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3205
3206 case CK_NullToMemberPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003207 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003208 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003209
3210 case CK_BaseToDerivedMemberPointer: {
3211 if (!Visit(E->getSubExpr()))
3212 return false;
3213 if (E->path_empty())
3214 return true;
3215 // Base-to-derived member pointer casts store the path in derived-to-base
3216 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3217 // the wrong end of the derived->base arc, so stagger the path by one class.
3218 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3219 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3220 PathI != PathE; ++PathI) {
3221 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3222 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3223 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003224 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003225 }
3226 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3227 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003228 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003229 return true;
3230 }
3231
3232 case CK_DerivedToBaseMemberPointer:
3233 if (!Visit(E->getSubExpr()))
3234 return false;
3235 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3236 PathE = E->path_end(); PathI != PathE; ++PathI) {
3237 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3238 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3239 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003240 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003241 }
3242 return true;
3243 }
3244}
3245
3246bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3247 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3248 // member can be formed.
3249 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3250}
3251
3252//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003253// Record Evaluation
3254//===----------------------------------------------------------------------===//
3255
3256namespace {
3257 class RecordExprEvaluator
3258 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3259 const LValue &This;
3260 APValue &Result;
3261 public:
3262
3263 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3264 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3265
Richard Smith1aa0be82012-03-03 22:46:17 +00003266 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003267 Result = V;
3268 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003269 }
Richard Smith51201882011-12-30 21:15:51 +00003270 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003271
Richard Smith59efe262011-11-11 04:05:33 +00003272 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003273 bool VisitInitListExpr(const InitListExpr *E);
3274 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3275 };
3276}
3277
Richard Smith51201882011-12-30 21:15:51 +00003278/// Perform zero-initialization on an object of non-union class type.
3279/// C++11 [dcl.init]p5:
3280/// To zero-initialize an object or reference of type T means:
3281/// [...]
3282/// -- if T is a (possibly cv-qualified) non-union class type,
3283/// each non-static data member and each base-class subobject is
3284/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003285static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3286 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003287 const LValue &This, APValue &Result) {
3288 assert(!RD->isUnion() && "Expected non-union class type");
3289 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3290 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3291 std::distance(RD->field_begin(), RD->field_end()));
3292
John McCall8d59dee2012-05-01 00:38:49 +00003293 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003294 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3295
3296 if (CD) {
3297 unsigned Index = 0;
3298 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003299 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003300 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3301 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003302 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3303 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003304 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003305 Result.getStructBase(Index)))
3306 return false;
3307 }
3308 }
3309
Richard Smithb4e85ed2012-01-06 16:39:00 +00003310 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3311 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003312 // -- if T is a reference type, no initialization is performed.
David Blaikie262bc182012-04-30 02:36:29 +00003313 if (I->getType()->isReferenceType())
Richard Smith51201882011-12-30 21:15:51 +00003314 continue;
3315
3316 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003317 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003318 return false;
Richard Smith51201882011-12-30 21:15:51 +00003319
David Blaikie262bc182012-04-30 02:36:29 +00003320 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003321 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003322 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003323 return false;
3324 }
3325
3326 return true;
3327}
3328
3329bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3330 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003331 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003332 if (RD->isUnion()) {
3333 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3334 // object's first non-static named data member is zero-initialized
3335 RecordDecl::field_iterator I = RD->field_begin();
3336 if (I == RD->field_end()) {
3337 Result = APValue((const FieldDecl*)0);
3338 return true;
3339 }
3340
3341 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003342 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCall8d59dee2012-05-01 00:38:49 +00003343 return false;
David Blaikie581deb32012-06-06 20:45:41 +00003344 Result = APValue(*I);
David Blaikie262bc182012-04-30 02:36:29 +00003345 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003346 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003347 }
3348
Richard Smithce582fe2012-02-17 00:44:16 +00003349 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003350 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003351 return false;
3352 }
3353
Richard Smithb4e85ed2012-01-06 16:39:00 +00003354 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003355}
3356
Richard Smith59efe262011-11-11 04:05:33 +00003357bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3358 switch (E->getCastKind()) {
3359 default:
3360 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3361
3362 case CK_ConstructorConversion:
3363 return Visit(E->getSubExpr());
3364
3365 case CK_DerivedToBase:
3366 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003367 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003368 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003369 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003370 if (!DerivedObject.isStruct())
3371 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003372
3373 // Derived-to-base rvalue conversion: just slice off the derived part.
3374 APValue *Value = &DerivedObject;
3375 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3376 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3377 PathE = E->path_end(); PathI != PathE; ++PathI) {
3378 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3379 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3380 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3381 RD = Base;
3382 }
3383 Result = *Value;
3384 return true;
3385 }
3386 }
3387}
3388
Richard Smith180f4792011-11-10 06:34:14 +00003389bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003390 // Cannot constant-evaluate std::initializer_list inits.
3391 if (E->initializesStdInitializerList())
3392 return false;
3393
Richard Smith180f4792011-11-10 06:34:14 +00003394 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003395 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00003396 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3397
3398 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003399 const FieldDecl *Field = E->getInitializedFieldInUnion();
3400 Result = APValue(Field);
3401 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003402 return true;
Richard Smithec789162012-01-12 18:54:33 +00003403
3404 // If the initializer list for a union does not contain any elements, the
3405 // first element of the union is value-initialized.
3406 ImplicitValueInitExpr VIE(Field->getType());
3407 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3408
Richard Smith180f4792011-11-10 06:34:14 +00003409 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003410 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3411 return false;
Richard Smith83587db2012-02-15 02:18:13 +00003412 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003413 }
3414
3415 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3416 "initializer list for class with base classes");
3417 Result = APValue(APValue::UninitStruct(), 0,
3418 std::distance(RD->field_begin(), RD->field_end()));
3419 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003420 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003421 for (RecordDecl::field_iterator Field = RD->field_begin(),
3422 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3423 // Anonymous bit-fields are not considered members of the class for
3424 // purposes of aggregate initialization.
3425 if (Field->isUnnamedBitfield())
3426 continue;
3427
3428 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003429
Richard Smith745f5142012-01-27 01:14:48 +00003430 bool HaveInit = ElementNo < E->getNumInits();
3431
3432 // FIXME: Diagnostics here should point to the end of the initializer
3433 // list, not the start.
John McCall8d59dee2012-05-01 00:38:49 +00003434 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie581deb32012-06-06 20:45:41 +00003435 Subobject, *Field, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003436 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003437
3438 // Perform an implicit value-initialization for members beyond the end of
3439 // the initializer list.
3440 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3441
Richard Smith83587db2012-02-15 02:18:13 +00003442 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003443 Result.getStructField(Field->getFieldIndex()),
Richard Smith745f5142012-01-27 01:14:48 +00003444 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3445 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003446 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003447 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003448 }
3449 }
3450
Richard Smith745f5142012-01-27 01:14:48 +00003451 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003452}
3453
3454bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3455 const CXXConstructorDecl *FD = E->getConstructor();
John McCall1de9d7d2012-04-26 18:10:01 +00003456 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3457
Richard Smith51201882011-12-30 21:15:51 +00003458 bool ZeroInit = E->requiresZeroInitialization();
3459 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003460 // If we've already performed zero-initialization, we're already done.
3461 if (!Result.isUninit())
3462 return true;
3463
Richard Smith51201882011-12-30 21:15:51 +00003464 if (ZeroInit)
3465 return ZeroInitialization(E);
3466
Richard Smith61802452011-12-22 02:22:31 +00003467 const CXXRecordDecl *RD = FD->getParent();
3468 if (RD->isUnion())
3469 Result = APValue((FieldDecl*)0);
3470 else
3471 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3472 std::distance(RD->field_begin(), RD->field_end()));
3473 return true;
3474 }
3475
Richard Smith180f4792011-11-10 06:34:14 +00003476 const FunctionDecl *Definition = 0;
3477 FD->getBody(Definition);
3478
Richard Smithc1c5f272011-12-13 06:39:58 +00003479 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3480 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003481
Richard Smith610a60c2012-01-10 04:32:03 +00003482 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003483 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003484 if (const MaterializeTemporaryExpr *ME
3485 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3486 return Visit(ME->GetTemporaryExpr());
3487
Richard Smith51201882011-12-30 21:15:51 +00003488 if (ZeroInit && !ZeroInitialization(E))
3489 return false;
3490
Richard Smith180f4792011-11-10 06:34:14 +00003491 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003492 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003493 cast<CXXConstructorDecl>(Definition), Info,
3494 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003495}
3496
3497static bool EvaluateRecord(const Expr *E, const LValue &This,
3498 APValue &Result, EvalInfo &Info) {
3499 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003500 "can't evaluate expression as a record rvalue");
3501 return RecordExprEvaluator(Info, This, Result).Visit(E);
3502}
3503
3504//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003505// Temporary Evaluation
3506//
3507// Temporaries are represented in the AST as rvalues, but generally behave like
3508// lvalues. The full-object of which the temporary is a subobject is implicitly
3509// materialized so that a reference can bind to it.
3510//===----------------------------------------------------------------------===//
3511namespace {
3512class TemporaryExprEvaluator
3513 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3514public:
3515 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3516 LValueExprEvaluatorBaseTy(Info, Result) {}
3517
3518 /// Visit an expression which constructs the value of this temporary.
3519 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003520 Result.set(E, Info.CurrentCall->Index);
3521 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003522 }
3523
3524 bool VisitCastExpr(const CastExpr *E) {
3525 switch (E->getCastKind()) {
3526 default:
3527 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3528
3529 case CK_ConstructorConversion:
3530 return VisitConstructExpr(E->getSubExpr());
3531 }
3532 }
3533 bool VisitInitListExpr(const InitListExpr *E) {
3534 return VisitConstructExpr(E);
3535 }
3536 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3537 return VisitConstructExpr(E);
3538 }
3539 bool VisitCallExpr(const CallExpr *E) {
3540 return VisitConstructExpr(E);
3541 }
3542};
3543} // end anonymous namespace
3544
3545/// Evaluate an expression of record type as a temporary.
3546static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003547 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003548 return TemporaryExprEvaluator(Info, Result).Visit(E);
3549}
3550
3551//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003552// Vector Evaluation
3553//===----------------------------------------------------------------------===//
3554
3555namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003556 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003557 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3558 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003559 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003560
Richard Smith07fc6572011-10-22 21:10:00 +00003561 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3562 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003563
Richard Smith07fc6572011-10-22 21:10:00 +00003564 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3565 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3566 // FIXME: remove this APValue copy.
3567 Result = APValue(V.data(), V.size());
3568 return true;
3569 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003570 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003571 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003572 Result = V;
3573 return true;
3574 }
Richard Smith51201882011-12-30 21:15:51 +00003575 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003576
Richard Smith07fc6572011-10-22 21:10:00 +00003577 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003578 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003579 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003580 bool VisitInitListExpr(const InitListExpr *E);
3581 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003582 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003583 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003584 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003585 };
3586} // end anonymous namespace
3587
3588static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003589 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003590 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003591}
3592
Richard Smith07fc6572011-10-22 21:10:00 +00003593bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3594 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003595 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003596
Richard Smithd62ca372011-12-06 22:44:34 +00003597 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003598 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003599
Eli Friedman46a52322011-03-25 00:43:55 +00003600 switch (E->getCastKind()) {
3601 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003602 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003603 if (SETy->isIntegerType()) {
3604 APSInt IntResult;
3605 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003606 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003607 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003608 } else if (SETy->isRealFloatingType()) {
3609 APFloat F(0.0);
3610 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003611 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003612 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003613 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003614 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003615 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003616
3617 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003618 SmallVector<APValue, 4> Elts(NElts, Val);
3619 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003620 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003621 case CK_BitCast: {
3622 // Evaluate the operand into an APInt we can extract from.
3623 llvm::APInt SValInt;
3624 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3625 return false;
3626 // Extract the elements
3627 QualType EltTy = VTy->getElementType();
3628 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3629 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3630 SmallVector<APValue, 4> Elts;
3631 if (EltTy->isRealFloatingType()) {
3632 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3633 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3634 unsigned FloatEltSize = EltSize;
3635 if (&Sem == &APFloat::x87DoubleExtended)
3636 FloatEltSize = 80;
3637 for (unsigned i = 0; i < NElts; i++) {
3638 llvm::APInt Elt;
3639 if (BigEndian)
3640 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3641 else
3642 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3643 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3644 }
3645 } else if (EltTy->isIntegerType()) {
3646 for (unsigned i = 0; i < NElts; i++) {
3647 llvm::APInt Elt;
3648 if (BigEndian)
3649 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3650 else
3651 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3652 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3653 }
3654 } else {
3655 return Error(E);
3656 }
3657 return Success(Elts, E);
3658 }
Eli Friedman46a52322011-03-25 00:43:55 +00003659 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003660 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003661 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003662}
3663
Richard Smith07fc6572011-10-22 21:10:00 +00003664bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003665VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003666 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003667 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003668 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003669
Nate Begeman59b5da62009-01-18 03:20:47 +00003670 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003671 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003672
Eli Friedman3edd5a92012-01-03 23:24:20 +00003673 // The number of initializers can be less than the number of
3674 // vector elements. For OpenCL, this can be due to nested vector
3675 // initialization. For GCC compatibility, missing trailing elements
3676 // should be initialized with zeroes.
3677 unsigned CountInits = 0, CountElts = 0;
3678 while (CountElts < NumElements) {
3679 // Handle nested vector initialization.
3680 if (CountInits < NumInits
3681 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3682 APValue v;
3683 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3684 return Error(E);
3685 unsigned vlen = v.getVectorLength();
3686 for (unsigned j = 0; j < vlen; j++)
3687 Elements.push_back(v.getVectorElt(j));
3688 CountElts += vlen;
3689 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003690 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003691 if (CountInits < NumInits) {
3692 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003693 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003694 } else // trailing integer zero.
3695 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3696 Elements.push_back(APValue(sInt));
3697 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003698 } else {
3699 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003700 if (CountInits < NumInits) {
3701 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003702 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003703 } else // trailing float zero.
3704 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3705 Elements.push_back(APValue(f));
3706 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003707 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003708 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003709 }
Richard Smith07fc6572011-10-22 21:10:00 +00003710 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003711}
3712
Richard Smith07fc6572011-10-22 21:10:00 +00003713bool
Richard Smith51201882011-12-30 21:15:51 +00003714VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003715 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003716 QualType EltTy = VT->getElementType();
3717 APValue ZeroElement;
3718 if (EltTy->isIntegerType())
3719 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3720 else
3721 ZeroElement =
3722 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3723
Chris Lattner5f9e2722011-07-23 10:55:15 +00003724 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003725 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003726}
3727
Richard Smith07fc6572011-10-22 21:10:00 +00003728bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003729 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003730 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003731}
3732
Nate Begeman59b5da62009-01-18 03:20:47 +00003733//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003734// Array Evaluation
3735//===----------------------------------------------------------------------===//
3736
3737namespace {
3738 class ArrayExprEvaluator
3739 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003740 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003741 APValue &Result;
3742 public:
3743
Richard Smith180f4792011-11-10 06:34:14 +00003744 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3745 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003746
3747 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003748 assert((V.isArray() || V.isLValue()) &&
3749 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003750 Result = V;
3751 return true;
3752 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003753
Richard Smith51201882011-12-30 21:15:51 +00003754 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003755 const ConstantArrayType *CAT =
3756 Info.Ctx.getAsConstantArrayType(E->getType());
3757 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003758 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003759
3760 Result = APValue(APValue::UninitArray(), 0,
3761 CAT->getSize().getZExtValue());
3762 if (!Result.hasArrayFiller()) return true;
3763
Richard Smith51201882011-12-30 21:15:51 +00003764 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003765 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003766 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003767 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003768 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003769 }
3770
Richard Smithcc5d4f62011-11-07 09:22:26 +00003771 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003772 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003773 };
3774} // end anonymous namespace
3775
Richard Smith180f4792011-11-10 06:34:14 +00003776static bool EvaluateArray(const Expr *E, const LValue &This,
3777 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003778 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003779 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003780}
3781
3782bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3783 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3784 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003785 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003786
Richard Smith974c5f92011-12-22 01:07:19 +00003787 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3788 // an appropriately-typed string literal enclosed in braces.
Richard Smithfe587202012-04-15 02:50:59 +00003789 if (E->isStringLiteralInit()) {
Richard Smith974c5f92011-12-22 01:07:19 +00003790 LValue LV;
3791 if (!EvaluateLValue(E->getInit(0), LV, Info))
3792 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003793 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003794 LV.moveInto(Val);
3795 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003796 }
3797
Richard Smith745f5142012-01-27 01:14:48 +00003798 bool Success = true;
3799
Richard Smithde31aa72012-07-07 22:48:24 +00003800 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
3801 "zero-initialized array shouldn't have any initialized elts");
3802 APValue Filler;
3803 if (Result.isArray() && Result.hasArrayFiller())
3804 Filler = Result.getArrayFiller();
3805
Richard Smithcc5d4f62011-11-07 09:22:26 +00003806 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3807 CAT->getSize().getZExtValue());
Richard Smithde31aa72012-07-07 22:48:24 +00003808
3809 // If the array was previously zero-initialized, preserve the
3810 // zero-initialized values.
3811 if (!Filler.isUninit()) {
3812 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
3813 Result.getArrayInitializedElt(I) = Filler;
3814 if (Result.hasArrayFiller())
3815 Result.getArrayFiller() = Filler;
3816 }
3817
Richard Smith180f4792011-11-10 06:34:14 +00003818 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003819 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003820 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003821 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003822 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003823 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3824 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003825 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3826 CAT->getElementType(), 1)) {
3827 if (!Info.keepEvaluatingAfterFailure())
3828 return false;
3829 Success = false;
3830 }
Richard Smith180f4792011-11-10 06:34:14 +00003831 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003832
Richard Smith745f5142012-01-27 01:14:48 +00003833 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003834 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003835 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3836 // but sometimes does:
3837 // struct S { constexpr S() : p(&p) {} void *p; };
3838 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003839 return EvaluateInPlace(Result.getArrayFiller(), Info,
3840 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003841}
3842
Richard Smithe24f5fc2011-11-17 22:56:20 +00003843bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smithde31aa72012-07-07 22:48:24 +00003844 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3845 // but sometimes does:
3846 // struct S { constexpr S() : p(&p) {} void *p; };
3847 // S s[10];
3848 LValue Subobject = This;
3849
3850 APValue *Value = &Result;
3851 bool HadZeroInit = true;
Richard Smitha4334df2012-07-10 22:12:55 +00003852 QualType ElemTy = E->getType();
3853 while (const ConstantArrayType *CAT =
3854 Info.Ctx.getAsConstantArrayType(ElemTy)) {
Richard Smithde31aa72012-07-07 22:48:24 +00003855 Subobject.addArray(Info, E, CAT);
3856 HadZeroInit &= !Value->isUninit();
3857 if (!HadZeroInit)
3858 *Value = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3859 if (!Value->hasArrayFiller())
3860 return true;
Richard Smithde31aa72012-07-07 22:48:24 +00003861 Value = &Value->getArrayFiller();
Richard Smitha4334df2012-07-10 22:12:55 +00003862 ElemTy = CAT->getElementType();
Richard Smithde31aa72012-07-07 22:48:24 +00003863 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00003864
Richard Smitha4334df2012-07-10 22:12:55 +00003865 if (!ElemTy->isRecordType())
3866 return Error(E);
3867
Richard Smithe24f5fc2011-11-17 22:56:20 +00003868 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003869
Richard Smith51201882011-12-30 21:15:51 +00003870 bool ZeroInit = E->requiresZeroInitialization();
3871 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003872 if (HadZeroInit)
3873 return true;
3874
Richard Smith51201882011-12-30 21:15:51 +00003875 if (ZeroInit) {
Richard Smitha4334df2012-07-10 22:12:55 +00003876 ImplicitValueInitExpr VIE(ElemTy);
Richard Smithde31aa72012-07-07 22:48:24 +00003877 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003878 }
3879
Richard Smith61802452011-12-22 02:22:31 +00003880 const CXXRecordDecl *RD = FD->getParent();
3881 if (RD->isUnion())
Richard Smithde31aa72012-07-07 22:48:24 +00003882 *Value = APValue((FieldDecl*)0);
Richard Smith61802452011-12-22 02:22:31 +00003883 else
Richard Smithde31aa72012-07-07 22:48:24 +00003884 *Value =
Richard Smith61802452011-12-22 02:22:31 +00003885 APValue(APValue::UninitStruct(), RD->getNumBases(),
3886 std::distance(RD->field_begin(), RD->field_end()));
3887 return true;
3888 }
3889
Richard Smithe24f5fc2011-11-17 22:56:20 +00003890 const FunctionDecl *Definition = 0;
3891 FD->getBody(Definition);
3892
Richard Smithc1c5f272011-12-13 06:39:58 +00003893 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3894 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003895
Richard Smithec789162012-01-12 18:54:33 +00003896 if (ZeroInit && !HadZeroInit) {
Richard Smitha4334df2012-07-10 22:12:55 +00003897 ImplicitValueInitExpr VIE(ElemTy);
Richard Smithde31aa72012-07-07 22:48:24 +00003898 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003899 return false;
3900 }
3901
Richard Smithe24f5fc2011-11-17 22:56:20 +00003902 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003903 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003904 cast<CXXConstructorDecl>(Definition),
Richard Smithde31aa72012-07-07 22:48:24 +00003905 Info, *Value);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003906}
3907
Richard Smithcc5d4f62011-11-07 09:22:26 +00003908//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003909// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003910//
3911// As a GNU extension, we support casting pointers to sufficiently-wide integer
3912// types and back in constant folding. Integer values are thus represented
3913// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003914//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003915
3916namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003917class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003918 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003919 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003920public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003921 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003922 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003923
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003924 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003925 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003926 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003927 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003928 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003929 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003930 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003931 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003932 return true;
3933 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003934 bool Success(const llvm::APSInt &SI, const Expr *E) {
3935 return Success(SI, E, Result);
3936 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003937
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003938 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003939 assert(E->getType()->isIntegralOrEnumerationType() &&
3940 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003941 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003942 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003943 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003944 Result.getInt().setIsUnsigned(
3945 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003946 return true;
3947 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003948 bool Success(const llvm::APInt &I, const Expr *E) {
3949 return Success(I, E, Result);
3950 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00003951
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003952 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003953 assert(E->getType()->isIntegralOrEnumerationType() &&
3954 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003955 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003956 return true;
3957 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003958 bool Success(uint64_t Value, const Expr *E) {
3959 return Success(Value, E, Result);
3960 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00003961
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003962 bool Success(CharUnits Size, const Expr *E) {
3963 return Success(Size.getQuantity(), E);
3964 }
3965
Richard Smith1aa0be82012-03-03 22:46:17 +00003966 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003967 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003968 Result = V;
3969 return true;
3970 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003971 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003972 }
Mike Stump1eb44332009-09-09 15:08:12 +00003973
Richard Smith51201882011-12-30 21:15:51 +00003974 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003975
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003976 //===--------------------------------------------------------------------===//
3977 // Visitor Methods
3978 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003979
Chris Lattner4c4867e2008-07-12 00:38:25 +00003980 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003981 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003982 }
3983 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003984 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003985 }
Eli Friedman04309752009-11-24 05:28:59 +00003986
3987 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3988 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003989 if (CheckReferencedDecl(E, E->getDecl()))
3990 return true;
3991
3992 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003993 }
3994 bool VisitMemberExpr(const MemberExpr *E) {
3995 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003996 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003997 return true;
3998 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003999
4000 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004001 }
4002
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004003 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004004 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004005 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004006 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004007
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004008 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004009 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004010
Anders Carlsson3068d112008-11-16 19:01:22 +00004011 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004012 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004013 }
Mike Stump1eb44332009-09-09 15:08:12 +00004014
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004015 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4016 return Success(E->getValue(), E);
4017 }
4018
Richard Smithf10d9172011-10-11 21:43:33 +00004019 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004020 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004021 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004022 }
4023
Sebastian Redl64b45f72009-01-05 20:52:13 +00004024 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004025 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004026 }
4027
Francois Pichet6ad6f282010-12-07 00:08:36 +00004028 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4029 return Success(E->getValue(), E);
4030 }
4031
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004032 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4033 return Success(E->getValue(), E);
4034 }
4035
John Wiegley21ff2e52011-04-28 00:16:57 +00004036 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4037 return Success(E->getValue(), E);
4038 }
4039
John Wiegley55262202011-04-25 06:54:41 +00004040 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4041 return Success(E->getValue(), E);
4042 }
4043
Eli Friedman722c7172009-02-28 03:59:05 +00004044 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004045 bool VisitUnaryImag(const UnaryOperator *E);
4046
Sebastian Redl295995c2010-09-10 20:55:47 +00004047 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004048 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004049
Chris Lattnerfcee0012008-07-11 21:24:13 +00004050private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004051 CharUnits GetAlignOfExpr(const Expr *E);
4052 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004053 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004054 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004055 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004056};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004057} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004058
Richard Smithc49bd112011-10-28 17:51:58 +00004059/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4060/// produce either the integer value or a pointer.
4061///
4062/// GCC has a heinous extension which folds casts between pointer types and
4063/// pointer-sized integral types. We support this by allowing the evaluation of
4064/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4065/// Some simple arithmetic on such values is supported (they are treated much
4066/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004067static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004068 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004069 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004070 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004071}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004072
Richard Smithf48fdb02011-12-09 22:58:01 +00004073static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004074 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004075 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004076 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004077 if (!Val.isInt()) {
4078 // FIXME: It would be better to produce the diagnostic for casting
4079 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004080 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004081 return false;
4082 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004083 Result = Val.getInt();
4084 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004085}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004086
Richard Smithf48fdb02011-12-09 22:58:01 +00004087/// Check whether the given declaration can be directly converted to an integral
4088/// rvalue. If not, no diagnostic is produced; there are other things we can
4089/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004090bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004091 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004092 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004093 // Check for signedness/width mismatches between E type and ECD value.
4094 bool SameSign = (ECD->getInitVal().isSigned()
4095 == E->getType()->isSignedIntegerOrEnumerationType());
4096 bool SameWidth = (ECD->getInitVal().getBitWidth()
4097 == Info.Ctx.getIntWidth(E->getType()));
4098 if (SameSign && SameWidth)
4099 return Success(ECD->getInitVal(), E);
4100 else {
4101 // Get rid of mismatch (otherwise Success assertions will fail)
4102 // by computing a new value matching the type of E.
4103 llvm::APSInt Val = ECD->getInitVal();
4104 if (!SameSign)
4105 Val.setIsSigned(!ECD->getInitVal().isSigned());
4106 if (!SameWidth)
4107 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4108 return Success(Val, E);
4109 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004110 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004111 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004112}
4113
Chris Lattnera4d55d82008-10-06 06:40:35 +00004114/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4115/// as GCC.
4116static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4117 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004118 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004119 enum gcc_type_class {
4120 no_type_class = -1,
4121 void_type_class, integer_type_class, char_type_class,
4122 enumeral_type_class, boolean_type_class,
4123 pointer_type_class, reference_type_class, offset_type_class,
4124 real_type_class, complex_type_class,
4125 function_type_class, method_type_class,
4126 record_type_class, union_type_class,
4127 array_type_class, string_type_class,
4128 lang_type_class
4129 };
Mike Stump1eb44332009-09-09 15:08:12 +00004130
4131 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004132 // ideal, however it is what gcc does.
4133 if (E->getNumArgs() == 0)
4134 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004135
Chris Lattnera4d55d82008-10-06 06:40:35 +00004136 QualType ArgTy = E->getArg(0)->getType();
4137 if (ArgTy->isVoidType())
4138 return void_type_class;
4139 else if (ArgTy->isEnumeralType())
4140 return enumeral_type_class;
4141 else if (ArgTy->isBooleanType())
4142 return boolean_type_class;
4143 else if (ArgTy->isCharType())
4144 return string_type_class; // gcc doesn't appear to use char_type_class
4145 else if (ArgTy->isIntegerType())
4146 return integer_type_class;
4147 else if (ArgTy->isPointerType())
4148 return pointer_type_class;
4149 else if (ArgTy->isReferenceType())
4150 return reference_type_class;
4151 else if (ArgTy->isRealType())
4152 return real_type_class;
4153 else if (ArgTy->isComplexType())
4154 return complex_type_class;
4155 else if (ArgTy->isFunctionType())
4156 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004157 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004158 return record_type_class;
4159 else if (ArgTy->isUnionType())
4160 return union_type_class;
4161 else if (ArgTy->isArrayType())
4162 return array_type_class;
4163 else if (ArgTy->isUnionType())
4164 return union_type_class;
4165 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004166 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004167}
4168
Richard Smith80d4b552011-12-28 19:48:30 +00004169/// EvaluateBuiltinConstantPForLValue - Determine the result of
4170/// __builtin_constant_p when applied to the given lvalue.
4171///
4172/// An lvalue is only "constant" if it is a pointer or reference to the first
4173/// character of a string literal.
4174template<typename LValue>
4175static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004176 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004177 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4178}
4179
4180/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4181/// GCC as we can manage.
4182static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4183 QualType ArgType = Arg->getType();
4184
4185 // __builtin_constant_p always has one operand. The rules which gcc follows
4186 // are not precisely documented, but are as follows:
4187 //
4188 // - If the operand is of integral, floating, complex or enumeration type,
4189 // and can be folded to a known value of that type, it returns 1.
4190 // - If the operand and can be folded to a pointer to the first character
4191 // of a string literal (or such a pointer cast to an integral type), it
4192 // returns 1.
4193 //
4194 // Otherwise, it returns 0.
4195 //
4196 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4197 // its support for this does not currently work.
4198 if (ArgType->isIntegralOrEnumerationType()) {
4199 Expr::EvalResult Result;
4200 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4201 return false;
4202
4203 APValue &V = Result.Val;
4204 if (V.getKind() == APValue::Int)
4205 return true;
4206
4207 return EvaluateBuiltinConstantPForLValue(V);
4208 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4209 return Arg->isEvaluatable(Ctx);
4210 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4211 LValue LV;
4212 Expr::EvalStatus Status;
4213 EvalInfo Info(Ctx, Status);
4214 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4215 : EvaluatePointer(Arg, LV, Info)) &&
4216 !Status.HasSideEffects)
4217 return EvaluateBuiltinConstantPForLValue(LV);
4218 }
4219
4220 // Anything else isn't considered to be sufficiently constant.
4221 return false;
4222}
4223
John McCall42c8f872010-05-10 23:27:23 +00004224/// Retrieves the "underlying object type" of the given expression,
4225/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004226QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4227 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4228 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004229 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004230 } else if (const Expr *E = B.get<const Expr*>()) {
4231 if (isa<CompoundLiteralExpr>(E))
4232 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004233 }
4234
4235 return QualType();
4236}
4237
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004238bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004239 LValue Base;
Richard Smithc6794852012-05-23 04:13:20 +00004240
4241 {
4242 // The operand of __builtin_object_size is never evaluated for side-effects.
4243 // If there are any, but we can determine the pointed-to object anyway, then
4244 // ignore the side-effects.
4245 SpeculativeEvaluationRAII SpeculativeEval(Info);
4246 if (!EvaluatePointer(E->getArg(0), Base, Info))
4247 return false;
4248 }
John McCall42c8f872010-05-10 23:27:23 +00004249
4250 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004251 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004252
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004253 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004254 if (T.isNull() ||
4255 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004256 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004257 T->isVariablyModifiedType() ||
4258 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004259 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004260
4261 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4262 CharUnits Offset = Base.getLValueOffset();
4263
4264 if (!Offset.isNegative() && Offset <= Size)
4265 Size -= Offset;
4266 else
4267 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004268 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004269}
4270
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004271bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith2c39d712012-04-13 00:45:38 +00004272 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004273 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004274 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004275
4276 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004277 if (TryEvaluateBuiltinObjectSize(E))
4278 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004279
Richard Smith8ae4ec22012-08-07 04:16:51 +00004280 // If evaluating the argument has side-effects, we can't determine the size
4281 // of the object, and so we lower it to unknown now. CodeGen relies on us to
4282 // handle all cases where the expression has side-effects.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004283 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004284 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004285 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004286 return Success(0, E);
4287 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004288
Richard Smithc6794852012-05-23 04:13:20 +00004289 // Expression had no side effects, but we couldn't statically determine the
4290 // size of the referenced object.
Richard Smithf48fdb02011-12-09 22:58:01 +00004291 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004292 }
4293
Benjamin Kramerd1900572012-10-06 14:42:22 +00004294 case Builtin::BI__builtin_bswap16:
Richard Smith70d38f32012-09-28 20:20:52 +00004295 case Builtin::BI__builtin_bswap32:
4296 case Builtin::BI__builtin_bswap64: {
4297 APSInt Val;
4298 if (!EvaluateInteger(E->getArg(0), Val, Info))
4299 return false;
4300
4301 return Success(Val.byteSwap(), E);
4302 }
4303
Chris Lattner019f4e82008-10-06 05:28:25 +00004304 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004305 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004306
Richard Smith80d4b552011-12-28 19:48:30 +00004307 case Builtin::BI__builtin_constant_p:
4308 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004309
Chris Lattner21fb98e2009-09-23 06:06:36 +00004310 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004311 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004312 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004313 return Success(Operand, E);
4314 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004315
4316 case Builtin::BI__builtin_expect:
4317 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004318
Douglas Gregor5726d402010-09-10 06:27:15 +00004319 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004320 // A call to strlen is not a constant expression.
Richard Smith80ad52f2013-01-02 11:42:31 +00004321 if (Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004322 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004323 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4324 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004325 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004326 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004327 case Builtin::BI__builtin_strlen:
4328 // As an extension, we support strlen() and __builtin_strlen() as constant
4329 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004330 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004331 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4332 // The string literal may have embedded null characters. Find the first
4333 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004334 StringRef Str = S->getString();
4335 StringRef::size_type Pos = Str.find(0);
4336 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004337 Str = Str.substr(0, Pos);
4338
4339 return Success(Str.size(), E);
4340 }
4341
Richard Smithf48fdb02011-12-09 22:58:01 +00004342 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004343
Richard Smith2c39d712012-04-13 00:45:38 +00004344 case Builtin::BI__atomic_always_lock_free:
Richard Smithfafbf062012-04-11 17:55:32 +00004345 case Builtin::BI__atomic_is_lock_free:
4346 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedman454b57a2011-10-17 21:44:23 +00004347 APSInt SizeVal;
4348 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4349 return false;
4350
4351 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4352 // of two less than the maximum inline atomic width, we know it is
4353 // lock-free. If the size isn't a power of two, or greater than the
4354 // maximum alignment where we promote atomics, we know it is not lock-free
4355 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4356 // the answer can only be determined at runtime; for example, 16-byte
4357 // atomics have lock-free implementations on some, but not all,
4358 // x86-64 processors.
4359
4360 // Check power-of-two.
4361 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith2c39d712012-04-13 00:45:38 +00004362 if (Size.isPowerOfTwo()) {
4363 // Check against inlining width.
4364 unsigned InlineWidthBits =
4365 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4366 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4367 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4368 Size == CharUnits::One() ||
4369 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4370 Expr::NPC_NeverValueDependent))
4371 // OK, we will inline appropriately-aligned operations of this size,
4372 // and _Atomic(T) is appropriately-aligned.
4373 return Success(1, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004374
Richard Smith2c39d712012-04-13 00:45:38 +00004375 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4376 castAs<PointerType>()->getPointeeType();
4377 if (!PointeeType->isIncompleteType() &&
4378 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4379 // OK, we will inline operations on this object.
4380 return Success(1, E);
4381 }
4382 }
4383 }
Eli Friedman454b57a2011-10-17 21:44:23 +00004384
Richard Smith2c39d712012-04-13 00:45:38 +00004385 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4386 Success(0, E) : Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004387 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004388 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004389}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004390
Richard Smith625b8072011-10-31 01:37:14 +00004391static bool HasSameBase(const LValue &A, const LValue &B) {
4392 if (!A.getLValueBase())
4393 return !B.getLValueBase();
4394 if (!B.getLValueBase())
4395 return false;
4396
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004397 if (A.getLValueBase().getOpaqueValue() !=
4398 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004399 const Decl *ADecl = GetLValueBaseDecl(A);
4400 if (!ADecl)
4401 return false;
4402 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004403 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004404 return false;
4405 }
4406
4407 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004408 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004409}
4410
Richard Smith7b48a292012-02-01 05:53:12 +00004411/// Perform the given integer operation, which is known to need at most BitWidth
4412/// bits, and check for overflow in the original type (if that type was not an
4413/// unsigned type).
4414template<typename Operation>
4415static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4416 const APSInt &LHS, const APSInt &RHS,
4417 unsigned BitWidth, Operation Op) {
4418 if (LHS.isUnsigned())
4419 return Op(LHS, RHS);
4420
4421 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4422 APSInt Result = Value.trunc(LHS.getBitWidth());
4423 if (Result.extend(BitWidth) != Value)
4424 HandleOverflow(Info, E, Value, E->getType());
4425 return Result;
4426}
4427
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004428namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00004429
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004430/// \brief Data recursive integer evaluator of certain binary operators.
4431///
4432/// We use a data recursive algorithm for binary operators so that we are able
4433/// to handle extreme cases of chained binary operators without causing stack
4434/// overflow.
4435class DataRecursiveIntBinOpEvaluator {
4436 struct EvalResult {
4437 APValue Val;
4438 bool Failed;
4439
4440 EvalResult() : Failed(false) { }
4441
4442 void swap(EvalResult &RHS) {
4443 Val.swap(RHS.Val);
4444 Failed = RHS.Failed;
4445 RHS.Failed = false;
4446 }
4447 };
4448
4449 struct Job {
4450 const Expr *E;
4451 EvalResult LHSResult; // meaningful only for binary operator expression.
4452 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4453
4454 Job() : StoredInfo(0) { }
4455 void startSpeculativeEval(EvalInfo &Info) {
4456 OldEvalStatus = Info.EvalStatus;
4457 Info.EvalStatus.Diag = 0;
4458 StoredInfo = &Info;
4459 }
4460 ~Job() {
4461 if (StoredInfo) {
4462 StoredInfo->EvalStatus = OldEvalStatus;
4463 }
4464 }
4465 private:
4466 EvalInfo *StoredInfo; // non-null if status changed.
4467 Expr::EvalStatus OldEvalStatus;
4468 };
4469
4470 SmallVector<Job, 16> Queue;
4471
4472 IntExprEvaluator &IntEval;
4473 EvalInfo &Info;
4474 APValue &FinalResult;
4475
4476public:
4477 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4478 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4479
4480 /// \brief True if \param E is a binary operator that we are going to handle
4481 /// data recursively.
4482 /// We handle binary operators that are comma, logical, or that have operands
4483 /// with integral or enumeration type.
4484 static bool shouldEnqueue(const BinaryOperator *E) {
4485 return E->getOpcode() == BO_Comma ||
4486 E->isLogicalOp() ||
4487 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4488 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00004489 }
4490
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004491 bool Traverse(const BinaryOperator *E) {
4492 enqueue(E);
4493 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00004494 while (!Queue.empty())
4495 process(PrevResult);
4496
4497 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004498
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004499 FinalResult.swap(PrevResult.Val);
4500 return true;
4501 }
4502
4503private:
4504 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4505 return IntEval.Success(Value, E, Result);
4506 }
4507 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4508 return IntEval.Success(Value, E, Result);
4509 }
4510 bool Error(const Expr *E) {
4511 return IntEval.Error(E);
4512 }
4513 bool Error(const Expr *E, diag::kind D) {
4514 return IntEval.Error(E, D);
4515 }
4516
4517 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4518 return Info.CCEDiag(E, D);
4519 }
4520
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004521 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4522 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004523 bool &SuppressRHSDiags);
4524
4525 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4526 const BinaryOperator *E, APValue &Result);
4527
4528 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4529 Result.Failed = !Evaluate(Result.Val, Info, E);
4530 if (Result.Failed)
4531 Result.Val = APValue();
4532 }
4533
Richard Trieub7783052012-03-21 23:30:30 +00004534 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004535
4536 void enqueue(const Expr *E) {
4537 E = E->IgnoreParens();
4538 Queue.resize(Queue.size()+1);
4539 Queue.back().E = E;
4540 Queue.back().Kind = Job::AnyExprKind;
4541 }
4542};
4543
4544}
4545
4546bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004547 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004548 bool &SuppressRHSDiags) {
4549 if (E->getOpcode() == BO_Comma) {
4550 // Ignore LHS but note if we could not evaluate it.
4551 if (LHSResult.Failed)
4552 Info.EvalStatus.HasSideEffects = true;
4553 return true;
4554 }
4555
4556 if (E->isLogicalOp()) {
4557 bool lhsResult;
4558 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004559 // We were able to evaluate the LHS, see if we can get away with not
4560 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004561 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004562 Success(lhsResult, E, LHSResult.Val);
4563 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004564 }
4565 } else {
4566 // Since we weren't able to evaluate the left hand side, it
4567 // must have had side effects.
4568 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004569
4570 // We can't evaluate the LHS; however, sometimes the result
4571 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4572 // Don't ignore RHS and suppress diagnostics from this arm.
4573 SuppressRHSDiags = true;
4574 }
4575
4576 return true;
4577 }
4578
4579 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4580 E->getRHS()->getType()->isIntegralOrEnumerationType());
4581
4582 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004583 return false; // Ignore RHS;
4584
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004585 return true;
4586}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004587
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004588bool DataRecursiveIntBinOpEvaluator::
4589 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4590 const BinaryOperator *E, APValue &Result) {
4591 if (E->getOpcode() == BO_Comma) {
4592 if (RHSResult.Failed)
4593 return false;
4594 Result = RHSResult.Val;
4595 return true;
4596 }
4597
4598 if (E->isLogicalOp()) {
4599 bool lhsResult, rhsResult;
4600 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4601 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4602
4603 if (LHSIsOK) {
4604 if (RHSIsOK) {
4605 if (E->getOpcode() == BO_LOr)
4606 return Success(lhsResult || rhsResult, E, Result);
4607 else
4608 return Success(lhsResult && rhsResult, E, Result);
4609 }
4610 } else {
4611 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004612 // We can't evaluate the LHS; however, sometimes the result
4613 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4614 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004615 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004616 }
4617 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004618
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004619 return false;
4620 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004621
4622 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4623 E->getRHS()->getType()->isIntegralOrEnumerationType());
4624
4625 if (LHSResult.Failed || RHSResult.Failed)
4626 return false;
4627
4628 const APValue &LHSVal = LHSResult.Val;
4629 const APValue &RHSVal = RHSResult.Val;
4630
4631 // Handle cases like (unsigned long)&a + 4.
4632 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4633 Result = LHSVal;
4634 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4635 RHSVal.getInt().getZExtValue());
4636 if (E->getOpcode() == BO_Add)
4637 Result.getLValueOffset() += AdditionalOffset;
4638 else
4639 Result.getLValueOffset() -= AdditionalOffset;
4640 return true;
4641 }
4642
4643 // Handle cases like 4 + (unsigned long)&a
4644 if (E->getOpcode() == BO_Add &&
4645 RHSVal.isLValue() && LHSVal.isInt()) {
4646 Result = RHSVal;
4647 Result.getLValueOffset() += CharUnits::fromQuantity(
4648 LHSVal.getInt().getZExtValue());
4649 return true;
4650 }
4651
4652 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4653 // Handle (intptr_t)&&A - (intptr_t)&&B.
4654 if (!LHSVal.getLValueOffset().isZero() ||
4655 !RHSVal.getLValueOffset().isZero())
4656 return false;
4657 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4658 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4659 if (!LHSExpr || !RHSExpr)
4660 return false;
4661 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4662 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4663 if (!LHSAddrExpr || !RHSAddrExpr)
4664 return false;
4665 // Make sure both labels come from the same function.
4666 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4667 RHSAddrExpr->getLabel()->getDeclContext())
4668 return false;
4669 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4670 return true;
4671 }
4672
4673 // All the following cases expect both operands to be an integer
4674 if (!LHSVal.isInt() || !RHSVal.isInt())
4675 return Error(E);
4676
4677 const APSInt &LHS = LHSVal.getInt();
4678 APSInt RHS = RHSVal.getInt();
4679
4680 switch (E->getOpcode()) {
4681 default:
4682 return Error(E);
4683 case BO_Mul:
4684 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4685 LHS.getBitWidth() * 2,
4686 std::multiplies<APSInt>()), E,
4687 Result);
4688 case BO_Add:
4689 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4690 LHS.getBitWidth() + 1,
4691 std::plus<APSInt>()), E, Result);
4692 case BO_Sub:
4693 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4694 LHS.getBitWidth() + 1,
4695 std::minus<APSInt>()), E, Result);
4696 case BO_And: return Success(LHS & RHS, E, Result);
4697 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4698 case BO_Or: return Success(LHS | RHS, E, Result);
4699 case BO_Div:
4700 case BO_Rem:
4701 if (RHS == 0)
4702 return Error(E, diag::note_expr_divide_by_zero);
4703 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4704 // not actually undefined behavior in C++11 due to a language defect.
4705 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4706 LHS.isSigned() && LHS.isMinSignedValue())
4707 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4708 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4709 Result);
4710 case BO_Shl: {
4711 // During constant-folding, a negative shift is an opposite shift. Such
4712 // a shift is not a constant expression.
4713 if (RHS.isSigned() && RHS.isNegative()) {
4714 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4715 RHS = -RHS;
4716 goto shift_right;
4717 }
4718
4719 shift_left:
4720 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4721 // the shifted type.
4722 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4723 if (SA != RHS) {
4724 CCEDiag(E, diag::note_constexpr_large_shift)
4725 << RHS << E->getType() << LHS.getBitWidth();
4726 } else if (LHS.isSigned()) {
4727 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4728 // operand, and must not overflow the corresponding unsigned type.
4729 if (LHS.isNegative())
4730 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4731 else if (LHS.countLeadingZeros() < SA)
4732 CCEDiag(E, diag::note_constexpr_lshift_discards);
4733 }
4734
4735 return Success(LHS << SA, E, Result);
4736 }
4737 case BO_Shr: {
4738 // During constant-folding, a negative shift is an opposite shift. Such a
4739 // shift is not a constant expression.
4740 if (RHS.isSigned() && RHS.isNegative()) {
4741 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4742 RHS = -RHS;
4743 goto shift_left;
4744 }
4745
4746 shift_right:
4747 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4748 // shifted type.
4749 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4750 if (SA != RHS)
4751 CCEDiag(E, diag::note_constexpr_large_shift)
4752 << RHS << E->getType() << LHS.getBitWidth();
4753
4754 return Success(LHS >> SA, E, Result);
4755 }
4756
4757 case BO_LT: return Success(LHS < RHS, E, Result);
4758 case BO_GT: return Success(LHS > RHS, E, Result);
4759 case BO_LE: return Success(LHS <= RHS, E, Result);
4760 case BO_GE: return Success(LHS >= RHS, E, Result);
4761 case BO_EQ: return Success(LHS == RHS, E, Result);
4762 case BO_NE: return Success(LHS != RHS, E, Result);
4763 }
4764}
4765
Richard Trieub7783052012-03-21 23:30:30 +00004766void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004767 Job &job = Queue.back();
4768
4769 switch (job.Kind) {
4770 case Job::AnyExprKind: {
4771 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4772 if (shouldEnqueue(Bop)) {
4773 job.Kind = Job::BinOpKind;
4774 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00004775 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004776 }
4777 }
4778
4779 EvaluateExpr(job.E, Result);
4780 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004781 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004782 }
4783
4784 case Job::BinOpKind: {
4785 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004786 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004787 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004788 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004789 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004790 }
4791 if (SuppressRHSDiags)
4792 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004793 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004794 job.Kind = Job::BinOpVisitedLHSKind;
4795 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00004796 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004797 }
4798
4799 case Job::BinOpVisitedLHSKind: {
4800 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4801 EvalResult RHS;
4802 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00004803 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004804 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004805 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004806 }
4807 }
4808
4809 llvm_unreachable("Invalid Job::Kind!");
4810}
4811
4812bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4813 if (E->isAssignmentOp())
4814 return Error(E);
4815
4816 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4817 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004818
Anders Carlsson286f85e2008-11-16 07:17:21 +00004819 QualType LHSTy = E->getLHS()->getType();
4820 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004821
4822 if (LHSTy->isAnyComplexType()) {
4823 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004824 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004825
Richard Smith745f5142012-01-27 01:14:48 +00004826 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4827 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004828 return false;
4829
Richard Smith745f5142012-01-27 01:14:48 +00004830 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004831 return false;
4832
4833 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004834 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004835 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004836 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004837 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4838
John McCall2de56d12010-08-25 11:45:40 +00004839 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004840 return Success((CR_r == APFloat::cmpEqual &&
4841 CR_i == APFloat::cmpEqual), E);
4842 else {
John McCall2de56d12010-08-25 11:45:40 +00004843 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004844 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004845 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004846 CR_r == APFloat::cmpLessThan ||
4847 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004848 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004849 CR_i == APFloat::cmpLessThan ||
4850 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004851 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004852 } else {
John McCall2de56d12010-08-25 11:45:40 +00004853 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004854 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4855 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4856 else {
John McCall2de56d12010-08-25 11:45:40 +00004857 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004858 "Invalid compex comparison.");
4859 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4860 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4861 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004862 }
4863 }
Mike Stump1eb44332009-09-09 15:08:12 +00004864
Anders Carlsson286f85e2008-11-16 07:17:21 +00004865 if (LHSTy->isRealFloatingType() &&
4866 RHSTy->isRealFloatingType()) {
4867 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004868
Richard Smith745f5142012-01-27 01:14:48 +00004869 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4870 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004871 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004872
Richard Smith745f5142012-01-27 01:14:48 +00004873 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004874 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004875
Anders Carlsson286f85e2008-11-16 07:17:21 +00004876 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004877
Anders Carlsson286f85e2008-11-16 07:17:21 +00004878 switch (E->getOpcode()) {
4879 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004880 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004881 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004882 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004883 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004884 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004885 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004886 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004887 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004888 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004889 E);
John McCall2de56d12010-08-25 11:45:40 +00004890 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004891 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004892 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004893 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004894 || CR == APFloat::cmpLessThan
4895 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004896 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004897 }
Mike Stump1eb44332009-09-09 15:08:12 +00004898
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004899 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004900 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004901 LValue LHSValue, RHSValue;
4902
4903 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4904 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004905 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004906
Richard Smith745f5142012-01-27 01:14:48 +00004907 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004908 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004909
Richard Smith625b8072011-10-31 01:37:14 +00004910 // Reject differing bases from the normal codepath; we special-case
4911 // comparisons to null.
4912 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004913 if (E->getOpcode() == BO_Sub) {
4914 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004915 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4916 return false;
4917 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramer7b2f93c2012-10-03 14:15:39 +00004918 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedman65639282012-01-04 23:13:47 +00004919 if (!LHSExpr || !RHSExpr)
4920 return false;
4921 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4922 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4923 if (!LHSAddrExpr || !RHSAddrExpr)
4924 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004925 // Make sure both labels come from the same function.
4926 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4927 RHSAddrExpr->getLabel()->getDeclContext())
4928 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004929 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004930 return true;
4931 }
Richard Smith9e36b532011-10-31 05:11:32 +00004932 // Inequalities and subtractions between unrelated pointers have
4933 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004934 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004935 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004936 // A constant address may compare equal to the address of a symbol.
4937 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004938 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004939 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4940 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004941 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004942 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004943 // distinct addresses. In clang, the result of such a comparison is
4944 // unspecified, so it is not a constant expression. However, we do know
4945 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004946 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4947 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004948 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004949 // We can't tell whether weak symbols will end up pointing to the same
4950 // object.
4951 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004952 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004953 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004954 // (Note that clang defaults to -fmerge-all-constants, which can
4955 // lead to inconsistent results for comparisons involving the address
4956 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004957 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004958 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004959
Richard Smith15efc4d2012-02-01 08:10:20 +00004960 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4961 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4962
Richard Smithf15fda02012-02-02 01:16:57 +00004963 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4964 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4965
John McCall2de56d12010-08-25 11:45:40 +00004966 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004967 // C++11 [expr.add]p6:
4968 // Unless both pointers point to elements of the same array object, or
4969 // one past the last element of the array object, the behavior is
4970 // undefined.
4971 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4972 !AreElementsOfSameArray(getType(LHSValue.Base),
4973 LHSDesignator, RHSDesignator))
4974 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4975
Chris Lattner4992bdd2010-04-20 17:13:14 +00004976 QualType Type = E->getLHS()->getType();
4977 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004978
Richard Smith180f4792011-11-10 06:34:14 +00004979 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004980 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004981 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004982
Richard Smith15efc4d2012-02-01 08:10:20 +00004983 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4984 // and produce incorrect results when it overflows. Such behavior
4985 // appears to be non-conforming, but is common, so perhaps we should
4986 // assume the standard intended for such cases to be undefined behavior
4987 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004988
Richard Smith15efc4d2012-02-01 08:10:20 +00004989 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4990 // overflow in the final conversion to ptrdiff_t.
4991 APSInt LHS(
4992 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4993 APSInt RHS(
4994 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4995 APSInt ElemSize(
4996 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4997 APSInt TrueResult = (LHS - RHS) / ElemSize;
4998 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4999
5000 if (Result.extend(65) != TrueResult)
5001 HandleOverflow(Info, E, TrueResult, E->getType());
5002 return Success(Result, E);
5003 }
Richard Smith82f28582012-01-31 06:41:30 +00005004
5005 // C++11 [expr.rel]p3:
5006 // Pointers to void (after pointer conversions) can be compared, with a
5007 // result defined as follows: If both pointers represent the same
5008 // address or are both the null pointer value, the result is true if the
5009 // operator is <= or >= and false otherwise; otherwise the result is
5010 // unspecified.
5011 // We interpret this as applying to pointers to *cv* void.
5012 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00005013 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00005014 CCEDiag(E, diag::note_constexpr_void_comparison);
5015
Richard Smithf15fda02012-02-02 01:16:57 +00005016 // C++11 [expr.rel]p2:
5017 // - If two pointers point to non-static data members of the same object,
5018 // or to subobjects or array elements fo such members, recursively, the
5019 // pointer to the later declared member compares greater provided the
5020 // two members have the same access control and provided their class is
5021 // not a union.
5022 // [...]
5023 // - Otherwise pointer comparisons are unspecified.
5024 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5025 E->isRelationalOp()) {
5026 bool WasArrayIndex;
5027 unsigned Mismatch =
5028 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5029 RHSDesignator, WasArrayIndex);
5030 // At the point where the designators diverge, the comparison has a
5031 // specified value if:
5032 // - we are comparing array indices
5033 // - we are comparing fields of a union, or fields with the same access
5034 // Otherwise, the result is unspecified and thus the comparison is not a
5035 // constant expression.
5036 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5037 Mismatch < RHSDesignator.Entries.size()) {
5038 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5039 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5040 if (!LF && !RF)
5041 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5042 else if (!LF)
5043 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5044 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5045 << RF->getParent() << RF;
5046 else if (!RF)
5047 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5048 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5049 << LF->getParent() << LF;
5050 else if (!LF->getParent()->isUnion() &&
5051 LF->getAccess() != RF->getAccess())
5052 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5053 << LF << LF->getAccess() << RF << RF->getAccess()
5054 << LF->getParent();
5055 }
5056 }
5057
Eli Friedmana3169882012-04-16 04:30:08 +00005058 // The comparison here must be unsigned, and performed with the same
5059 // width as the pointer.
Eli Friedmana3169882012-04-16 04:30:08 +00005060 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5061 uint64_t CompareLHS = LHSOffset.getQuantity();
5062 uint64_t CompareRHS = RHSOffset.getQuantity();
5063 assert(PtrSize <= 64 && "Unexpected pointer width");
5064 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5065 CompareLHS &= Mask;
5066 CompareRHS &= Mask;
5067
Eli Friedman28503762012-04-16 19:23:57 +00005068 // If there is a base and this is a relational operator, we can only
5069 // compare pointers within the object in question; otherwise, the result
5070 // depends on where the object is located in memory.
5071 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5072 QualType BaseTy = getType(LHSValue.Base);
5073 if (BaseTy->isIncompleteType())
5074 return Error(E);
5075 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5076 uint64_t OffsetLimit = Size.getQuantity();
5077 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5078 return Error(E);
5079 }
5080
Richard Smith625b8072011-10-31 01:37:14 +00005081 switch (E->getOpcode()) {
5082 default: llvm_unreachable("missing comparison operator");
Eli Friedmana3169882012-04-16 04:30:08 +00005083 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5084 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5085 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5086 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5087 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5088 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00005089 }
Anders Carlsson3068d112008-11-16 19:01:22 +00005090 }
5091 }
Richard Smithb02e4622012-02-01 01:42:44 +00005092
5093 if (LHSTy->isMemberPointerType()) {
5094 assert(E->isEqualityOp() && "unexpected member pointer operation");
5095 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5096
5097 MemberPtr LHSValue, RHSValue;
5098
5099 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5100 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5101 return false;
5102
5103 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5104 return false;
5105
5106 // C++11 [expr.eq]p2:
5107 // If both operands are null, they compare equal. Otherwise if only one is
5108 // null, they compare unequal.
5109 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5110 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5111 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5112 }
5113
5114 // Otherwise if either is a pointer to a virtual member function, the
5115 // result is unspecified.
5116 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5117 if (MD->isVirtual())
5118 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5119 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5120 if (MD->isVirtual())
5121 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5122
5123 // Otherwise they compare equal if and only if they would refer to the
5124 // same member of the same most derived object or the same subobject if
5125 // they were dereferenced with a hypothetical object of the associated
5126 // class type.
5127 bool Equal = LHSValue == RHSValue;
5128 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5129 }
5130
Richard Smith26f2cac2012-02-14 22:35:28 +00005131 if (LHSTy->isNullPtrType()) {
5132 assert(E->isComparisonOp() && "unexpected nullptr operation");
5133 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5134 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5135 // are compared, the result is true of the operator is <=, >= or ==, and
5136 // false otherwise.
5137 BinaryOperator::Opcode Opcode = E->getOpcode();
5138 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5139 }
5140
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005141 assert((!LHSTy->isIntegralOrEnumerationType() ||
5142 !RHSTy->isIntegralOrEnumerationType()) &&
5143 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5144 // We can't continue from here for non-integral types.
5145 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005146}
5147
Ken Dyck8b752f12010-01-27 17:10:57 +00005148CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005149 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5150 // result shall be the alignment of the referenced type."
5151 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5152 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005153
5154 // __alignof is defined to return the preferred alignment.
5155 return Info.Ctx.toCharUnitsFromBits(
5156 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005157}
5158
Ken Dyck8b752f12010-01-27 17:10:57 +00005159CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005160 E = E->IgnoreParens();
5161
5162 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005163 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005164 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005165 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5166 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005167
Chris Lattneraf707ab2009-01-24 21:53:27 +00005168 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005169 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5170 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005171
Chris Lattnere9feb472009-01-24 21:09:06 +00005172 return GetAlignOfType(E->getType());
5173}
5174
5175
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005176/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5177/// a result as the expression's type.
5178bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5179 const UnaryExprOrTypeTraitExpr *E) {
5180 switch(E->getKind()) {
5181 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005182 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005183 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005184 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005185 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005186 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005187
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005188 case UETT_VecStep: {
5189 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005190
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005191 if (Ty->isVectorType()) {
Ted Kremenek890f0f12012-08-23 20:46:57 +00005192 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005193
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005194 // The vec_step built-in functions that take a 3-component
5195 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5196 if (n == 3)
5197 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005198
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005199 return Success(n, E);
5200 } else
5201 return Success(1, E);
5202 }
5203
5204 case UETT_SizeOf: {
5205 QualType SrcTy = E->getTypeOfArgument();
5206 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5207 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005208 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5209 SrcTy = Ref->getPointeeType();
5210
Richard Smith180f4792011-11-10 06:34:14 +00005211 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005212 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005213 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005214 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005215 }
5216 }
5217
5218 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005219}
5220
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005221bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005222 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005223 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005224 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005225 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005226 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005227 for (unsigned i = 0; i != n; ++i) {
5228 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5229 switch (ON.getKind()) {
5230 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005231 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005232 APSInt IdxResult;
5233 if (!EvaluateInteger(Idx, IdxResult, Info))
5234 return false;
5235 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5236 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005237 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005238 CurrentType = AT->getElementType();
5239 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5240 Result += IdxResult.getSExtValue() * ElementSize;
5241 break;
5242 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005243
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005244 case OffsetOfExpr::OffsetOfNode::Field: {
5245 FieldDecl *MemberDecl = ON.getField();
5246 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005247 if (!RT)
5248 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005249 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005250 if (RD->isInvalidDecl()) return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005251 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005252 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005253 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005254 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005255 CurrentType = MemberDecl->getType().getNonReferenceType();
5256 break;
5257 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005258
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005259 case OffsetOfExpr::OffsetOfNode::Identifier:
5260 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005261
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005262 case OffsetOfExpr::OffsetOfNode::Base: {
5263 CXXBaseSpecifier *BaseSpec = ON.getBase();
5264 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005265 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005266
5267 // Find the layout of the class whose base we are looking into.
5268 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005269 if (!RT)
5270 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005271 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005272 if (RD->isInvalidDecl()) return false;
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005273 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5274
5275 // Find the base class itself.
5276 CurrentType = BaseSpec->getType();
5277 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5278 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005279 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005280
5281 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005282 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005283 break;
5284 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005285 }
5286 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005287 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005288}
5289
Chris Lattnerb542afe2008-07-11 19:10:17 +00005290bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005291 switch (E->getOpcode()) {
5292 default:
5293 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5294 // See C99 6.6p3.
5295 return Error(E);
5296 case UO_Extension:
5297 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5298 // If so, we could clear the diagnostic ID.
5299 return Visit(E->getSubExpr());
5300 case UO_Plus:
5301 // The result is just the value.
5302 return Visit(E->getSubExpr());
5303 case UO_Minus: {
5304 if (!Visit(E->getSubExpr()))
5305 return false;
5306 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005307 const APSInt &Value = Result.getInt();
5308 if (Value.isSigned() && Value.isMinSignedValue())
5309 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5310 E->getType());
5311 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005312 }
5313 case UO_Not: {
5314 if (!Visit(E->getSubExpr()))
5315 return false;
5316 if (!Result.isInt()) return Error(E);
5317 return Success(~Result.getInt(), E);
5318 }
5319 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005320 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005321 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005322 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005323 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005324 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005325 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005326}
Mike Stump1eb44332009-09-09 15:08:12 +00005327
Chris Lattner732b2232008-07-12 01:15:53 +00005328/// HandleCast - This is used to evaluate implicit or explicit casts where the
5329/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005330bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5331 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005332 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005333 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005334
Eli Friedman46a52322011-03-25 00:43:55 +00005335 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005336 case CK_BaseToDerived:
5337 case CK_DerivedToBase:
5338 case CK_UncheckedDerivedToBase:
5339 case CK_Dynamic:
5340 case CK_ToUnion:
5341 case CK_ArrayToPointerDecay:
5342 case CK_FunctionToPointerDecay:
5343 case CK_NullToPointer:
5344 case CK_NullToMemberPointer:
5345 case CK_BaseToDerivedMemberPointer:
5346 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005347 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005348 case CK_ConstructorConversion:
5349 case CK_IntegralToPointer:
5350 case CK_ToVoid:
5351 case CK_VectorSplat:
5352 case CK_IntegralToFloating:
5353 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005354 case CK_CPointerToObjCPointerCast:
5355 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005356 case CK_AnyPointerToBlockPointerCast:
5357 case CK_ObjCObjectLValueCast:
5358 case CK_FloatingRealToComplex:
5359 case CK_FloatingComplexToReal:
5360 case CK_FloatingComplexCast:
5361 case CK_FloatingComplexToIntegralComplex:
5362 case CK_IntegralRealToComplex:
5363 case CK_IntegralComplexCast:
5364 case CK_IntegralComplexToFloatingComplex:
Eli Friedmana6c66ce2012-08-31 00:14:07 +00005365 case CK_BuiltinFnToFnPtr:
Eli Friedman46a52322011-03-25 00:43:55 +00005366 llvm_unreachable("invalid cast kind for integral value");
5367
Eli Friedmane50c2972011-03-25 19:07:11 +00005368 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005369 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005370 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005371 case CK_ARCProduceObject:
5372 case CK_ARCConsumeObject:
5373 case CK_ARCReclaimReturnedObject:
5374 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005375 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005376 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005377
Richard Smith7d580a42012-01-17 21:17:26 +00005378 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005379 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005380 case CK_AtomicToNonAtomic:
5381 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005382 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005383 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005384
5385 case CK_MemberPointerToBoolean:
5386 case CK_PointerToBoolean:
5387 case CK_IntegralToBoolean:
5388 case CK_FloatingToBoolean:
5389 case CK_FloatingComplexToBoolean:
5390 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005391 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005392 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005393 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005394 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005395 }
5396
Eli Friedman46a52322011-03-25 00:43:55 +00005397 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005398 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005399 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005400
Eli Friedmanbe265702009-02-20 01:15:07 +00005401 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005402 // Allow casts of address-of-label differences if they are no-ops
5403 // or narrowing. (The narrowing case isn't actually guaranteed to
5404 // be constant-evaluatable except in some narrow cases which are hard
5405 // to detect here. We let it through on the assumption the user knows
5406 // what they are doing.)
5407 if (Result.isAddrLabelDiff())
5408 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005409 // Only allow casts of lvalues if they are lossless.
5410 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5411 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005412
Richard Smithf72fccf2012-01-30 22:27:01 +00005413 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5414 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005415 }
Mike Stump1eb44332009-09-09 15:08:12 +00005416
Eli Friedman46a52322011-03-25 00:43:55 +00005417 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005418 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5419
John McCallefdb83e2010-05-07 21:00:08 +00005420 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005421 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005422 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005423
Daniel Dunbardd211642009-02-19 22:24:01 +00005424 if (LV.getLValueBase()) {
5425 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005426 // FIXME: Allow a larger integer size than the pointer size, and allow
5427 // narrowing back down to pointer width in subsequent integral casts.
5428 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005429 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005430 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005431
Richard Smithb755a9d2011-11-16 07:18:12 +00005432 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005433 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005434 return true;
5435 }
5436
Ken Dycka7305832010-01-15 12:37:54 +00005437 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5438 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005439 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005440 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005441
Eli Friedman46a52322011-03-25 00:43:55 +00005442 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005443 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005444 if (!EvaluateComplex(SubExpr, C, Info))
5445 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005446 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005447 }
Eli Friedman2217c872009-02-22 11:46:18 +00005448
Eli Friedman46a52322011-03-25 00:43:55 +00005449 case CK_FloatingToIntegral: {
5450 APFloat F(0.0);
5451 if (!EvaluateFloat(SubExpr, F, Info))
5452 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005453
Richard Smithc1c5f272011-12-13 06:39:58 +00005454 APSInt Value;
5455 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5456 return false;
5457 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005458 }
5459 }
Mike Stump1eb44332009-09-09 15:08:12 +00005460
Eli Friedman46a52322011-03-25 00:43:55 +00005461 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005462}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005463
Eli Friedman722c7172009-02-28 03:59:05 +00005464bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5465 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005466 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005467 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5468 return false;
5469 if (!LV.isComplexInt())
5470 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005471 return Success(LV.getComplexIntReal(), E);
5472 }
5473
5474 return Visit(E->getSubExpr());
5475}
5476
Eli Friedman664a1042009-02-27 04:45:43 +00005477bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005478 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005479 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005480 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5481 return false;
5482 if (!LV.isComplexInt())
5483 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005484 return Success(LV.getComplexIntImag(), E);
5485 }
5486
Richard Smith8327fad2011-10-24 18:44:57 +00005487 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005488 return Success(0, E);
5489}
5490
Douglas Gregoree8aff02011-01-04 17:33:58 +00005491bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5492 return Success(E->getPackLength(), E);
5493}
5494
Sebastian Redl295995c2010-09-10 20:55:47 +00005495bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5496 return Success(E->getValue(), E);
5497}
5498
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005499//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005500// Float Evaluation
5501//===----------------------------------------------------------------------===//
5502
5503namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005504class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005505 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005506 APFloat &Result;
5507public:
5508 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005509 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005510
Richard Smith1aa0be82012-03-03 22:46:17 +00005511 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005512 Result = V.getFloat();
5513 return true;
5514 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005515
Richard Smith51201882011-12-30 21:15:51 +00005516 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005517 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5518 return true;
5519 }
5520
Chris Lattner019f4e82008-10-06 05:28:25 +00005521 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005522
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005523 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005524 bool VisitBinaryOperator(const BinaryOperator *E);
5525 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005526 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005527
John McCallabd3a852010-05-07 22:08:54 +00005528 bool VisitUnaryReal(const UnaryOperator *E);
5529 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005530
Richard Smith51201882011-12-30 21:15:51 +00005531 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005532};
5533} // end anonymous namespace
5534
5535static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005536 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005537 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005538}
5539
Jay Foad4ba2a172011-01-12 09:06:06 +00005540static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005541 QualType ResultTy,
5542 const Expr *Arg,
5543 bool SNaN,
5544 llvm::APFloat &Result) {
5545 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5546 if (!S) return false;
5547
5548 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5549
5550 llvm::APInt fill;
5551
5552 // Treat empty strings as if they were zero.
5553 if (S->getString().empty())
5554 fill = llvm::APInt(32, 0);
5555 else if (S->getString().getAsInteger(0, fill))
5556 return false;
5557
5558 if (SNaN)
5559 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5560 else
5561 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5562 return true;
5563}
5564
Chris Lattner019f4e82008-10-06 05:28:25 +00005565bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005566 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005567 default:
5568 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5569
Chris Lattner019f4e82008-10-06 05:28:25 +00005570 case Builtin::BI__builtin_huge_val:
5571 case Builtin::BI__builtin_huge_valf:
5572 case Builtin::BI__builtin_huge_vall:
5573 case Builtin::BI__builtin_inf:
5574 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005575 case Builtin::BI__builtin_infl: {
5576 const llvm::fltSemantics &Sem =
5577 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005578 Result = llvm::APFloat::getInf(Sem);
5579 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005580 }
Mike Stump1eb44332009-09-09 15:08:12 +00005581
John McCalldb7b72a2010-02-28 13:00:19 +00005582 case Builtin::BI__builtin_nans:
5583 case Builtin::BI__builtin_nansf:
5584 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005585 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5586 true, Result))
5587 return Error(E);
5588 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005589
Chris Lattner9e621712008-10-06 06:31:58 +00005590 case Builtin::BI__builtin_nan:
5591 case Builtin::BI__builtin_nanf:
5592 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005593 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005594 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005595 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5596 false, Result))
5597 return Error(E);
5598 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005599
5600 case Builtin::BI__builtin_fabs:
5601 case Builtin::BI__builtin_fabsf:
5602 case Builtin::BI__builtin_fabsl:
5603 if (!EvaluateFloat(E->getArg(0), Result, Info))
5604 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005605
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005606 if (Result.isNegative())
5607 Result.changeSign();
5608 return true;
5609
Mike Stump1eb44332009-09-09 15:08:12 +00005610 case Builtin::BI__builtin_copysign:
5611 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005612 case Builtin::BI__builtin_copysignl: {
5613 APFloat RHS(0.);
5614 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5615 !EvaluateFloat(E->getArg(1), RHS, Info))
5616 return false;
5617 Result.copySign(RHS);
5618 return true;
5619 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005620 }
5621}
5622
John McCallabd3a852010-05-07 22:08:54 +00005623bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005624 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5625 ComplexValue CV;
5626 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5627 return false;
5628 Result = CV.FloatReal;
5629 return true;
5630 }
5631
5632 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005633}
5634
5635bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005636 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5637 ComplexValue CV;
5638 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5639 return false;
5640 Result = CV.FloatImag;
5641 return true;
5642 }
5643
Richard Smith8327fad2011-10-24 18:44:57 +00005644 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005645 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5646 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005647 return true;
5648}
5649
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005650bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005651 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005652 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005653 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005654 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005655 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005656 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5657 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005658 Result.changeSign();
5659 return true;
5660 }
5661}
Chris Lattner019f4e82008-10-06 05:28:25 +00005662
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005663bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005664 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5665 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005666
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005667 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005668 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5669 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005670 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005671 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005672 return false;
5673
5674 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005675 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005676 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005677 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005678 break;
John McCall2de56d12010-08-25 11:45:40 +00005679 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005680 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005681 break;
John McCall2de56d12010-08-25 11:45:40 +00005682 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005683 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005684 break;
John McCall2de56d12010-08-25 11:45:40 +00005685 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005686 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005687 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005688 }
Richard Smith7b48a292012-02-01 05:53:12 +00005689
5690 if (Result.isInfinity() || Result.isNaN())
5691 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5692 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005693}
5694
5695bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5696 Result = E->getValue();
5697 return true;
5698}
5699
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005700bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5701 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005702
Eli Friedman2a523ee2011-03-25 00:54:52 +00005703 switch (E->getCastKind()) {
5704 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005705 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005706
5707 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005708 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005709 return EvaluateInteger(SubExpr, IntResult, Info) &&
5710 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5711 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005712 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005713
5714 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005715 if (!Visit(SubExpr))
5716 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005717 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5718 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005719 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005720
Eli Friedman2a523ee2011-03-25 00:54:52 +00005721 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005722 ComplexValue V;
5723 if (!EvaluateComplex(SubExpr, V, Info))
5724 return false;
5725 Result = V.getComplexFloatReal();
5726 return true;
5727 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005728 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005729}
5730
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005731//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005732// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005733//===----------------------------------------------------------------------===//
5734
5735namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005736class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005737 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005738 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005739
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005740public:
John McCallf4cf1a12010-05-07 17:22:02 +00005741 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005742 : ExprEvaluatorBaseTy(info), Result(Result) {}
5743
Richard Smith1aa0be82012-03-03 22:46:17 +00005744 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005745 Result.setFrom(V);
5746 return true;
5747 }
Mike Stump1eb44332009-09-09 15:08:12 +00005748
Eli Friedman7ead5c72012-01-10 04:58:17 +00005749 bool ZeroInitialization(const Expr *E);
5750
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005751 //===--------------------------------------------------------------------===//
5752 // Visitor Methods
5753 //===--------------------------------------------------------------------===//
5754
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005755 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005756 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005757 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005758 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005759 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005760};
5761} // end anonymous namespace
5762
John McCallf4cf1a12010-05-07 17:22:02 +00005763static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5764 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005765 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005766 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005767}
5768
Eli Friedman7ead5c72012-01-10 04:58:17 +00005769bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek890f0f12012-08-23 20:46:57 +00005770 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005771 if (ElemTy->isRealFloatingType()) {
5772 Result.makeComplexFloat();
5773 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5774 Result.FloatReal = Zero;
5775 Result.FloatImag = Zero;
5776 } else {
5777 Result.makeComplexInt();
5778 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5779 Result.IntReal = Zero;
5780 Result.IntImag = Zero;
5781 }
5782 return true;
5783}
5784
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005785bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5786 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005787
5788 if (SubExpr->getType()->isRealFloatingType()) {
5789 Result.makeComplexFloat();
5790 APFloat &Imag = Result.FloatImag;
5791 if (!EvaluateFloat(SubExpr, Imag, Info))
5792 return false;
5793
5794 Result.FloatReal = APFloat(Imag.getSemantics());
5795 return true;
5796 } else {
5797 assert(SubExpr->getType()->isIntegerType() &&
5798 "Unexpected imaginary literal.");
5799
5800 Result.makeComplexInt();
5801 APSInt &Imag = Result.IntImag;
5802 if (!EvaluateInteger(SubExpr, Imag, Info))
5803 return false;
5804
5805 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5806 return true;
5807 }
5808}
5809
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005810bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005811
John McCall8786da72010-12-14 17:51:41 +00005812 switch (E->getCastKind()) {
5813 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005814 case CK_BaseToDerived:
5815 case CK_DerivedToBase:
5816 case CK_UncheckedDerivedToBase:
5817 case CK_Dynamic:
5818 case CK_ToUnion:
5819 case CK_ArrayToPointerDecay:
5820 case CK_FunctionToPointerDecay:
5821 case CK_NullToPointer:
5822 case CK_NullToMemberPointer:
5823 case CK_BaseToDerivedMemberPointer:
5824 case CK_DerivedToBaseMemberPointer:
5825 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005826 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005827 case CK_ConstructorConversion:
5828 case CK_IntegralToPointer:
5829 case CK_PointerToIntegral:
5830 case CK_PointerToBoolean:
5831 case CK_ToVoid:
5832 case CK_VectorSplat:
5833 case CK_IntegralCast:
5834 case CK_IntegralToBoolean:
5835 case CK_IntegralToFloating:
5836 case CK_FloatingToIntegral:
5837 case CK_FloatingToBoolean:
5838 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005839 case CK_CPointerToObjCPointerCast:
5840 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005841 case CK_AnyPointerToBlockPointerCast:
5842 case CK_ObjCObjectLValueCast:
5843 case CK_FloatingComplexToReal:
5844 case CK_FloatingComplexToBoolean:
5845 case CK_IntegralComplexToReal:
5846 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005847 case CK_ARCProduceObject:
5848 case CK_ARCConsumeObject:
5849 case CK_ARCReclaimReturnedObject:
5850 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005851 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmana6c66ce2012-08-31 00:14:07 +00005852 case CK_BuiltinFnToFnPtr:
John McCall8786da72010-12-14 17:51:41 +00005853 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005854
John McCall8786da72010-12-14 17:51:41 +00005855 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005856 case CK_AtomicToNonAtomic:
5857 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005858 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005859 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005860
5861 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005862 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005863 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005864 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005865
5866 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005867 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005868 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005869 return false;
5870
John McCall8786da72010-12-14 17:51:41 +00005871 Result.makeComplexFloat();
5872 Result.FloatImag = APFloat(Real.getSemantics());
5873 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005874 }
5875
John McCall8786da72010-12-14 17:51:41 +00005876 case CK_FloatingComplexCast: {
5877 if (!Visit(E->getSubExpr()))
5878 return false;
5879
5880 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5881 QualType From
5882 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5883
Richard Smithc1c5f272011-12-13 06:39:58 +00005884 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5885 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005886 }
5887
5888 case CK_FloatingComplexToIntegralComplex: {
5889 if (!Visit(E->getSubExpr()))
5890 return false;
5891
5892 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5893 QualType From
5894 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5895 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005896 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5897 To, Result.IntReal) &&
5898 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5899 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005900 }
5901
5902 case CK_IntegralRealToComplex: {
5903 APSInt &Real = Result.IntReal;
5904 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5905 return false;
5906
5907 Result.makeComplexInt();
5908 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5909 return true;
5910 }
5911
5912 case CK_IntegralComplexCast: {
5913 if (!Visit(E->getSubExpr()))
5914 return false;
5915
5916 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5917 QualType From
5918 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5919
Richard Smithf72fccf2012-01-30 22:27:01 +00005920 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5921 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005922 return true;
5923 }
5924
5925 case CK_IntegralComplexToFloatingComplex: {
5926 if (!Visit(E->getSubExpr()))
5927 return false;
5928
Ted Kremenek890f0f12012-08-23 20:46:57 +00005929 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005930 QualType From
Ted Kremenek890f0f12012-08-23 20:46:57 +00005931 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005932 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005933 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5934 To, Result.FloatReal) &&
5935 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5936 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005937 }
5938 }
5939
5940 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005941}
5942
John McCallf4cf1a12010-05-07 17:22:02 +00005943bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005944 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005945 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5946
Richard Smith745f5142012-01-27 01:14:48 +00005947 bool LHSOK = Visit(E->getLHS());
5948 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005949 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005950
John McCallf4cf1a12010-05-07 17:22:02 +00005951 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005952 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005953 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005954
Daniel Dunbar3f279872009-01-29 01:32:56 +00005955 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5956 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005957 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005958 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005959 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005960 if (Result.isComplexFloat()) {
5961 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5962 APFloat::rmNearestTiesToEven);
5963 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5964 APFloat::rmNearestTiesToEven);
5965 } else {
5966 Result.getComplexIntReal() += RHS.getComplexIntReal();
5967 Result.getComplexIntImag() += RHS.getComplexIntImag();
5968 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005969 break;
John McCall2de56d12010-08-25 11:45:40 +00005970 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005971 if (Result.isComplexFloat()) {
5972 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5973 APFloat::rmNearestTiesToEven);
5974 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5975 APFloat::rmNearestTiesToEven);
5976 } else {
5977 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5978 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5979 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005980 break;
John McCall2de56d12010-08-25 11:45:40 +00005981 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005982 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005983 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005984 APFloat &LHS_r = LHS.getComplexFloatReal();
5985 APFloat &LHS_i = LHS.getComplexFloatImag();
5986 APFloat &RHS_r = RHS.getComplexFloatReal();
5987 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005988
Daniel Dunbar3f279872009-01-29 01:32:56 +00005989 APFloat Tmp = LHS_r;
5990 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5991 Result.getComplexFloatReal() = Tmp;
5992 Tmp = LHS_i;
5993 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5994 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5995
5996 Tmp = LHS_r;
5997 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5998 Result.getComplexFloatImag() = Tmp;
5999 Tmp = LHS_i;
6000 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6001 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6002 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00006003 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00006004 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006005 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6006 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00006007 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006008 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6009 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6010 }
6011 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006012 case BO_Div:
6013 if (Result.isComplexFloat()) {
6014 ComplexValue LHS = Result;
6015 APFloat &LHS_r = LHS.getComplexFloatReal();
6016 APFloat &LHS_i = LHS.getComplexFloatImag();
6017 APFloat &RHS_r = RHS.getComplexFloatReal();
6018 APFloat &RHS_i = RHS.getComplexFloatImag();
6019 APFloat &Res_r = Result.getComplexFloatReal();
6020 APFloat &Res_i = Result.getComplexFloatImag();
6021
6022 APFloat Den = RHS_r;
6023 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6024 APFloat Tmp = RHS_i;
6025 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6026 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6027
6028 Res_r = LHS_r;
6029 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6030 Tmp = LHS_i;
6031 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6032 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6033 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6034
6035 Res_i = LHS_i;
6036 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6037 Tmp = LHS_r;
6038 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6039 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6040 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6041 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00006042 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6043 return Error(E, diag::note_expr_divide_by_zero);
6044
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006045 ComplexValue LHS = Result;
6046 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6047 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6048 Result.getComplexIntReal() =
6049 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6050 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6051 Result.getComplexIntImag() =
6052 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6053 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6054 }
6055 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006056 }
6057
John McCallf4cf1a12010-05-07 17:22:02 +00006058 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006059}
6060
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006061bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6062 // Get the operand value into 'Result'.
6063 if (!Visit(E->getSubExpr()))
6064 return false;
6065
6066 switch (E->getOpcode()) {
6067 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00006068 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006069 case UO_Extension:
6070 return true;
6071 case UO_Plus:
6072 // The result is always just the subexpr.
6073 return true;
6074 case UO_Minus:
6075 if (Result.isComplexFloat()) {
6076 Result.getComplexFloatReal().changeSign();
6077 Result.getComplexFloatImag().changeSign();
6078 }
6079 else {
6080 Result.getComplexIntReal() = -Result.getComplexIntReal();
6081 Result.getComplexIntImag() = -Result.getComplexIntImag();
6082 }
6083 return true;
6084 case UO_Not:
6085 if (Result.isComplexFloat())
6086 Result.getComplexFloatImag().changeSign();
6087 else
6088 Result.getComplexIntImag() = -Result.getComplexIntImag();
6089 return true;
6090 }
6091}
6092
Eli Friedman7ead5c72012-01-10 04:58:17 +00006093bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6094 if (E->getNumInits() == 2) {
6095 if (E->getType()->isComplexType()) {
6096 Result.makeComplexFloat();
6097 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6098 return false;
6099 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6100 return false;
6101 } else {
6102 Result.makeComplexInt();
6103 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6104 return false;
6105 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6106 return false;
6107 }
6108 return true;
6109 }
6110 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6111}
6112
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00006113//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00006114// Void expression evaluation, primarily for a cast to void on the LHS of a
6115// comma operator
6116//===----------------------------------------------------------------------===//
6117
6118namespace {
6119class VoidExprEvaluator
6120 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6121public:
6122 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6123
Richard Smith1aa0be82012-03-03 22:46:17 +00006124 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00006125
6126 bool VisitCastExpr(const CastExpr *E) {
6127 switch (E->getCastKind()) {
6128 default:
6129 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6130 case CK_ToVoid:
6131 VisitIgnoredValue(E->getSubExpr());
6132 return true;
6133 }
6134 }
6135};
6136} // end anonymous namespace
6137
6138static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6139 assert(E->isRValue() && E->getType()->isVoidType());
6140 return VoidExprEvaluator(Info).Visit(E);
6141}
6142
6143//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006144// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006145//===----------------------------------------------------------------------===//
6146
Richard Smith1aa0be82012-03-03 22:46:17 +00006147static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006148 // In C, function designators are not lvalues, but we evaluate them as if they
6149 // are.
6150 if (E->isGLValue() || E->getType()->isFunctionType()) {
6151 LValue LV;
6152 if (!EvaluateLValue(E, LV, Info))
6153 return false;
6154 LV.moveInto(Result);
6155 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006156 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006157 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006158 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006159 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006160 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006161 } else if (E->getType()->hasPointerRepresentation()) {
6162 LValue LV;
6163 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006164 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006165 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006166 } else if (E->getType()->isRealFloatingType()) {
6167 llvm::APFloat F(0.0);
6168 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006169 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006170 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006171 } else if (E->getType()->isAnyComplexType()) {
6172 ComplexValue C;
6173 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006174 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006175 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006176 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006177 MemberPtr P;
6178 if (!EvaluateMemberPointer(E, P, Info))
6179 return false;
6180 P.moveInto(Result);
6181 return true;
Richard Smith51201882011-12-30 21:15:51 +00006182 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006183 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006184 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006185 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006186 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006187 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006188 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006189 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006190 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006191 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6192 return false;
6193 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006194 } else if (E->getType()->isVoidType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00006195 if (!Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006196 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00006197 << E->getType();
Richard Smithaa9c3502011-12-07 00:43:50 +00006198 if (!EvaluateVoid(E, Info))
6199 return false;
Richard Smith80ad52f2013-01-02 11:42:31 +00006200 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006201 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006202 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006203 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006204 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006205 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006206 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006207
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006208 return true;
6209}
6210
Richard Smith83587db2012-02-15 02:18:13 +00006211/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6212/// cases, the in-place evaluation is essential, since later initializers for
6213/// an object can indirectly refer to subobjects which were initialized earlier.
6214static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6215 const Expr *E, CheckConstantExpressionKind CCEK,
6216 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006217 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006218 return false;
6219
6220 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006221 // Evaluate arrays and record types in-place, so that later initializers can
6222 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006223 if (E->getType()->isArrayType())
6224 return EvaluateArray(E, This, Result, Info);
6225 else if (E->getType()->isRecordType())
6226 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006227 }
6228
6229 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006230 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006231}
6232
Richard Smithf48fdb02011-12-09 22:58:01 +00006233/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6234/// lvalue-to-rvalue cast if it is an lvalue.
6235static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006236 if (!CheckLiteralType(Info, E))
6237 return false;
6238
Richard Smith1aa0be82012-03-03 22:46:17 +00006239 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006240 return false;
6241
6242 if (E->isGLValue()) {
6243 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006244 LV.setFrom(Info.Ctx, Result);
6245 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006246 return false;
6247 }
6248
Richard Smith1aa0be82012-03-03 22:46:17 +00006249 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006250 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006251}
Richard Smithc49bd112011-10-28 17:51:58 +00006252
Richard Smith51f47082011-10-29 00:50:52 +00006253/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006254/// any crazy technique (that has nothing to do with language standards) that
6255/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006256/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6257/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006258bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006259 // Fast-path evaluations of integer literals, since we sometimes see files
6260 // containing vast quantities of these.
6261 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6262 Result.Val = APValue(APSInt(L->getValue(),
6263 L->getType()->isUnsignedIntegerType()));
6264 return true;
6265 }
6266
Richard Smith2d6a5672012-01-14 04:30:29 +00006267 // FIXME: Evaluating values of large array and record types can cause
6268 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006269 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00006270 !Ctx.getLangOpts().CPlusPlus11)
Richard Smith1445bba2011-11-10 03:30:42 +00006271 return false;
6272
Richard Smithf48fdb02011-12-09 22:58:01 +00006273 EvalInfo Info(Ctx, Result);
6274 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006275}
6276
Jay Foad4ba2a172011-01-12 09:06:06 +00006277bool Expr::EvaluateAsBooleanCondition(bool &Result,
6278 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006279 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006280 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006281 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006282}
6283
Richard Smith80d4b552011-12-28 19:48:30 +00006284bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6285 SideEffectsKind AllowSideEffects) const {
6286 if (!getType()->isIntegralOrEnumerationType())
6287 return false;
6288
Richard Smithc49bd112011-10-28 17:51:58 +00006289 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006290 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6291 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006292 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006293
Richard Smithc49bd112011-10-28 17:51:58 +00006294 Result = ExprResult.Val.getInt();
6295 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006296}
6297
Jay Foad4ba2a172011-01-12 09:06:06 +00006298bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006299 EvalInfo Info(Ctx, Result);
6300
John McCallefdb83e2010-05-07 21:00:08 +00006301 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006302 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6303 !CheckLValueConstantExpression(Info, getExprLoc(),
6304 Ctx.getLValueReferenceType(getType()), LV))
6305 return false;
6306
Richard Smith1aa0be82012-03-03 22:46:17 +00006307 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006308 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006309}
6310
Richard Smith099e7f62011-12-19 06:19:21 +00006311bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6312 const VarDecl *VD,
6313 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006314 // FIXME: Evaluating initializers for large array and record types can cause
6315 // performance problems. Only do so in C++11 for now.
6316 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00006317 !Ctx.getLangOpts().CPlusPlus11)
Richard Smith2d6a5672012-01-14 04:30:29 +00006318 return false;
6319
Richard Smith099e7f62011-12-19 06:19:21 +00006320 Expr::EvalStatus EStatus;
6321 EStatus.Diag = &Notes;
6322
6323 EvalInfo InitInfo(Ctx, EStatus);
6324 InitInfo.setEvaluatingDecl(VD, Value);
6325
6326 LValue LVal;
6327 LVal.set(VD);
6328
Richard Smith51201882011-12-30 21:15:51 +00006329 // C++11 [basic.start.init]p2:
6330 // Variables with static storage duration or thread storage duration shall be
6331 // zero-initialized before any other initialization takes place.
6332 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006333 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006334 !VD->getType()->isReferenceType()) {
6335 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006336 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6337 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006338 return false;
6339 }
6340
Richard Smith83587db2012-02-15 02:18:13 +00006341 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6342 /*AllowNonLiteralTypes=*/true) ||
6343 EStatus.HasSideEffects)
6344 return false;
6345
6346 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6347 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006348}
6349
Richard Smith51f47082011-10-29 00:50:52 +00006350/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6351/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006352bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006353 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006354 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006355}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006356
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006357APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006358 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006359 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006360 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006361 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006362 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006363
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006364 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006365}
John McCalld905f5a2010-05-07 05:32:02 +00006366
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006367 bool Expr::EvalResult::isGlobalLValue() const {
6368 assert(Val.isLValue());
6369 return IsGlobalLValue(Val.getLValueBase());
6370 }
6371
6372
John McCalld905f5a2010-05-07 05:32:02 +00006373/// isIntegerConstantExpr - this recursive routine will test if an expression is
6374/// an integer constant expression.
6375
6376/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6377/// comma, etc
John McCalld905f5a2010-05-07 05:32:02 +00006378
6379// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smithceb59d92012-12-28 13:25:52 +00006380// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
6381// and a (possibly null) SourceLocation indicating the location of the problem.
6382//
John McCalld905f5a2010-05-07 05:32:02 +00006383// 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.
John McCalld905f5a2010-05-07 05:32:02 +00006387
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006388namespace {
6389
Richard Smithceb59d92012-12-28 13:25:52 +00006390enum ICEKind {
6391 /// This expression is an ICE.
6392 IK_ICE,
6393 /// This expression is not an ICE, but if it isn't evaluated, it's
6394 /// a legal subexpression for an ICE. This return value is used to handle
6395 /// the comma operator in C99 mode, and non-constant subexpressions.
6396 IK_ICEIfUnevaluated,
6397 /// This expression is not an ICE, and is not a legal subexpression for one.
6398 IK_NotICE
6399};
6400
John McCalld905f5a2010-05-07 05:32:02 +00006401struct ICEDiag {
Richard Smithceb59d92012-12-28 13:25:52 +00006402 ICEKind Kind;
John McCalld905f5a2010-05-07 05:32:02 +00006403 SourceLocation Loc;
6404
Richard Smithceb59d92012-12-28 13:25:52 +00006405 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCalld905f5a2010-05-07 05:32:02 +00006406};
6407
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006408}
6409
Richard Smithceb59d92012-12-28 13:25:52 +00006410static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
6411
6412static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCalld905f5a2010-05-07 05:32:02 +00006413
6414static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6415 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006416 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smithceb59d92012-12-28 13:25:52 +00006417 !EVResult.Val.isInt())
6418 return ICEDiag(IK_NotICE, E->getLocStart());
6419
John McCalld905f5a2010-05-07 05:32:02 +00006420 return NoDiag();
6421}
6422
6423static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6424 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smithceb59d92012-12-28 13:25:52 +00006425 if (!E->getType()->isIntegralOrEnumerationType())
6426 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006427
6428 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006429#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006430#define STMT(Node, Base) case Expr::Node##Class:
6431#define EXPR(Node, Base)
6432#include "clang/AST/StmtNodes.inc"
6433 case Expr::PredefinedExprClass:
6434 case Expr::FloatingLiteralClass:
6435 case Expr::ImaginaryLiteralClass:
6436 case Expr::StringLiteralClass:
6437 case Expr::ArraySubscriptExprClass:
6438 case Expr::MemberExprClass:
6439 case Expr::CompoundAssignOperatorClass:
6440 case Expr::CompoundLiteralExprClass:
6441 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006442 case Expr::DesignatedInitExprClass:
6443 case Expr::ImplicitValueInitExprClass:
6444 case Expr::ParenListExprClass:
6445 case Expr::VAArgExprClass:
6446 case Expr::AddrLabelExprClass:
6447 case Expr::StmtExprClass:
6448 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006449 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006450 case Expr::CXXDynamicCastExprClass:
6451 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006452 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006453 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006454 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006455 case Expr::CXXThisExprClass:
6456 case Expr::CXXThrowExprClass:
6457 case Expr::CXXNewExprClass:
6458 case Expr::CXXDeleteExprClass:
6459 case Expr::CXXPseudoDestructorExprClass:
6460 case Expr::UnresolvedLookupExprClass:
6461 case Expr::DependentScopeDeclRefExprClass:
6462 case Expr::CXXConstructExprClass:
6463 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006464 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006465 case Expr::CXXTemporaryObjectExprClass:
6466 case Expr::CXXUnresolvedConstructExprClass:
6467 case Expr::CXXDependentScopeMemberExprClass:
6468 case Expr::UnresolvedMemberExprClass:
6469 case Expr::ObjCStringLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +00006470 case Expr::ObjCBoxedExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006471 case Expr::ObjCArrayLiteralClass:
6472 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006473 case Expr::ObjCEncodeExprClass:
6474 case Expr::ObjCMessageExprClass:
6475 case Expr::ObjCSelectorExprClass:
6476 case Expr::ObjCProtocolExprClass:
6477 case Expr::ObjCIvarRefExprClass:
6478 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006479 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006480 case Expr::ObjCIsaExprClass:
6481 case Expr::ShuffleVectorExprClass:
6482 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006483 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006484 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006485 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006486 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smith9a4db032012-09-12 00:56:43 +00006487 case Expr::FunctionParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006488 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006489 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006490 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006491 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006492 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006493 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006494 case Expr::LambdaExprClass:
Richard Smithceb59d92012-12-28 13:25:52 +00006495 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redlcea8d962011-09-24 17:48:14 +00006496
Douglas Gregoree8aff02011-01-04 17:33:58 +00006497 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006498 case Expr::GNUNullExprClass:
6499 // GCC considers the GNU __null value to be an integral constant expression.
6500 return NoDiag();
6501
John McCall91a57552011-07-15 05:09:51 +00006502 case Expr::SubstNonTypeTemplateParmExprClass:
6503 return
6504 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6505
John McCalld905f5a2010-05-07 05:32:02 +00006506 case Expr::ParenExprClass:
6507 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006508 case Expr::GenericSelectionExprClass:
6509 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006510 case Expr::IntegerLiteralClass:
6511 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006512 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006513 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006514 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006515 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006516 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006517 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006518 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006519 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006520 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006521 return NoDiag();
6522 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006523 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006524 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6525 // constant expressions, but they can never be ICEs because an ICE cannot
6526 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006527 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006528 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006529 return CheckEvalInICE(E, Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006530 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006531 }
Richard Smith359c89d2012-02-24 22:12:32 +00006532 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006533 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6534 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006535 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006536 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006537 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006538 // Parameter variables are never constants. Without this check,
6539 // getAnyInitializer() can find a default argument, which leads
6540 // to chaos.
6541 if (isa<ParmVarDecl>(D))
Richard Smithceb59d92012-12-28 13:25:52 +00006542 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006543
6544 // C++ 7.1.5.1p2
6545 // A variable of non-volatile const-qualified integral or enumeration
6546 // type initialized by an ICE can be used in ICEs.
6547 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006548 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smithceb59d92012-12-28 13:25:52 +00006549 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithdb1822c2011-11-08 01:31:09 +00006550
Richard Smith099e7f62011-12-19 06:19:21 +00006551 const VarDecl *VD;
6552 // Look for a declaration of this variable that has an initializer, and
6553 // check whether it is an ICE.
6554 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6555 return NoDiag();
6556 else
Richard Smithceb59d92012-12-28 13:25:52 +00006557 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006558 }
6559 }
Richard Smithceb59d92012-12-28 13:25:52 +00006560 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006561 }
John McCalld905f5a2010-05-07 05:32:02 +00006562 case Expr::UnaryOperatorClass: {
6563 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6564 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006565 case UO_PostInc:
6566 case UO_PostDec:
6567 case UO_PreInc:
6568 case UO_PreDec:
6569 case UO_AddrOf:
6570 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006571 // C99 6.6/3 allows increment and decrement within unevaluated
6572 // subexpressions of constant expressions, but they can never be ICEs
6573 // because an ICE cannot contain an lvalue operand.
Richard Smithceb59d92012-12-28 13:25:52 +00006574 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006575 case UO_Extension:
6576 case UO_LNot:
6577 case UO_Plus:
6578 case UO_Minus:
6579 case UO_Not:
6580 case UO_Real:
6581 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006582 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006583 }
Richard Smithceb59d92012-12-28 13:25:52 +00006584
John McCalld905f5a2010-05-07 05:32:02 +00006585 // OffsetOf falls through here.
6586 }
6587 case Expr::OffsetOfExprClass: {
Richard Smithceb59d92012-12-28 13:25:52 +00006588 // Note that per C99, offsetof must be an ICE. And AFAIK, using
6589 // EvaluateAsRValue matches the proposed gcc behavior for cases like
6590 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
6591 // compliance: we should warn earlier for offsetof expressions with
6592 // array subscripts that aren't ICEs, and if the array subscripts
6593 // are ICEs, the value of the offsetof must be an integer constant.
6594 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006595 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006596 case Expr::UnaryExprOrTypeTraitExprClass: {
6597 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6598 if ((Exp->getKind() == UETT_SizeOf) &&
6599 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smithceb59d92012-12-28 13:25:52 +00006600 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006601 return NoDiag();
6602 }
6603 case Expr::BinaryOperatorClass: {
6604 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6605 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006606 case BO_PtrMemD:
6607 case BO_PtrMemI:
6608 case BO_Assign:
6609 case BO_MulAssign:
6610 case BO_DivAssign:
6611 case BO_RemAssign:
6612 case BO_AddAssign:
6613 case BO_SubAssign:
6614 case BO_ShlAssign:
6615 case BO_ShrAssign:
6616 case BO_AndAssign:
6617 case BO_XorAssign:
6618 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006619 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6620 // constant expressions, but they can never be ICEs because an ICE cannot
6621 // contain an lvalue operand.
Richard Smithceb59d92012-12-28 13:25:52 +00006622 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006623
John McCall2de56d12010-08-25 11:45:40 +00006624 case BO_Mul:
6625 case BO_Div:
6626 case BO_Rem:
6627 case BO_Add:
6628 case BO_Sub:
6629 case BO_Shl:
6630 case BO_Shr:
6631 case BO_LT:
6632 case BO_GT:
6633 case BO_LE:
6634 case BO_GE:
6635 case BO_EQ:
6636 case BO_NE:
6637 case BO_And:
6638 case BO_Xor:
6639 case BO_Or:
6640 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006641 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6642 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006643 if (Exp->getOpcode() == BO_Div ||
6644 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006645 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006646 // we don't evaluate one.
Richard Smithceb59d92012-12-28 13:25:52 +00006647 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006648 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006649 if (REval == 0)
Richard Smithceb59d92012-12-28 13:25:52 +00006650 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006651 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006652 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006653 if (LEval.isMinSignedValue())
Richard Smithceb59d92012-12-28 13:25:52 +00006654 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006655 }
6656 }
6657 }
John McCall2de56d12010-08-25 11:45:40 +00006658 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006659 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006660 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6661 // if it isn't evaluated.
Richard Smithceb59d92012-12-28 13:25:52 +00006662 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
6663 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006664 } else {
6665 // In both C89 and C++, commas in ICEs are illegal.
Richard Smithceb59d92012-12-28 13:25:52 +00006666 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006667 }
6668 }
Richard Smithceb59d92012-12-28 13:25:52 +00006669 return Worst(LHSResult, RHSResult);
John McCalld905f5a2010-05-07 05:32:02 +00006670 }
John McCall2de56d12010-08-25 11:45:40 +00006671 case BO_LAnd:
6672 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006673 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6674 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006675 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCalld905f5a2010-05-07 05:32:02 +00006676 // Rare case where the RHS has a comma "side-effect"; we need
6677 // to actually check the condition to see whether the side
6678 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006679 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006680 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006681 return RHSResult;
6682 return NoDiag();
6683 }
6684
Richard Smithceb59d92012-12-28 13:25:52 +00006685 return Worst(LHSResult, RHSResult);
John McCalld905f5a2010-05-07 05:32:02 +00006686 }
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)
Richard Smithceb59d92012-12-28 13:25:52 +00006710 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith2116b142011-12-18 02:33:09 +00006711 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:
Richard Smithceb59d92012-12-28 13:25:52 +00006723 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedmaneea0e812011-09-29 21:49:34 +00006724 }
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);
Richard Smithceb59d92012-12-28 13:25:52 +00006729 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCall56ca35d2011-02-17 10:25:35 +00006730 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006731 if (FalseResult.Kind == IK_NotICE) return FalseResult;
6732 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
6733 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith9b403c52012-12-28 12:53:55 +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);
Richard Smithceb59d92012-12-28 13:25:52 +00006748 if (CondResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00006749 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
Richard Smithceb59d92012-12-28 13:25:52 +00006754 if (TrueResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00006755 return TrueResult;
Richard Smithceb59d92012-12-28 13:25:52 +00006756 if (FalseResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00006757 return FalseResult;
Richard Smithceb59d92012-12-28 13:25:52 +00006758 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCalld905f5a2010-05-07 05:32:02 +00006759 return CondResult;
Richard Smithceb59d92012-12-28 13:25:52 +00006760 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCalld905f5a2010-05-07 05:32:02 +00006761 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 Smithceb59d92012-12-28 13:25:52 +00006765 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCalld905f5a2010-05-07 05:32:02 +00006766 return FalseResult;
John McCalld905f5a2010-05-07 05:32:02 +00006767 return TrueResult;
6768 }
6769 case Expr::CXXDefaultArgExprClass:
6770 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6771 case Expr::ChooseExprClass: {
6772 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6773 }
6774 }
6775
David Blaikie30263482012-01-20 21:50:17 +00006776 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006777}
6778
Richard Smithf48fdb02011-12-09 22:58:01 +00006779/// Evaluate an expression as a C++11 integral constant expression.
6780static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6781 const Expr *E,
6782 llvm::APSInt *Value,
6783 SourceLocation *Loc) {
6784 if (!E->getType()->isIntegralOrEnumerationType()) {
6785 if (Loc) *Loc = E->getExprLoc();
6786 return false;
6787 }
6788
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006789 APValue Result;
6790 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006791 return false;
6792
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006793 assert(Result.isInt() && "pointer cast to int is not an ICE");
6794 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006795 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006796}
6797
Richard Smithdd1f29b2011-12-12 09:28:41 +00006798bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith80ad52f2013-01-02 11:42:31 +00006799 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf48fdb02011-12-09 22:58:01 +00006800 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6801
Richard Smithceb59d92012-12-28 13:25:52 +00006802 ICEDiag D = CheckICE(this, Ctx);
6803 if (D.Kind != IK_ICE) {
6804 if (Loc) *Loc = D.Loc;
John McCalld905f5a2010-05-07 05:32:02 +00006805 return false;
6806 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006807 return true;
6808}
6809
6810bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6811 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith80ad52f2013-01-02 11:42:31 +00006812 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf48fdb02011-12-09 22:58:01 +00006813 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6814
6815 if (!isIntegerConstantExpr(Ctx, Loc))
6816 return false;
6817 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006818 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006819 return true;
6820}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006821
Richard Smith70488e22012-02-14 21:38:30 +00006822bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smithceb59d92012-12-28 13:25:52 +00006823 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith70488e22012-02-14 21:38:30 +00006824}
6825
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006826bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6827 SourceLocation *Loc) const {
6828 // We support this checking in C++98 mode in order to diagnose compatibility
6829 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006830 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006831
Richard Smith70488e22012-02-14 21:38:30 +00006832 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006833 Expr::EvalStatus Status;
6834 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6835 Status.Diag = &Diags;
6836 EvalInfo Info(Ctx, Status);
6837
6838 APValue Scratch;
6839 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6840
6841 if (!Diags.empty()) {
6842 IsConstExpr = false;
6843 if (Loc) *Loc = Diags[0].first;
6844 } else if (!IsConstExpr) {
6845 // FIXME: This shouldn't happen.
6846 if (Loc) *Loc = getExprLoc();
6847 }
6848
6849 return IsConstExpr;
6850}
Richard Smith745f5142012-01-27 01:14:48 +00006851
6852bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6853 llvm::SmallVectorImpl<
6854 PartialDiagnosticAt> &Diags) {
6855 // FIXME: It would be useful to check constexpr function templates, but at the
6856 // moment the constant expression evaluator cannot cope with the non-rigorous
6857 // ASTs which we build for dependent expressions.
6858 if (FD->isDependentContext())
6859 return true;
6860
6861 Expr::EvalStatus Status;
6862 Status.Diag = &Diags;
6863
6864 EvalInfo Info(FD->getASTContext(), Status);
6865 Info.CheckingPotentialConstantExpression = true;
6866
6867 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6868 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6869
6870 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6871 // is a temporary being used as the 'this' pointer.
6872 LValue This;
6873 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006874 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006875
Richard Smith745f5142012-01-27 01:14:48 +00006876 ArrayRef<const Expr*> Args;
6877
6878 SourceLocation Loc = FD->getLocation();
6879
Richard Smith1aa0be82012-03-03 22:46:17 +00006880 APValue Scratch;
6881 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006882 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006883 else
Richard Smith745f5142012-01-27 01:14:48 +00006884 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6885 Args, FD->getBody(), Info, Scratch);
6886
6887 return Diags.empty();
6888}