blob: ac21b469411116ae048902ca69ed428b977242a1 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith745f5142012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlssonc44eec62008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000038#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000039#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000040#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000041#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000042#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000047#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000048#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000049
Anders Carlssonc44eec62008-07-03 04:20:39 +000050using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000051using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000052using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000053
Richard Smith83587db2012-02-15 02:18:13 +000054static bool IsGlobalLValue(APValue::LValueBase B);
55
John McCallf4cf1a12010-05-07 17:22:02 +000056namespace {
Richard Smith180f4792011-11-10 06:34:14 +000057 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000058 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000059 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000060
Richard Smith83587db2012-02-15 02:18:13 +000061 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +000062 if (!B) return QualType();
63 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
64 return D->getType();
65 return B.get<const Expr*>()->getType();
66 }
67
Richard Smith180f4792011-11-10 06:34:14 +000068 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000069 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000070 static
Richard Smithf15fda02012-02-02 01:16:57 +000071 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000072 APValue::BaseOrMemberType Value;
73 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000074 return Value;
75 }
76
77 /// Get an LValue path entry, which is known to not be an array index, as a
78 /// field declaration.
Richard Smith83587db2012-02-15 02:18:13 +000079 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000080 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000081 }
82 /// Get an LValue path entry, which is known to not be an array index, as a
83 /// base class declaration.
Richard Smith83587db2012-02-15 02:18:13 +000084 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000085 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000086 }
87 /// Determine whether this LValue path entry for a base class names a virtual
88 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +000089 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000090 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +000091 }
92
Richard Smithb4e85ed2012-01-06 16:39:00 +000093 /// Find the path length and type of the most-derived subobject in the given
94 /// path, and find the size of the containing array, if any.
95 static
96 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
97 ArrayRef<APValue::LValuePathEntry> Path,
98 uint64_t &ArraySize, QualType &Type) {
99 unsigned MostDerivedLength = 0;
100 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000101 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000102 if (Type->isArrayType()) {
103 const ConstantArrayType *CAT =
104 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
105 Type = CAT->getElementType();
106 ArraySize = CAT->getSize().getZExtValue();
107 MostDerivedLength = I + 1;
Richard Smith86024012012-02-18 22:04:06 +0000108 } else if (Type->isAnyComplexType()) {
109 const ComplexType *CT = Type->castAs<ComplexType>();
110 Type = CT->getElementType();
111 ArraySize = 2;
112 MostDerivedLength = I + 1;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000113 } else if (const FieldDecl *FD = getAsField(Path[I])) {
114 Type = FD->getType();
115 ArraySize = 0;
116 MostDerivedLength = I + 1;
117 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000118 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000119 ArraySize = 0;
120 }
Richard Smith9a17a682011-11-07 05:07:52 +0000121 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000122 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000123 }
124
Richard Smithb4e85ed2012-01-06 16:39:00 +0000125 // The order of this enum is important for diagnostics.
126 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000127 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith86024012012-02-18 22:04:06 +0000128 CSK_This, CSK_Real, CSK_Imag
Richard Smithb4e85ed2012-01-06 16:39:00 +0000129 };
130
Richard Smith0a3bdb62011-11-04 02:25:55 +0000131 /// A path from a glvalue to a subobject of that glvalue.
132 struct SubobjectDesignator {
133 /// True if the subobject was named in a manner not supported by C++11. Such
134 /// lvalues can still be folded, but they are not core constant expressions
135 /// and we cannot perform lvalue-to-rvalue conversions on them.
136 bool Invalid : 1;
137
Richard Smithb4e85ed2012-01-06 16:39:00 +0000138 /// Is this a pointer one past the end of an object?
139 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000140
Richard Smithb4e85ed2012-01-06 16:39:00 +0000141 /// The length of the path to the most-derived object of which this is a
142 /// subobject.
143 unsigned MostDerivedPathLength : 30;
144
145 /// The size of the array of which the most-derived object is an element, or
146 /// 0 if the most-derived object is not an array element.
147 uint64_t MostDerivedArraySize;
148
149 /// The type of the most derived object referred to by this address.
150 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000151
Richard Smith9a17a682011-11-07 05:07:52 +0000152 typedef APValue::LValuePathEntry PathEntry;
153
Richard Smith0a3bdb62011-11-04 02:25:55 +0000154 /// The entries on the path from the glvalue to the designated subobject.
155 SmallVector<PathEntry, 8> Entries;
156
Richard Smithb4e85ed2012-01-06 16:39:00 +0000157 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000158
Richard Smithb4e85ed2012-01-06 16:39:00 +0000159 explicit SubobjectDesignator(QualType T)
160 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
161 MostDerivedArraySize(0), MostDerivedType(T) {}
162
163 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
164 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
165 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000166 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000167 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000168 ArrayRef<PathEntry> VEntries = V.getLValuePath();
169 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
170 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000171 MostDerivedPathLength =
172 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
173 V.getLValuePath(), MostDerivedArraySize,
174 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000175 }
176 }
177
Richard Smith0a3bdb62011-11-04 02:25:55 +0000178 void setInvalid() {
179 Invalid = true;
180 Entries.clear();
181 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000182
183 /// Determine whether this is a one-past-the-end pointer.
184 bool isOnePastTheEnd() const {
185 if (IsOnePastTheEnd)
186 return true;
187 if (MostDerivedArraySize &&
188 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
189 return true;
190 return false;
191 }
192
193 /// Check that this refers to a valid subobject.
194 bool isValidSubobject() const {
195 if (Invalid)
196 return false;
197 return !isOnePastTheEnd();
198 }
199 /// Check that this refers to a valid subobject, and if not, produce a
200 /// relevant diagnostic and set the designator as invalid.
201 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
202
203 /// Update this designator to refer to the first element within this array.
204 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000205 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000206 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000207 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000208
209 // This is a most-derived object.
210 MostDerivedType = CAT->getElementType();
211 MostDerivedArraySize = CAT->getSize().getZExtValue();
212 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000213 }
214 /// Update this designator to refer to the given base or member of this
215 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000216 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000217 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000218 APValue::BaseOrMemberType Value(D, Virtual);
219 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000220 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000221
222 // If this isn't a base class, it's a new most-derived object.
223 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
224 MostDerivedType = FD->getType();
225 MostDerivedArraySize = 0;
226 MostDerivedPathLength = Entries.size();
227 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000228 }
Richard Smith86024012012-02-18 22:04:06 +0000229 /// Update this designator to refer to the given complex component.
230 void addComplexUnchecked(QualType EltTy, bool Imag) {
231 PathEntry Entry;
232 Entry.ArrayIndex = Imag;
233 Entries.push_back(Entry);
234
235 // This is technically a most-derived object, though in practice this
236 // is unlikely to matter.
237 MostDerivedType = EltTy;
238 MostDerivedArraySize = 2;
239 MostDerivedPathLength = Entries.size();
240 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000241 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000242 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000243 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000244 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000245 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000246 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000247 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
248 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
249 setInvalid();
250 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000251 return;
252 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000253 // [expr.add]p4: For the purposes of these operators, a pointer to a
254 // nonarray object behaves the same as a pointer to the first element of
255 // an array of length one with the type of the object as its element type.
256 if (IsOnePastTheEnd && N == (uint64_t)-1)
257 IsOnePastTheEnd = false;
258 else if (!IsOnePastTheEnd && N == 1)
259 IsOnePastTheEnd = true;
260 else if (N != 0) {
261 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000262 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000263 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000264 }
265 };
266
Richard Smithd0dccea2011-10-28 22:34:42 +0000267 /// A stack frame in the constexpr call stack.
268 struct CallStackFrame {
269 EvalInfo &Info;
270
271 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000272 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000273
Richard Smith08d6e032011-12-16 19:06:07 +0000274 /// CallLoc - The location of the call expression for this call.
275 SourceLocation CallLoc;
276
277 /// Callee - The function which was called.
278 const FunctionDecl *Callee;
279
Richard Smith83587db2012-02-15 02:18:13 +0000280 /// Index - The call index of this call.
281 unsigned Index;
282
Richard Smith180f4792011-11-10 06:34:14 +0000283 /// This - The binding for the this pointer in this call, if any.
284 const LValue *This;
285
Richard Smithd0dccea2011-10-28 22:34:42 +0000286 /// ParmBindings - Parameter bindings for this function call, indexed by
287 /// parameters' function scope indices.
Richard Smith1aa0be82012-03-03 22:46:17 +0000288 const APValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000289
Eli Friedmanf6172ae2012-06-25 21:21:08 +0000290 // Note that we intentionally use std::map here so that references to
291 // values are stable.
292 typedef std::map<const Expr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000293 typedef MapTy::const_iterator temp_iterator;
294 /// Temporaries - Temporary lvalues materialized within this stack frame.
295 MapTy Temporaries;
296
Richard Smith08d6e032011-12-16 19:06:07 +0000297 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
298 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000299 const APValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000300 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000301 };
302
Richard Smithdd1f29b2011-12-12 09:28:41 +0000303 /// A partial diagnostic which we might know in advance that we are not going
304 /// to emit.
305 class OptionalDiagnostic {
306 PartialDiagnostic *Diag;
307
308 public:
309 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
310
311 template<typename T>
312 OptionalDiagnostic &operator<<(const T &v) {
313 if (Diag)
314 *Diag << v;
315 return *this;
316 }
Richard Smith789f9b62012-01-31 04:08:20 +0000317
318 OptionalDiagnostic &operator<<(const APSInt &I) {
319 if (Diag) {
320 llvm::SmallVector<char, 32> Buffer;
321 I.toString(Buffer);
322 *Diag << StringRef(Buffer.data(), Buffer.size());
323 }
324 return *this;
325 }
326
327 OptionalDiagnostic &operator<<(const APFloat &F) {
328 if (Diag) {
329 llvm::SmallVector<char, 32> Buffer;
330 F.toString(Buffer);
331 *Diag << StringRef(Buffer.data(), Buffer.size());
332 }
333 return *this;
334 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000335 };
336
Richard Smith83587db2012-02-15 02:18:13 +0000337 /// EvalInfo - This is a private struct used by the evaluator to capture
338 /// information about a subexpression as it is folded. It retains information
339 /// about the AST context, but also maintains information about the folded
340 /// expression.
341 ///
342 /// If an expression could be evaluated, it is still possible it is not a C
343 /// "integer constant expression" or constant expression. If not, this struct
344 /// captures information about how and why not.
345 ///
346 /// One bit of information passed *into* the request for constant folding
347 /// indicates whether the subexpression is "evaluated" or not according to C
348 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
349 /// evaluate the expression regardless of what the RHS is, but C only allows
350 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000351 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000352 ASTContext &Ctx;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000353
Richard Smithbd552ef2011-10-31 05:52:43 +0000354 /// EvalStatus - Contains information about the evaluation.
355 Expr::EvalStatus &EvalStatus;
356
357 /// CurrentCall - The top of the constexpr call stack.
358 CallStackFrame *CurrentCall;
359
Richard Smithbd552ef2011-10-31 05:52:43 +0000360 /// CallStackDepth - The number of calls in the call stack right now.
361 unsigned CallStackDepth;
362
Richard Smith83587db2012-02-15 02:18:13 +0000363 /// NextCallIndex - The next call index to assign.
364 unsigned NextCallIndex;
365
Richard Smithbd552ef2011-10-31 05:52:43 +0000366 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000367 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000368 CallStackFrame BottomFrame;
369
Richard Smith180f4792011-11-10 06:34:14 +0000370 /// EvaluatingDecl - This is the declaration whose initializer is being
371 /// evaluated, if any.
372 const VarDecl *EvaluatingDecl;
373
374 /// EvaluatingDeclValue - This is the value being constructed for the
375 /// declaration whose initializer is being evaluated, if any.
376 APValue *EvaluatingDeclValue;
377
Richard Smithc1c5f272011-12-13 06:39:58 +0000378 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
379 /// notes attached to it will also be stored, otherwise they will not be.
380 bool HasActiveDiagnostic;
381
Richard Smith745f5142012-01-27 01:14:48 +0000382 /// CheckingPotentialConstantExpression - Are we checking whether the
383 /// expression is a potential constant expression? If so, some diagnostics
384 /// are suppressed.
385 bool CheckingPotentialConstantExpression;
386
Richard Smithbd552ef2011-10-31 05:52:43 +0000387 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000388 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000389 CallStackDepth(0), NextCallIndex(1),
390 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000391 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Argyrios Kyrtzidis649dfbc2012-03-15 18:07:13 +0000392 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000393
Richard Smith180f4792011-11-10 06:34:14 +0000394 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
395 EvaluatingDecl = VD;
396 EvaluatingDeclValue = &Value;
397 }
398
David Blaikie4e4d0842012-03-11 07:00:24 +0000399 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000400
Richard Smithc1c5f272011-12-13 06:39:58 +0000401 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000402 // Don't perform any constexpr calls (other than the call we're checking)
403 // when checking a potential constant expression.
404 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
405 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000406 if (NextCallIndex == 0) {
407 // NextCallIndex has wrapped around.
408 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
409 return false;
410 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000411 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
412 return true;
413 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
414 << getLangOpts().ConstexprCallDepth;
415 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000416 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000417
Richard Smith83587db2012-02-15 02:18:13 +0000418 CallStackFrame *getCallFrame(unsigned CallIndex) {
419 assert(CallIndex && "no call index in getCallFrame");
420 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
421 // be null in this loop.
422 CallStackFrame *Frame = CurrentCall;
423 while (Frame->Index > CallIndex)
424 Frame = Frame->Caller;
425 return (Frame->Index == CallIndex) ? Frame : 0;
426 }
427
Richard Smithc1c5f272011-12-13 06:39:58 +0000428 private:
429 /// Add a diagnostic to the diagnostics list.
430 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
431 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
432 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
433 return EvalStatus.Diag->back().second;
434 }
435
Richard Smith08d6e032011-12-16 19:06:07 +0000436 /// Add notes containing a call stack to the current point of evaluation.
437 void addCallStack(unsigned Limit);
438
Richard Smithc1c5f272011-12-13 06:39:58 +0000439 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000440 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000441 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
442 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000443 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000444 // If we have a prior diagnostic, it will be noting that the expression
445 // isn't a constant expression. This diagnostic is more important.
446 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000447 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000448 unsigned CallStackNotes = CallStackDepth - 1;
449 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
450 if (Limit)
451 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000452 if (CheckingPotentialConstantExpression)
453 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000454
Richard Smithc1c5f272011-12-13 06:39:58 +0000455 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000456 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000457 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
458 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000459 if (!CheckingPotentialConstantExpression)
460 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000461 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000462 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000463 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000464 return OptionalDiagnostic();
465 }
466
Richard Smith5cfc7d82012-03-15 04:53:45 +0000467 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
468 = diag::note_invalid_subexpr_in_const_expr,
469 unsigned ExtraNotes = 0) {
470 if (EvalStatus.Diag)
471 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
472 HasActiveDiagnostic = false;
473 return OptionalDiagnostic();
474 }
475
Richard Smithdd1f29b2011-12-12 09:28:41 +0000476 /// Diagnose that the evaluation does not produce a C++11 core constant
477 /// expression.
Richard Smith5cfc7d82012-03-15 04:53:45 +0000478 template<typename LocArg>
479 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000480 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000481 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000482 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000483 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
484 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000485 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000486 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000487 return Diag(Loc, DiagId, ExtraNotes);
488 }
489
490 /// Add a note to a prior diagnostic.
491 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
492 if (!HasActiveDiagnostic)
493 return OptionalDiagnostic();
494 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000495 }
Richard Smith099e7f62011-12-19 06:19:21 +0000496
497 /// Add a stack of notes to a prior diagnostic.
498 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
499 if (HasActiveDiagnostic) {
500 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
501 Diags.begin(), Diags.end());
502 }
503 }
Richard Smith745f5142012-01-27 01:14:48 +0000504
505 /// Should we continue evaluation as much as possible after encountering a
506 /// construct which can't be folded?
507 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000508 return CheckingPotentialConstantExpression &&
509 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000510 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000511 };
Richard Smithf15fda02012-02-02 01:16:57 +0000512
513 /// Object used to treat all foldable expressions as constant expressions.
514 struct FoldConstant {
515 bool Enabled;
516
517 explicit FoldConstant(EvalInfo &Info)
518 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
519 !Info.EvalStatus.HasSideEffects) {
520 }
521 // Treat the value we've computed since this object was created as constant.
522 void Fold(EvalInfo &Info) {
523 if (Enabled && !Info.EvalStatus.Diag->empty() &&
524 !Info.EvalStatus.HasSideEffects)
525 Info.EvalStatus.Diag->clear();
526 }
527 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000528
529 /// RAII object used to suppress diagnostics and side-effects from a
530 /// speculative evaluation.
531 class SpeculativeEvaluationRAII {
532 EvalInfo &Info;
533 Expr::EvalStatus Old;
534
535 public:
536 SpeculativeEvaluationRAII(EvalInfo &Info,
537 llvm::SmallVectorImpl<PartialDiagnosticAt>
538 *NewDiag = 0)
539 : Info(Info), Old(Info.EvalStatus) {
540 Info.EvalStatus.Diag = NewDiag;
541 }
542 ~SpeculativeEvaluationRAII() {
543 Info.EvalStatus = Old;
544 }
545 };
Richard Smith08d6e032011-12-16 19:06:07 +0000546}
Richard Smithbd552ef2011-10-31 05:52:43 +0000547
Richard Smithb4e85ed2012-01-06 16:39:00 +0000548bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
549 CheckSubobjectKind CSK) {
550 if (Invalid)
551 return false;
552 if (isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000553 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000554 << CSK;
555 setInvalid();
556 return false;
557 }
558 return true;
559}
560
561void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
562 const Expr *E, uint64_t N) {
563 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000564 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000565 << static_cast<int>(N) << /*array*/ 0
566 << static_cast<unsigned>(MostDerivedArraySize);
567 else
Richard Smith5cfc7d82012-03-15 04:53:45 +0000568 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000569 << static_cast<int>(N) << /*non-array*/ 1;
570 setInvalid();
571}
572
Richard Smith08d6e032011-12-16 19:06:07 +0000573CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
574 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000575 const APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000576 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000577 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000578 Info.CurrentCall = this;
579 ++Info.CallStackDepth;
580}
581
582CallStackFrame::~CallStackFrame() {
583 assert(Info.CurrentCall == this && "calls retired out of order");
584 --Info.CallStackDepth;
585 Info.CurrentCall = Caller;
586}
587
588/// Produce a string describing the given constexpr call.
589static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
590 unsigned ArgIndex = 0;
591 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000592 !isa<CXXConstructorDecl>(Frame->Callee) &&
593 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000594
595 if (!IsMemberCall)
596 Out << *Frame->Callee << '(';
597
598 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
599 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000600 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000601 Out << ", ";
602
603 const ParmVarDecl *Param = *I;
Richard Smith1aa0be82012-03-03 22:46:17 +0000604 const APValue &Arg = Frame->Arguments[ArgIndex];
605 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smith08d6e032011-12-16 19:06:07 +0000606
607 if (ArgIndex == 0 && IsMemberCall)
608 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000609 }
610
Richard Smith08d6e032011-12-16 19:06:07 +0000611 Out << ')';
612}
613
614void EvalInfo::addCallStack(unsigned Limit) {
615 // Determine which calls to skip, if any.
616 unsigned ActiveCalls = CallStackDepth - 1;
617 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
618 if (Limit && Limit < ActiveCalls) {
619 SkipStart = Limit / 2 + Limit % 2;
620 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000621 }
622
Richard Smith08d6e032011-12-16 19:06:07 +0000623 // Walk the call stack and add the diagnostics.
624 unsigned CallIdx = 0;
625 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
626 Frame = Frame->Caller, ++CallIdx) {
627 // Skip this call?
628 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
629 if (CallIdx == SkipStart) {
630 // Note that we're skipping calls.
631 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
632 << unsigned(ActiveCalls - Limit);
633 }
634 continue;
635 }
636
637 llvm::SmallVector<char, 128> Buffer;
638 llvm::raw_svector_ostream Out(Buffer);
639 describeCall(Frame, Out);
640 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
641 }
642}
643
644namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000645 struct ComplexValue {
646 private:
647 bool IsInt;
648
649 public:
650 APSInt IntReal, IntImag;
651 APFloat FloatReal, FloatImag;
652
653 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
654
655 void makeComplexFloat() { IsInt = false; }
656 bool isComplexFloat() const { return !IsInt; }
657 APFloat &getComplexFloatReal() { return FloatReal; }
658 APFloat &getComplexFloatImag() { return FloatImag; }
659
660 void makeComplexInt() { IsInt = true; }
661 bool isComplexInt() const { return IsInt; }
662 APSInt &getComplexIntReal() { return IntReal; }
663 APSInt &getComplexIntImag() { return IntImag; }
664
Richard Smith1aa0be82012-03-03 22:46:17 +0000665 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000666 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000667 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000668 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000669 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000670 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000671 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000672 assert(v.isComplexFloat() || v.isComplexInt());
673 if (v.isComplexFloat()) {
674 makeComplexFloat();
675 FloatReal = v.getComplexFloatReal();
676 FloatImag = v.getComplexFloatImag();
677 } else {
678 makeComplexInt();
679 IntReal = v.getComplexIntReal();
680 IntImag = v.getComplexIntImag();
681 }
682 }
John McCallf4cf1a12010-05-07 17:22:02 +0000683 };
John McCallefdb83e2010-05-07 21:00:08 +0000684
685 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000686 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000687 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000688 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000689 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000690
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000691 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000692 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000693 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000694 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000695 SubobjectDesignator &getLValueDesignator() { return Designator; }
696 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000697
Richard Smith1aa0be82012-03-03 22:46:17 +0000698 void moveInto(APValue &V) const {
699 if (Designator.Invalid)
700 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
701 else
702 V = APValue(Base, Offset, Designator.Entries,
703 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000704 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000705 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000706 assert(V.isLValue());
707 Base = V.getLValueBase();
708 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000709 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000710 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000711 }
712
Richard Smith83587db2012-02-15 02:18:13 +0000713 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000714 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000715 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000716 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000717 Designator = SubobjectDesignator(getType(B));
718 }
719
720 // Check that this LValue is not based on a null pointer. If it is, produce
721 // a diagnostic and mark the designator as invalid.
722 bool checkNullPointer(EvalInfo &Info, const Expr *E,
723 CheckSubobjectKind CSK) {
724 if (Designator.Invalid)
725 return false;
726 if (!Base) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000727 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000728 << CSK;
729 Designator.setInvalid();
730 return false;
731 }
732 return true;
733 }
734
735 // Check this LValue refers to an object. If not, set the designator to be
736 // invalid and emit a diagnostic.
737 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000738 // Outside C++11, do not build a designator referring to a subobject of
739 // any object: we won't use such a designator for anything.
740 if (!Info.getLangOpts().CPlusPlus0x)
741 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000742 return checkNullPointer(Info, E, CSK) &&
743 Designator.checkSubobject(Info, E, CSK);
744 }
745
746 void addDecl(EvalInfo &Info, const Expr *E,
747 const Decl *D, bool Virtual = false) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000748 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
749 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000750 }
751 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000752 if (checkSubobject(Info, E, CSK_ArrayToPointer))
753 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000754 }
Richard Smith86024012012-02-18 22:04:06 +0000755 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000756 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
757 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000758 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000759 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000760 if (checkNullPointer(Info, E, CSK_ArrayIndex))
761 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000762 }
John McCallefdb83e2010-05-07 21:00:08 +0000763 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000764
765 struct MemberPtr {
766 MemberPtr() {}
767 explicit MemberPtr(const ValueDecl *Decl) :
768 DeclAndIsDerivedMember(Decl, false), Path() {}
769
770 /// The member or (direct or indirect) field referred to by this member
771 /// pointer, or 0 if this is a null member pointer.
772 const ValueDecl *getDecl() const {
773 return DeclAndIsDerivedMember.getPointer();
774 }
775 /// Is this actually a member of some type derived from the relevant class?
776 bool isDerivedMember() const {
777 return DeclAndIsDerivedMember.getInt();
778 }
779 /// Get the class which the declaration actually lives in.
780 const CXXRecordDecl *getContainingRecord() const {
781 return cast<CXXRecordDecl>(
782 DeclAndIsDerivedMember.getPointer()->getDeclContext());
783 }
784
Richard Smith1aa0be82012-03-03 22:46:17 +0000785 void moveInto(APValue &V) const {
786 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000787 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000788 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000789 assert(V.isMemberPointer());
790 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
791 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
792 Path.clear();
793 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
794 Path.insert(Path.end(), P.begin(), P.end());
795 }
796
797 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
798 /// whether the member is a member of some class derived from the class type
799 /// of the member pointer.
800 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
801 /// Path - The path of base/derived classes from the member declaration's
802 /// class (exclusive) to the class type of the member pointer (inclusive).
803 SmallVector<const CXXRecordDecl*, 4> Path;
804
805 /// Perform a cast towards the class of the Decl (either up or down the
806 /// hierarchy).
807 bool castBack(const CXXRecordDecl *Class) {
808 assert(!Path.empty());
809 const CXXRecordDecl *Expected;
810 if (Path.size() >= 2)
811 Expected = Path[Path.size() - 2];
812 else
813 Expected = getContainingRecord();
814 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
815 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
816 // if B does not contain the original member and is not a base or
817 // derived class of the class containing the original member, the result
818 // of the cast is undefined.
819 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
820 // (D::*). We consider that to be a language defect.
821 return false;
822 }
823 Path.pop_back();
824 return true;
825 }
826 /// Perform a base-to-derived member pointer cast.
827 bool castToDerived(const CXXRecordDecl *Derived) {
828 if (!getDecl())
829 return true;
830 if (!isDerivedMember()) {
831 Path.push_back(Derived);
832 return true;
833 }
834 if (!castBack(Derived))
835 return false;
836 if (Path.empty())
837 DeclAndIsDerivedMember.setInt(false);
838 return true;
839 }
840 /// Perform a derived-to-base member pointer cast.
841 bool castToBase(const CXXRecordDecl *Base) {
842 if (!getDecl())
843 return true;
844 if (Path.empty())
845 DeclAndIsDerivedMember.setInt(true);
846 if (isDerivedMember()) {
847 Path.push_back(Base);
848 return true;
849 }
850 return castBack(Base);
851 }
852 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000853
Richard Smithb02e4622012-02-01 01:42:44 +0000854 /// Compare two member pointers, which are assumed to be of the same type.
855 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
856 if (!LHS.getDecl() || !RHS.getDecl())
857 return !LHS.getDecl() && !RHS.getDecl();
858 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
859 return false;
860 return LHS.Path == RHS.Path;
861 }
862
Richard Smithc1c5f272011-12-13 06:39:58 +0000863 /// Kinds of constant expression checking, for diagnostics.
864 enum CheckConstantExpressionKind {
865 CCEK_Constant, ///< A normal constant.
866 CCEK_ReturnValue, ///< A constexpr function return value.
867 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
868 };
John McCallf4cf1a12010-05-07 17:22:02 +0000869}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000870
Richard Smith1aa0be82012-03-03 22:46:17 +0000871static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000872static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
873 const LValue &This, const Expr *E,
874 CheckConstantExpressionKind CCEK = CCEK_Constant,
875 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000876static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
877static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000878static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
879 EvalInfo &Info);
880static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000881static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000882static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000883 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000884static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000885static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000886
887//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000888// Misc utilities
889//===----------------------------------------------------------------------===//
890
Richard Smith180f4792011-11-10 06:34:14 +0000891/// Should this call expression be treated as a string literal?
892static bool IsStringLiteralCall(const CallExpr *E) {
893 unsigned Builtin = E->isBuiltinCall();
894 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
895 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
896}
897
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000898static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000899 // C++11 [expr.const]p3 An address constant expression is a prvalue core
900 // constant expression of pointer type that evaluates to...
901
902 // ... a null pointer value, or a prvalue core constant expression of type
903 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000904 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000905
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000906 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
907 // ... the address of an object with static storage duration,
908 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
909 return VD->hasGlobalStorage();
910 // ... the address of a function,
911 return isa<FunctionDecl>(D);
912 }
913
914 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000915 switch (E->getStmtClass()) {
916 default:
917 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000918 case Expr::CompoundLiteralExprClass: {
919 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
920 return CLE->isFileScope() && CLE->isLValue();
921 }
Richard Smith180f4792011-11-10 06:34:14 +0000922 // A string literal has static storage duration.
923 case Expr::StringLiteralClass:
924 case Expr::PredefinedExprClass:
925 case Expr::ObjCStringLiteralClass:
926 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000927 case Expr::CXXTypeidExprClass:
Francois Pichete275a182012-04-16 04:08:35 +0000928 case Expr::CXXUuidofExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000929 return true;
930 case Expr::CallExprClass:
931 return IsStringLiteralCall(cast<CallExpr>(E));
932 // For GCC compatibility, &&label has static storage duration.
933 case Expr::AddrLabelExprClass:
934 return true;
935 // A Block literal expression may be used as the initialization value for
936 // Block variables at global or local static scope.
937 case Expr::BlockExprClass:
938 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000939 case Expr::ImplicitValueInitExprClass:
940 // FIXME:
941 // We can never form an lvalue with an implicit value initialization as its
942 // base through expression evaluation, so these only appear in one case: the
943 // implicit variable declaration we invent when checking whether a constexpr
944 // constructor can produce a constant expression. We must assume that such
945 // an expression might be a global lvalue.
946 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000947 }
John McCall42c8f872010-05-10 23:27:23 +0000948}
949
Richard Smith83587db2012-02-15 02:18:13 +0000950static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
951 assert(Base && "no location for a null lvalue");
952 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
953 if (VD)
954 Info.Note(VD->getLocation(), diag::note_declared_at);
955 else
Ted Kremenek890f0f12012-08-23 20:46:57 +0000956 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smith83587db2012-02-15 02:18:13 +0000957 diag::note_constexpr_temporary_here);
958}
959
Richard Smith9a17a682011-11-07 05:07:52 +0000960/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000961/// value for an address or reference constant expression. Return true if we
962/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000963static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
964 QualType Type, const LValue &LVal) {
965 bool IsReferenceType = Type->isReferenceType();
966
Richard Smithc1c5f272011-12-13 06:39:58 +0000967 APValue::LValueBase Base = LVal.getLValueBase();
968 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
969
Richard Smithb78ae972012-02-18 04:58:18 +0000970 // Check that the object is a global. Note that the fake 'this' object we
971 // manufacture when checking potential constant expressions is conservatively
972 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000973 if (!IsGlobalLValue(Base)) {
974 if (Info.getLangOpts().CPlusPlus0x) {
975 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000976 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
977 << IsReferenceType << !Designator.Entries.empty()
978 << !!VD << VD;
979 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000980 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000981 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000982 }
Richard Smith61e61622012-01-12 06:08:57 +0000983 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000984 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000985 }
Richard Smith83587db2012-02-15 02:18:13 +0000986 assert((Info.CheckingPotentialConstantExpression ||
987 LVal.getLValueCallIndex() == 0) &&
988 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +0000989
990 // Allow address constant expressions to be past-the-end pointers. This is
991 // an extension: the standard requires them to point to an object.
992 if (!IsReferenceType)
993 return true;
994
995 // A reference constant expression must refer to an object.
996 if (!Base) {
997 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +0000998 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +0000999 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001000 }
1001
Richard Smithc1c5f272011-12-13 06:39:58 +00001002 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001003 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001004 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001005 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001006 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001007 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001008 }
1009
Richard Smith9a17a682011-11-07 05:07:52 +00001010 return true;
1011}
1012
Richard Smith51201882011-12-30 21:15:51 +00001013/// Check that this core constant expression is of literal type, and if not,
1014/// produce an appropriate diagnostic.
1015static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1016 if (!E->isRValue() || E->getType()->isLiteralType())
1017 return true;
1018
1019 // Prvalue constant expressions must be of literal types.
1020 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001021 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001022 << E->getType();
1023 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001024 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001025 return false;
1026}
1027
Richard Smith47a1eed2011-10-29 20:57:55 +00001028/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001029/// constant expression. If not, report an appropriate diagnostic. Does not
1030/// check that the expression is of literal type.
1031static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1032 QualType Type, const APValue &Value) {
1033 // Core issue 1454: For a literal constant expression of array or class type,
1034 // each subobject of its value shall have been initialized by a constant
1035 // expression.
1036 if (Value.isArray()) {
1037 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1038 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1039 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1040 Value.getArrayInitializedElt(I)))
1041 return false;
1042 }
1043 if (!Value.hasArrayFiller())
1044 return true;
1045 return CheckConstantExpression(Info, DiagLoc, EltTy,
1046 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001047 }
Richard Smith83587db2012-02-15 02:18:13 +00001048 if (Value.isUnion() && Value.getUnionField()) {
1049 return CheckConstantExpression(Info, DiagLoc,
1050 Value.getUnionField()->getType(),
1051 Value.getUnionValue());
1052 }
1053 if (Value.isStruct()) {
1054 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1055 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1056 unsigned BaseIndex = 0;
1057 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1058 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1059 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1060 Value.getStructBase(BaseIndex)))
1061 return false;
1062 }
1063 }
1064 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1065 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001066 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1067 Value.getStructField(I->getFieldIndex())))
Richard Smith83587db2012-02-15 02:18:13 +00001068 return false;
1069 }
1070 }
1071
1072 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001073 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001074 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001075 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1076 }
1077
1078 // Everything else is fine.
1079 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001080}
1081
Richard Smith9e36b532011-10-31 05:11:32 +00001082const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001083 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001084}
1085
1086static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001087 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001088}
1089
Richard Smith65ac5982011-11-01 21:06:14 +00001090static bool IsWeakLValue(const LValue &Value) {
1091 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001092 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001093}
1094
Richard Smith1aa0be82012-03-03 22:46:17 +00001095static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001096 // A null base expression indicates a null pointer. These are always
1097 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001098 if (!Value.getLValueBase()) {
1099 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001100 return true;
1101 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001102
Richard Smithe24f5fc2011-11-17 22:56:20 +00001103 // We have a non-null base. These are generally known to be true, but if it's
1104 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001105 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001106 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001107 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001108}
1109
Richard Smith1aa0be82012-03-03 22:46:17 +00001110static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001111 switch (Val.getKind()) {
1112 case APValue::Uninitialized:
1113 return false;
1114 case APValue::Int:
1115 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001116 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001117 case APValue::Float:
1118 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001119 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001120 case APValue::ComplexInt:
1121 Result = Val.getComplexIntReal().getBoolValue() ||
1122 Val.getComplexIntImag().getBoolValue();
1123 return true;
1124 case APValue::ComplexFloat:
1125 Result = !Val.getComplexFloatReal().isZero() ||
1126 !Val.getComplexFloatImag().isZero();
1127 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001128 case APValue::LValue:
1129 return EvalPointerValueAsBool(Val, Result);
1130 case APValue::MemberPointer:
1131 Result = Val.getMemberPointerDecl();
1132 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001133 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001134 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001135 case APValue::Struct:
1136 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001137 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001138 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001139 }
1140
Richard Smithc49bd112011-10-28 17:51:58 +00001141 llvm_unreachable("unknown APValue kind");
1142}
1143
1144static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1145 EvalInfo &Info) {
1146 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001147 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001148 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001149 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001150 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001151}
1152
Richard Smithc1c5f272011-12-13 06:39:58 +00001153template<typename T>
Eli Friedman26dc97c2012-07-17 21:03:05 +00001154static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +00001155 const T &SrcValue, QualType DestType) {
Eli Friedman26dc97c2012-07-17 21:03:05 +00001156 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001157 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001158}
1159
1160static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1161 QualType SrcType, const APFloat &Value,
1162 QualType DestType, APSInt &Result) {
1163 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001164 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001165 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001166
Richard Smithc1c5f272011-12-13 06:39:58 +00001167 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001168 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001169 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1170 & APFloat::opInvalidOp)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001171 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001172 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001173}
1174
Richard Smithc1c5f272011-12-13 06:39:58 +00001175static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1176 QualType SrcType, QualType DestType,
1177 APFloat &Result) {
1178 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001179 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001180 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1181 APFloat::rmNearestTiesToEven, &ignored)
1182 & APFloat::opOverflow)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001183 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001184 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001185}
1186
Richard Smithf72fccf2012-01-30 22:27:01 +00001187static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1188 QualType DestType, QualType SrcType,
1189 APSInt &Value) {
1190 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001191 APSInt Result = Value;
1192 // Figure out if this is a truncate, extend or noop cast.
1193 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001194 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001195 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001196 return Result;
1197}
1198
Richard Smithc1c5f272011-12-13 06:39:58 +00001199static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1200 QualType SrcType, const APSInt &Value,
1201 QualType DestType, APFloat &Result) {
1202 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1203 if (Result.convertFromAPInt(Value, Value.isSigned(),
1204 APFloat::rmNearestTiesToEven)
1205 & APFloat::opOverflow)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001206 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001207 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001208}
1209
Eli Friedmane6a24e82011-12-22 03:51:45 +00001210static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1211 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001212 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001213 if (!Evaluate(SVal, Info, E))
1214 return false;
1215 if (SVal.isInt()) {
1216 Res = SVal.getInt();
1217 return true;
1218 }
1219 if (SVal.isFloat()) {
1220 Res = SVal.getFloat().bitcastToAPInt();
1221 return true;
1222 }
1223 if (SVal.isVector()) {
1224 QualType VecTy = E->getType();
1225 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1226 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1227 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1228 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1229 Res = llvm::APInt::getNullValue(VecSize);
1230 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1231 APValue &Elt = SVal.getVectorElt(i);
1232 llvm::APInt EltAsInt;
1233 if (Elt.isInt()) {
1234 EltAsInt = Elt.getInt();
1235 } else if (Elt.isFloat()) {
1236 EltAsInt = Elt.getFloat().bitcastToAPInt();
1237 } else {
1238 // Don't try to handle vectors of anything other than int or float
1239 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001240 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001241 return false;
1242 }
1243 unsigned BaseEltSize = EltAsInt.getBitWidth();
1244 if (BigEndian)
1245 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1246 else
1247 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1248 }
1249 return true;
1250 }
1251 // Give up if the input isn't an int, float, or vector. For example, we
1252 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001253 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001254 return false;
1255}
1256
Richard Smithb4e85ed2012-01-06 16:39:00 +00001257/// Cast an lvalue referring to a base subobject to a derived class, by
1258/// truncating the lvalue's path to the given length.
1259static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1260 const RecordDecl *TruncatedType,
1261 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001262 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001263
1264 // Check we actually point to a derived class object.
1265 if (TruncatedElements == D.Entries.size())
1266 return true;
1267 assert(TruncatedElements >= D.MostDerivedPathLength &&
1268 "not casting to a derived class");
1269 if (!Result.checkSubobject(Info, E, CSK_Derived))
1270 return false;
1271
1272 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001273 const RecordDecl *RD = TruncatedType;
1274 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCall8d59dee2012-05-01 00:38:49 +00001275 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001276 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1277 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001278 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001279 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001280 else
Richard Smith180f4792011-11-10 06:34:14 +00001281 Result.Offset -= Layout.getBaseClassOffset(Base);
1282 RD = Base;
1283 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001284 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001285 return true;
1286}
1287
John McCall8d59dee2012-05-01 00:38:49 +00001288static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001289 const CXXRecordDecl *Derived,
1290 const CXXRecordDecl *Base,
1291 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001292 if (!RL) {
1293 if (Derived->isInvalidDecl()) return false;
1294 RL = &Info.Ctx.getASTRecordLayout(Derived);
1295 }
1296
Richard Smith180f4792011-11-10 06:34:14 +00001297 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001298 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCall8d59dee2012-05-01 00:38:49 +00001299 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001300}
1301
Richard Smithb4e85ed2012-01-06 16:39:00 +00001302static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001303 const CXXRecordDecl *DerivedDecl,
1304 const CXXBaseSpecifier *Base) {
1305 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1306
John McCall8d59dee2012-05-01 00:38:49 +00001307 if (!Base->isVirtual())
1308 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001309
Richard Smithb4e85ed2012-01-06 16:39:00 +00001310 SubobjectDesignator &D = Obj.Designator;
1311 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001312 return false;
1313
Richard Smithb4e85ed2012-01-06 16:39:00 +00001314 // Extract most-derived object and corresponding type.
1315 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1316 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1317 return false;
1318
1319 // Find the virtual base class.
John McCall8d59dee2012-05-01 00:38:49 +00001320 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001321 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1322 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001323 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001324 return true;
1325}
1326
1327/// Update LVal to refer to the given field, which must be a member of the type
1328/// currently described by LVal.
John McCall8d59dee2012-05-01 00:38:49 +00001329static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001330 const FieldDecl *FD,
1331 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001332 if (!RL) {
1333 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001334 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCall8d59dee2012-05-01 00:38:49 +00001335 }
Richard Smith180f4792011-11-10 06:34:14 +00001336
1337 unsigned I = FD->getFieldIndex();
1338 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001339 LVal.addDecl(Info, E, FD);
John McCall8d59dee2012-05-01 00:38:49 +00001340 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001341}
1342
Richard Smithd9b02e72012-01-25 22:15:11 +00001343/// Update LVal to refer to the given indirect field.
John McCall8d59dee2012-05-01 00:38:49 +00001344static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smithd9b02e72012-01-25 22:15:11 +00001345 LValue &LVal,
1346 const IndirectFieldDecl *IFD) {
1347 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1348 CE = IFD->chain_end(); C != CE; ++C)
John McCall8d59dee2012-05-01 00:38:49 +00001349 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1350 return false;
1351 return true;
Richard Smithd9b02e72012-01-25 22:15:11 +00001352}
1353
Richard Smith180f4792011-11-10 06:34:14 +00001354/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001355static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1356 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001357 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1358 // extension.
1359 if (Type->isVoidType() || Type->isFunctionType()) {
1360 Size = CharUnits::One();
1361 return true;
1362 }
1363
1364 if (!Type->isConstantSizeType()) {
1365 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001366 // FIXME: Better diagnostic.
1367 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001368 return false;
1369 }
1370
1371 Size = Info.Ctx.getTypeSizeInChars(Type);
1372 return true;
1373}
1374
1375/// Update a pointer value to model pointer arithmetic.
1376/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001377/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001378/// \param LVal - The pointer value to be updated.
1379/// \param EltTy - The pointee type represented by LVal.
1380/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001381static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1382 LValue &LVal, QualType EltTy,
1383 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001384 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001385 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001386 return false;
1387
1388 // Compute the new offset in the appropriate width.
1389 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001390 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001391 return true;
1392}
1393
Richard Smith86024012012-02-18 22:04:06 +00001394/// Update an lvalue to refer to a component of a complex number.
1395/// \param Info - Information about the ongoing evaluation.
1396/// \param LVal - The lvalue to be updated.
1397/// \param EltTy - The complex number's component type.
1398/// \param Imag - False for the real component, true for the imaginary.
1399static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1400 LValue &LVal, QualType EltTy,
1401 bool Imag) {
1402 if (Imag) {
1403 CharUnits SizeOfComponent;
1404 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1405 return false;
1406 LVal.Offset += SizeOfComponent;
1407 }
1408 LVal.addComplex(Info, E, EltTy, Imag);
1409 return true;
1410}
1411
Richard Smith03f96112011-10-24 17:54:18 +00001412/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001413static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1414 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001415 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001416 // If this is a parameter to an active constexpr function call, perform
1417 // argument substitution.
1418 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001419 // Assume arguments of a potential constant expression are unknown
1420 // constant expressions.
1421 if (Info.CheckingPotentialConstantExpression)
1422 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001423 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001424 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001425 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001426 }
Richard Smith177dce72011-11-01 16:57:24 +00001427 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1428 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001429 }
Richard Smith03f96112011-10-24 17:54:18 +00001430
Richard Smith099e7f62011-12-19 06:19:21 +00001431 // Dig out the initializer, and use the declaration which it's attached to.
1432 const Expr *Init = VD->getAnyInitializer(VD);
1433 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001434 // If we're checking a potential constant expression, the variable could be
1435 // initialized later.
1436 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001437 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001438 return false;
1439 }
1440
Richard Smith180f4792011-11-10 06:34:14 +00001441 // If we're currently evaluating the initializer of this declaration, use that
1442 // in-flight value.
1443 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001444 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001445 return !Result.isUninit();
1446 }
1447
Richard Smith65ac5982011-11-01 21:06:14 +00001448 // Never evaluate the initializer of a weak variable. We can't be sure that
1449 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001450 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001451 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001452 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001453 }
Richard Smith65ac5982011-11-01 21:06:14 +00001454
Richard Smith099e7f62011-12-19 06:19:21 +00001455 // Check that we can fold the initializer. In C++, we will have already done
1456 // this in the cases where it matters for conformance.
1457 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1458 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001459 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001460 Notes.size() + 1) << VD;
1461 Info.Note(VD->getLocation(), diag::note_declared_at);
1462 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001463 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001464 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001465 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001466 Notes.size() + 1) << VD;
1467 Info.Note(VD->getLocation(), diag::note_declared_at);
1468 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001469 }
Richard Smith03f96112011-10-24 17:54:18 +00001470
Richard Smith1aa0be82012-03-03 22:46:17 +00001471 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001472 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001473}
1474
Richard Smithc49bd112011-10-28 17:51:58 +00001475static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001476 Qualifiers Quals = T.getQualifiers();
1477 return Quals.hasConst() && !Quals.hasVolatile();
1478}
1479
Richard Smith59efe262011-11-11 04:05:33 +00001480/// Get the base index of the given base class within an APValue representing
1481/// the given derived class.
1482static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1483 const CXXRecordDecl *Base) {
1484 Base = Base->getCanonicalDecl();
1485 unsigned Index = 0;
1486 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1487 E = Derived->bases_end(); I != E; ++I, ++Index) {
1488 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1489 return Index;
1490 }
1491
1492 llvm_unreachable("base class missing from derived class's bases list");
1493}
1494
Richard Smithfe587202012-04-15 02:50:59 +00001495/// Extract the value of a character from a string literal. CharType is used to
1496/// determine the expected signedness of the result -- a string literal used to
1497/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1498/// of the wrong signedness.
Richard Smithf3908f22012-02-17 03:35:37 +00001499static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smithfe587202012-04-15 02:50:59 +00001500 uint64_t Index, QualType CharType) {
Richard Smithf3908f22012-02-17 03:35:37 +00001501 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1502 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1503 assert(S && "unexpected string literal expression kind");
Richard Smithfe587202012-04-15 02:50:59 +00001504 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smithf3908f22012-02-17 03:35:37 +00001505
1506 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smithfe587202012-04-15 02:50:59 +00001507 CharType->isUnsignedIntegerType());
Richard Smithf3908f22012-02-17 03:35:37 +00001508 if (Index < S->getLength())
1509 Value = S->getCodeUnit(Index);
1510 return Value;
1511}
1512
Richard Smithcc5d4f62011-11-07 09:22:26 +00001513/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001514static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001515 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001516 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001517 if (Sub.Invalid)
1518 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001519 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001520 if (Sub.isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001521 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001522 (unsigned)diag::note_constexpr_read_past_end :
1523 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001524 return false;
1525 }
Richard Smithf64699e2011-11-11 08:28:03 +00001526 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001527 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001528 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1529 // This object might be initialized later.
1530 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001531
Richard Smith0069b842012-03-10 00:28:11 +00001532 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001533 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001534 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001535 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001536 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001537 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001538 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001539 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001540 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001541 // Note, it should not be possible to form a pointer with a valid
1542 // designator which points more than one past the end of the array.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001543 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001544 (unsigned)diag::note_constexpr_read_past_end :
1545 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001546 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001547 }
Richard Smithf3908f22012-02-17 03:35:37 +00001548 // An array object is represented as either an Array APValue or as an
1549 // LValue which refers to a string literal.
1550 if (O->isLValue()) {
1551 assert(I == N - 1 && "extracting subobject of character?");
1552 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001553 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithfe587202012-04-15 02:50:59 +00001554 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smithf3908f22012-02-17 03:35:37 +00001555 return true;
1556 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001557 O = &O->getArrayInitializedElt(Index);
1558 else
1559 O = &O->getArrayFiller();
1560 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001561 } else if (ObjType->isAnyComplexType()) {
1562 // Next subobject is a complex number.
1563 uint64_t Index = Sub.Entries[I].ArrayIndex;
1564 if (Index > 1) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001565 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Richard Smith86024012012-02-18 22:04:06 +00001566 (unsigned)diag::note_constexpr_read_past_end :
1567 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1568 return false;
1569 }
1570 assert(I == N - 1 && "extracting subobject of scalar?");
1571 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001572 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001573 : O->getComplexIntReal());
1574 } else {
1575 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001576 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001577 : O->getComplexFloatReal());
1578 }
1579 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001580 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001581 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001582 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001583 << Field;
1584 Info.Note(Field->getLocation(), diag::note_declared_at);
1585 return false;
1586 }
1587
Richard Smith180f4792011-11-10 06:34:14 +00001588 // Next subobject is a class, struct or union field.
1589 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1590 if (RD->isUnion()) {
1591 const FieldDecl *UnionField = O->getUnionField();
1592 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001593 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001594 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001595 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001596 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001597 }
Richard Smith180f4792011-11-10 06:34:14 +00001598 O = &O->getUnionValue();
1599 } else
1600 O = &O->getStructField(Field->getFieldIndex());
1601 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001602
1603 if (ObjType.isVolatileQualified()) {
1604 if (Info.getLangOpts().CPlusPlus) {
1605 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001606 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001607 << 2 << Field;
1608 Info.Note(Field->getLocation(), diag::note_declared_at);
1609 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001610 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001611 }
1612 return false;
1613 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001614 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001615 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001616 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1617 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1618 O = &O->getStructBase(getBaseIndex(Derived, Base));
1619 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001620 }
Richard Smith180f4792011-11-10 06:34:14 +00001621
Richard Smithf48fdb02011-12-09 22:58:01 +00001622 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001623 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001624 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001625 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001626 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001627 }
1628
Richard Smith0069b842012-03-10 00:28:11 +00001629 // This may look super-stupid, but it serves an important purpose: if we just
1630 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1631 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1632 // object, which is destroyed by Tmp's destructor.
1633 APValue Tmp;
1634 O->swap(Tmp);
1635 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001636 return true;
1637}
1638
Richard Smithf15fda02012-02-02 01:16:57 +00001639/// Find the position where two subobject designators diverge, or equivalently
1640/// the length of the common initial subsequence.
1641static unsigned FindDesignatorMismatch(QualType ObjType,
1642 const SubobjectDesignator &A,
1643 const SubobjectDesignator &B,
1644 bool &WasArrayIndex) {
1645 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1646 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001647 if (!ObjType.isNull() &&
1648 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001649 // Next subobject is an array element.
1650 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1651 WasArrayIndex = true;
1652 return I;
1653 }
Richard Smith86024012012-02-18 22:04:06 +00001654 if (ObjType->isAnyComplexType())
1655 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1656 else
1657 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001658 } else {
1659 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1660 WasArrayIndex = false;
1661 return I;
1662 }
1663 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1664 // Next subobject is a field.
1665 ObjType = FD->getType();
1666 else
1667 // Next subobject is a base class.
1668 ObjType = QualType();
1669 }
1670 }
1671 WasArrayIndex = false;
1672 return I;
1673}
1674
1675/// Determine whether the given subobject designators refer to elements of the
1676/// same array object.
1677static bool AreElementsOfSameArray(QualType ObjType,
1678 const SubobjectDesignator &A,
1679 const SubobjectDesignator &B) {
1680 if (A.Entries.size() != B.Entries.size())
1681 return false;
1682
1683 bool IsArray = A.MostDerivedArraySize != 0;
1684 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1685 // A is a subobject of the array element.
1686 return false;
1687
1688 // If A (and B) designates an array element, the last entry will be the array
1689 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1690 // of length 1' case, and the entire path must match.
1691 bool WasArrayIndex;
1692 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1693 return CommonLength >= A.Entries.size() - IsArray;
1694}
1695
Richard Smith180f4792011-11-10 06:34:14 +00001696/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1697/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1698/// for looking up the glvalue referred to by an entity of reference type.
1699///
1700/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001701/// \param Conv - The expression for which we are performing the conversion.
1702/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001703/// \param Type - The type we expect this conversion to produce, before
1704/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001705/// \param LVal - The glvalue on which we are attempting to perform this action.
1706/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001707static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1708 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001709 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001710 if (LVal.Designator.Invalid)
1711 // A diagnostic will have already been produced.
1712 return false;
1713
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001714 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001715
Richard Smithf48fdb02011-12-09 22:58:01 +00001716 if (!LVal.Base) {
1717 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001718 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001719 return false;
1720 }
1721
Richard Smith83587db2012-02-15 02:18:13 +00001722 CallStackFrame *Frame = 0;
1723 if (LVal.CallIndex) {
1724 Frame = Info.getCallFrame(LVal.CallIndex);
1725 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001726 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001727 NoteLValueLocation(Info, LVal.Base);
1728 return false;
1729 }
1730 }
1731
Richard Smith7098cbd2011-12-21 05:04:46 +00001732 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1733 // is not a constant expression (even if the object is non-volatile). We also
1734 // apply this rule to C++98, in order to conform to the expected 'volatile'
1735 // semantics.
1736 if (Type.isVolatileQualified()) {
1737 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001738 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001739 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001740 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001741 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001742 }
Richard Smithc49bd112011-10-28 17:51:58 +00001743
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001744 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001745 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1746 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001747 // expressions are constant expressions too. Inside constexpr functions,
1748 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001749 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001750 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregord2008e22012-04-06 22:40:38 +00001751 if (VD) {
1752 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1753 VD = VDef;
1754 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001755 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001756 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001757 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001758 }
1759
Richard Smith7098cbd2011-12-21 05:04:46 +00001760 // DR1313: If the object is volatile-qualified but the glvalue was not,
1761 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001762 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001763 if (VT.isVolatileQualified()) {
1764 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001765 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001766 Info.Note(VD->getLocation(), diag::note_declared_at);
1767 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001768 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001769 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001770 return false;
1771 }
1772
1773 if (!isa<ParmVarDecl>(VD)) {
1774 if (VD->isConstexpr()) {
1775 // OK, we can read this variable.
1776 } else if (VT->isIntegralOrEnumerationType()) {
1777 if (!VT.isConstQualified()) {
1778 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001779 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001780 Info.Note(VD->getLocation(), diag::note_declared_at);
1781 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001782 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001783 }
1784 return false;
1785 }
1786 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1787 // We support folding of const floating-point types, in order to make
1788 // static const data members of such types (supported as an extension)
1789 // more useful.
1790 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001791 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001792 Info.Note(VD->getLocation(), diag::note_declared_at);
1793 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001794 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001795 }
1796 } else {
1797 // FIXME: Allow folding of values of any literal type in all languages.
1798 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001799 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001800 Info.Note(VD->getLocation(), diag::note_declared_at);
1801 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001802 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001803 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001804 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001805 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001806 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001807
Richard Smithf48fdb02011-12-09 22:58:01 +00001808 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001809 return false;
1810
Richard Smith47a1eed2011-10-29 20:57:55 +00001811 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001812 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001813
1814 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1815 // conversion. This happens when the declaration and the lvalue should be
1816 // considered synonymous, for instance when initializing an array of char
1817 // from a string literal. Continue as if the initializer lvalue was the
1818 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001819 assert(RVal.getLValueOffset().isZero() &&
1820 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001821 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001822
1823 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1824 Frame = Info.getCallFrame(CallIndex);
1825 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001826 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001827 NoteLValueLocation(Info, RVal.getLValueBase());
1828 return false;
1829 }
1830 } else {
1831 Frame = 0;
1832 }
Richard Smithc49bd112011-10-28 17:51:58 +00001833 }
1834
Richard Smith7098cbd2011-12-21 05:04:46 +00001835 // Volatile temporary objects cannot be read in constant expressions.
1836 if (Base->getType().isVolatileQualified()) {
1837 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001838 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001839 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1840 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001841 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001842 }
1843 return false;
1844 }
1845
Richard Smithcc5d4f62011-11-07 09:22:26 +00001846 if (Frame) {
1847 // If this is a temporary expression with a nontrivial initializer, grab the
1848 // value from the relevant stack frame.
1849 RVal = Frame->Temporaries[Base];
1850 } else if (const CompoundLiteralExpr *CLE
1851 = dyn_cast<CompoundLiteralExpr>(Base)) {
1852 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1853 // initializer until now for such expressions. Such an expression can't be
1854 // an ICE in C, so this only matters for fold.
1855 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1856 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1857 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001858 } else if (isa<StringLiteral>(Base)) {
1859 // We represent a string literal array as an lvalue pointing at the
1860 // corresponding expression, rather than building an array of chars.
1861 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001862 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001863 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001864 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001865 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001866 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001867
Richard Smithf48fdb02011-12-09 22:58:01 +00001868 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1869 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001870}
1871
Richard Smith59efe262011-11-11 04:05:33 +00001872/// Build an lvalue for the object argument of a member function call.
1873static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1874 LValue &This) {
1875 if (Object->getType()->isPointerType())
1876 return EvaluatePointer(Object, This, Info);
1877
1878 if (Object->isGLValue())
1879 return EvaluateLValue(Object, This, Info);
1880
Richard Smithe24f5fc2011-11-17 22:56:20 +00001881 if (Object->getType()->isLiteralType())
1882 return EvaluateTemporary(Object, This, Info);
1883
1884 return false;
1885}
1886
1887/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1888/// lvalue referring to the result.
1889///
1890/// \param Info - Information about the ongoing evaluation.
1891/// \param BO - The member pointer access operation.
1892/// \param LV - Filled in with a reference to the resulting object.
1893/// \param IncludeMember - Specifies whether the member itself is included in
1894/// the resulting LValue subobject designator. This is not possible when
1895/// creating a bound member function.
1896/// \return The field or method declaration to which the member pointer refers,
1897/// or 0 if evaluation fails.
1898static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1899 const BinaryOperator *BO,
1900 LValue &LV,
1901 bool IncludeMember = true) {
1902 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1903
Richard Smith745f5142012-01-27 01:14:48 +00001904 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1905 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001906 return 0;
1907
1908 MemberPtr MemPtr;
1909 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1910 return 0;
1911
1912 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1913 // member value, the behavior is undefined.
1914 if (!MemPtr.getDecl())
1915 return 0;
1916
Richard Smith745f5142012-01-27 01:14:48 +00001917 if (!EvalObjOK)
1918 return 0;
1919
Richard Smithe24f5fc2011-11-17 22:56:20 +00001920 if (MemPtr.isDerivedMember()) {
1921 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001922 // The end of the derived-to-base path for the base object must match the
1923 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001924 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001925 LV.Designator.Entries.size())
1926 return 0;
1927 unsigned PathLengthToMember =
1928 LV.Designator.Entries.size() - MemPtr.Path.size();
1929 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1930 const CXXRecordDecl *LVDecl = getAsBaseClass(
1931 LV.Designator.Entries[PathLengthToMember + I]);
1932 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1933 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1934 return 0;
1935 }
1936
1937 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001938 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1939 PathLengthToMember))
1940 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001941 } else if (!MemPtr.Path.empty()) {
1942 // Extend the LValue path with the member pointer's path.
1943 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1944 MemPtr.Path.size() + IncludeMember);
1945
1946 // Walk down to the appropriate base class.
1947 QualType LVType = BO->getLHS()->getType();
1948 if (const PointerType *PT = LVType->getAs<PointerType>())
1949 LVType = PT->getPointeeType();
1950 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1951 assert(RD && "member pointer access on non-class-type expression");
1952 // The first class in the path is that of the lvalue.
1953 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1954 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCall8d59dee2012-05-01 00:38:49 +00001955 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1956 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001957 RD = Base;
1958 }
1959 // Finally cast to the class containing the member.
John McCall8d59dee2012-05-01 00:38:49 +00001960 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1961 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001962 }
1963
1964 // Add the member. Note that we cannot build bound member functions here.
1965 if (IncludeMember) {
John McCall8d59dee2012-05-01 00:38:49 +00001966 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
1967 if (!HandleLValueMember(Info, BO, LV, FD))
1968 return 0;
1969 } else if (const IndirectFieldDecl *IFD =
1970 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
1971 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
1972 return 0;
1973 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00001974 llvm_unreachable("can't construct reference to bound member function");
John McCall8d59dee2012-05-01 00:38:49 +00001975 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001976 }
1977
1978 return MemPtr.getDecl();
1979}
1980
1981/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1982/// the provided lvalue, which currently refers to the base object.
1983static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1984 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001985 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001986 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001987 return false;
1988
Richard Smithb4e85ed2012-01-06 16:39:00 +00001989 QualType TargetQT = E->getType();
1990 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1991 TargetQT = PT->getPointeeType();
1992
1993 // Check this cast lands within the final derived-to-base subobject path.
1994 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001995 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00001996 << D.MostDerivedType << TargetQT;
1997 return false;
1998 }
1999
Richard Smithe24f5fc2011-11-17 22:56:20 +00002000 // Check the type of the final cast. We don't need to check the path,
2001 // since a cast can only be formed if the path is unique.
2002 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002003 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2004 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002005 if (NewEntriesSize == D.MostDerivedPathLength)
2006 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2007 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002008 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002009 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002010 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002011 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002012 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002013 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002014
2015 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002016 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002017}
2018
Mike Stumpc4c90452009-10-27 22:09:17 +00002019namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002020enum EvalStmtResult {
2021 /// Evaluation failed.
2022 ESR_Failed,
2023 /// Hit a 'return' statement.
2024 ESR_Returned,
2025 /// Evaluation succeeded.
2026 ESR_Succeeded
2027};
2028}
2029
2030// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002031static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002032 const Stmt *S) {
2033 switch (S->getStmtClass()) {
2034 default:
2035 return ESR_Failed;
2036
2037 case Stmt::NullStmtClass:
2038 case Stmt::DeclStmtClass:
2039 return ESR_Succeeded;
2040
Richard Smithc1c5f272011-12-13 06:39:58 +00002041 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002042 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002043 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002044 return ESR_Failed;
2045 return ESR_Returned;
2046 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002047
2048 case Stmt::CompoundStmtClass: {
2049 const CompoundStmt *CS = cast<CompoundStmt>(S);
2050 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2051 BE = CS->body_end(); BI != BE; ++BI) {
2052 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2053 if (ESR != ESR_Succeeded)
2054 return ESR;
2055 }
2056 return ESR_Succeeded;
2057 }
2058 }
2059}
2060
Richard Smith61802452011-12-22 02:22:31 +00002061/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2062/// default constructor. If so, we'll fold it whether or not it's marked as
2063/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2064/// so we need special handling.
2065static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002066 const CXXConstructorDecl *CD,
2067 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002068 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2069 return false;
2070
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002071 // Value-initialization does not call a trivial default constructor, so such a
2072 // call is a core constant expression whether or not the constructor is
2073 // constexpr.
2074 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002075 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002076 // FIXME: If DiagDecl is an implicitly-declared special member function,
2077 // we should be much more explicit about why it's not constexpr.
2078 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2079 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2080 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002081 } else {
2082 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2083 }
2084 }
2085 return true;
2086}
2087
Richard Smithc1c5f272011-12-13 06:39:58 +00002088/// CheckConstexprFunction - Check that a function can be called in a constant
2089/// expression.
2090static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2091 const FunctionDecl *Declaration,
2092 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002093 // Potential constant expressions can contain calls to declared, but not yet
2094 // defined, constexpr functions.
2095 if (Info.CheckingPotentialConstantExpression && !Definition &&
2096 Declaration->isConstexpr())
2097 return false;
2098
Richard Smithc1c5f272011-12-13 06:39:58 +00002099 // Can we evaluate this function call?
2100 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2101 return true;
2102
2103 if (Info.getLangOpts().CPlusPlus0x) {
2104 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002105 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2106 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002107 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2108 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2109 << DiagDecl;
2110 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2111 } else {
2112 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2113 }
2114 return false;
2115}
2116
Richard Smith180f4792011-11-10 06:34:14 +00002117namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002118typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002119}
2120
2121/// EvaluateArgs - Evaluate the arguments to a function call.
2122static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2123 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002124 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002125 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002126 I != E; ++I) {
2127 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2128 // If we're checking for a potential constant expression, evaluate all
2129 // initializers even if some of them fail.
2130 if (!Info.keepEvaluatingAfterFailure())
2131 return false;
2132 Success = false;
2133 }
2134 }
2135 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002136}
2137
Richard Smithd0dccea2011-10-28 22:34:42 +00002138/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002139static bool HandleFunctionCall(SourceLocation CallLoc,
2140 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002141 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002142 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002143 ArgVector ArgValues(Args.size());
2144 if (!EvaluateArgs(Args, ArgValues, Info))
2145 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002146
Richard Smith745f5142012-01-27 01:14:48 +00002147 if (!Info.CheckCallLimit(CallLoc))
2148 return false;
2149
2150 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002151 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2152}
2153
Richard Smith180f4792011-11-10 06:34:14 +00002154/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002155static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002156 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002157 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002158 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002159 ArgVector ArgValues(Args.size());
2160 if (!EvaluateArgs(Args, ArgValues, Info))
2161 return false;
2162
Richard Smith745f5142012-01-27 01:14:48 +00002163 if (!Info.CheckCallLimit(CallLoc))
2164 return false;
2165
Richard Smith86c3ae42012-02-13 03:54:03 +00002166 const CXXRecordDecl *RD = Definition->getParent();
2167 if (RD->getNumVBases()) {
2168 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2169 return false;
2170 }
2171
Richard Smith745f5142012-01-27 01:14:48 +00002172 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002173
2174 // If it's a delegating constructor, just delegate.
2175 if (Definition->isDelegatingConstructor()) {
2176 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002177 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002178 }
2179
Richard Smith610a60c2012-01-10 04:32:03 +00002180 // For a trivial copy or move constructor, perform an APValue copy. This is
2181 // essential for unions, where the operations performed by the constructor
2182 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002183 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002184 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2185 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002186 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002187 RHS.setFrom(Info.Ctx, ArgValues[0]);
2188 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2189 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002190 }
2191
2192 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002193 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002194 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2195 std::distance(RD->field_begin(), RD->field_end()));
2196
John McCall8d59dee2012-05-01 00:38:49 +00002197 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00002198 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2199
Richard Smith745f5142012-01-27 01:14:48 +00002200 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002201 unsigned BasesSeen = 0;
2202#ifndef NDEBUG
2203 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2204#endif
2205 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2206 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002207 LValue Subobject = This;
2208 APValue *Value = &Result;
2209
2210 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002211 if ((*I)->isBaseInitializer()) {
2212 QualType BaseType((*I)->getBaseClass(), 0);
2213#ifndef NDEBUG
2214 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002215 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002216 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2217 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2218 "base class initializers not in expected order");
2219 ++BaseIt;
2220#endif
John McCall8d59dee2012-05-01 00:38:49 +00002221 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2222 BaseType->getAsCXXRecordDecl(), &Layout))
2223 return false;
Richard Smith745f5142012-01-27 01:14:48 +00002224 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002225 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCall8d59dee2012-05-01 00:38:49 +00002226 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2227 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002228 if (RD->isUnion()) {
2229 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002230 Value = &Result.getUnionValue();
2231 } else {
2232 Value = &Result.getStructField(FD->getFieldIndex());
2233 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002234 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002235 // Walk the indirect field decl's chain to find the object to initialize,
2236 // and make sure we've initialized every step along it.
2237 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2238 CE = IFD->chain_end();
2239 C != CE; ++C) {
2240 FieldDecl *FD = cast<FieldDecl>(*C);
2241 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2242 // Switch the union field if it differs. This happens if we had
2243 // preceding zero-initialization, and we're now initializing a union
2244 // subobject other than the first.
2245 // FIXME: In this case, the values of the other subobjects are
2246 // specified, since zero-initialization sets all padding bits to zero.
2247 if (Value->isUninit() ||
2248 (Value->isUnion() && Value->getUnionField() != FD)) {
2249 if (CD->isUnion())
2250 *Value = APValue(FD);
2251 else
2252 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2253 std::distance(CD->field_begin(), CD->field_end()));
2254 }
John McCall8d59dee2012-05-01 00:38:49 +00002255 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2256 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002257 if (CD->isUnion())
2258 Value = &Value->getUnionValue();
2259 else
2260 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002261 }
Richard Smith180f4792011-11-10 06:34:14 +00002262 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002263 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002264 }
Richard Smith745f5142012-01-27 01:14:48 +00002265
Richard Smith83587db2012-02-15 02:18:13 +00002266 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2267 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002268 ? CCEK_Constant : CCEK_MemberInit)) {
2269 // If we're checking for a potential constant expression, evaluate all
2270 // initializers even if some of them fail.
2271 if (!Info.keepEvaluatingAfterFailure())
2272 return false;
2273 Success = false;
2274 }
Richard Smith180f4792011-11-10 06:34:14 +00002275 }
2276
Richard Smith745f5142012-01-27 01:14:48 +00002277 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002278}
2279
Eli Friedman4efaa272008-11-12 09:44:48 +00002280//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002281// Generic Evaluation
2282//===----------------------------------------------------------------------===//
2283namespace {
2284
Richard Smithf48fdb02011-12-09 22:58:01 +00002285// FIXME: RetTy is always bool. Remove it.
2286template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002287class ExprEvaluatorBase
2288 : public ConstStmtVisitor<Derived, RetTy> {
2289private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002290 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002291 return static_cast<Derived*>(this)->Success(V, E);
2292 }
Richard Smith51201882011-12-30 21:15:51 +00002293 RetTy DerivedZeroInitialization(const Expr *E) {
2294 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002295 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002296
Richard Smith74e1ad92012-02-16 02:46:34 +00002297 // Check whether a conditional operator with a non-constant condition is a
2298 // potential constant expression. If neither arm is a potential constant
2299 // expression, then the conditional operator is not either.
2300 template<typename ConditionalOperator>
2301 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2302 assert(Info.CheckingPotentialConstantExpression);
2303
2304 // Speculatively evaluate both arms.
2305 {
2306 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2307 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2308
2309 StmtVisitorTy::Visit(E->getFalseExpr());
2310 if (Diag.empty())
2311 return;
2312
2313 Diag.clear();
2314 StmtVisitorTy::Visit(E->getTrueExpr());
2315 if (Diag.empty())
2316 return;
2317 }
2318
2319 Error(E, diag::note_constexpr_conditional_never_const);
2320 }
2321
2322
2323 template<typename ConditionalOperator>
2324 bool HandleConditionalOperator(const ConditionalOperator *E) {
2325 bool BoolResult;
2326 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2327 if (Info.CheckingPotentialConstantExpression)
2328 CheckPotentialConstantConditional(E);
2329 return false;
2330 }
2331
2332 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2333 return StmtVisitorTy::Visit(EvalExpr);
2334 }
2335
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002336protected:
2337 EvalInfo &Info;
2338 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2339 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2340
Richard Smithdd1f29b2011-12-12 09:28:41 +00002341 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002342 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002343 }
2344
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00002345 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2346
2347public:
2348 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2349
2350 EvalInfo &getEvalInfo() { return Info; }
2351
Richard Smithf48fdb02011-12-09 22:58:01 +00002352 /// Report an evaluation error. This should only be called when an error is
2353 /// first discovered. When propagating an error, just return false.
2354 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002355 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002356 return false;
2357 }
2358 bool Error(const Expr *E) {
2359 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2360 }
2361
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002362 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002363 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002364 }
2365 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002366 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002367 }
2368
2369 RetTy VisitParenExpr(const ParenExpr *E)
2370 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2371 RetTy VisitUnaryExtension(const UnaryOperator *E)
2372 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2373 RetTy VisitUnaryPlus(const UnaryOperator *E)
2374 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2375 RetTy VisitChooseExpr(const ChooseExpr *E)
2376 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2377 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2378 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002379 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2380 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002381 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2382 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002383 // We cannot create any objects for which cleanups are required, so there is
2384 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2385 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2386 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002387
Richard Smithc216a012011-12-12 12:46:16 +00002388 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2389 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2390 return static_cast<Derived*>(this)->VisitCastExpr(E);
2391 }
2392 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2393 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2394 return static_cast<Derived*>(this)->VisitCastExpr(E);
2395 }
2396
Richard Smithe24f5fc2011-11-17 22:56:20 +00002397 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2398 switch (E->getOpcode()) {
2399 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002400 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002401
2402 case BO_Comma:
2403 VisitIgnoredValue(E->getLHS());
2404 return StmtVisitorTy::Visit(E->getRHS());
2405
2406 case BO_PtrMemD:
2407 case BO_PtrMemI: {
2408 LValue Obj;
2409 if (!HandleMemberPointerAccess(Info, E, Obj))
2410 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002411 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002412 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002413 return false;
2414 return DerivedSuccess(Result, E);
2415 }
2416 }
2417 }
2418
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002419 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002420 // Evaluate and cache the common expression. We treat it as a temporary,
2421 // even though it's not quite the same thing.
2422 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2423 Info, E->getCommon()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002424 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002425
Richard Smith74e1ad92012-02-16 02:46:34 +00002426 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002427 }
2428
2429 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002430 bool IsBcpCall = false;
2431 // If the condition (ignoring parens) is a __builtin_constant_p call,
2432 // the result is a constant expression if it can be folded without
2433 // side-effects. This is an important GNU extension. See GCC PR38377
2434 // for discussion.
2435 if (const CallExpr *CallCE =
2436 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2437 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2438 IsBcpCall = true;
2439
2440 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2441 // constant expression; we can't check whether it's potentially foldable.
2442 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2443 return false;
2444
2445 FoldConstant Fold(Info);
2446
Richard Smith74e1ad92012-02-16 02:46:34 +00002447 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002448 return false;
2449
2450 if (IsBcpCall)
2451 Fold.Fold(Info);
2452
2453 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002454 }
2455
2456 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002457 APValue &Value = Info.CurrentCall->Temporaries[E];
2458 if (Value.isUninit()) {
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002459 const Expr *Source = E->getSourceExpr();
2460 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002461 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002462 if (Source == E) { // sanity checking.
2463 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002464 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002465 }
2466 return StmtVisitorTy::Visit(Source);
2467 }
Richard Smithe92b1f42012-06-26 08:12:11 +00002468 return DerivedSuccess(Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002469 }
Richard Smithf10d9172011-10-11 21:43:33 +00002470
Richard Smithd0dccea2011-10-28 22:34:42 +00002471 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002472 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002473 QualType CalleeType = Callee->getType();
2474
Richard Smithd0dccea2011-10-28 22:34:42 +00002475 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002476 LValue *This = 0, ThisVal;
2477 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002478 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002479
Richard Smith59efe262011-11-11 04:05:33 +00002480 // Extract function decl and 'this' pointer from the callee.
2481 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002482 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002483 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2484 // Explicit bound member calls, such as x.f() or p->g();
2485 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002486 return false;
2487 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002488 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002489 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002490 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2491 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002492 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2493 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002494 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002495 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002496 return Error(Callee);
2497
2498 FD = dyn_cast<FunctionDecl>(Member);
2499 if (!FD)
2500 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002501 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002502 LValue Call;
2503 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002504 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002505
Richard Smithb4e85ed2012-01-06 16:39:00 +00002506 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002507 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002508 FD = dyn_cast_or_null<FunctionDecl>(
2509 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002510 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002511 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002512
2513 // Overloaded operator calls to member functions are represented as normal
2514 // calls with '*this' as the first argument.
2515 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2516 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002517 // FIXME: When selecting an implicit conversion for an overloaded
2518 // operator delete, we sometimes try to evaluate calls to conversion
2519 // operators without a 'this' parameter!
2520 if (Args.empty())
2521 return Error(E);
2522
Richard Smith59efe262011-11-11 04:05:33 +00002523 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2524 return false;
2525 This = &ThisVal;
2526 Args = Args.slice(1);
2527 }
2528
2529 // Don't call function pointers which have been cast to some other type.
2530 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002531 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002532 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002533 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002534
Richard Smithb04035a2012-02-01 02:39:43 +00002535 if (This && !This->checkSubobject(Info, E, CSK_This))
2536 return false;
2537
Richard Smith86c3ae42012-02-13 03:54:03 +00002538 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2539 // calls to such functions in constant expressions.
2540 if (This && !HasQualifier &&
2541 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2542 return Error(E, diag::note_constexpr_virtual_call);
2543
Richard Smithc1c5f272011-12-13 06:39:58 +00002544 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002545 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002546 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002547
Richard Smithc1c5f272011-12-13 06:39:58 +00002548 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002549 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2550 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002551 return false;
2552
Richard Smith83587db2012-02-15 02:18:13 +00002553 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002554 }
2555
Richard Smithc49bd112011-10-28 17:51:58 +00002556 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2557 return StmtVisitorTy::Visit(E->getInitializer());
2558 }
Richard Smithf10d9172011-10-11 21:43:33 +00002559 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002560 if (E->getNumInits() == 0)
2561 return DerivedZeroInitialization(E);
2562 if (E->getNumInits() == 1)
2563 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002564 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002565 }
2566 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002567 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002568 }
2569 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002570 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002571 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002572 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002573 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002574 }
Richard Smithf10d9172011-10-11 21:43:33 +00002575
Richard Smith180f4792011-11-10 06:34:14 +00002576 /// A member expression where the object is a prvalue is itself a prvalue.
2577 RetTy VisitMemberExpr(const MemberExpr *E) {
2578 assert(!E->isArrow() && "missing call to bound member function?");
2579
Richard Smith1aa0be82012-03-03 22:46:17 +00002580 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002581 if (!Evaluate(Val, Info, E->getBase()))
2582 return false;
2583
2584 QualType BaseTy = E->getBase()->getType();
2585
2586 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002587 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002588 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek890f0f12012-08-23 20:46:57 +00002589 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smith180f4792011-11-10 06:34:14 +00002590 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2591
Richard Smithb4e85ed2012-01-06 16:39:00 +00002592 SubobjectDesignator Designator(BaseTy);
2593 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002594
Richard Smithf48fdb02011-12-09 22:58:01 +00002595 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002596 DerivedSuccess(Val, E);
2597 }
2598
Richard Smithc49bd112011-10-28 17:51:58 +00002599 RetTy VisitCastExpr(const CastExpr *E) {
2600 switch (E->getCastKind()) {
2601 default:
2602 break;
2603
David Chisnall7a7ee302012-01-16 17:27:18 +00002604 case CK_AtomicToNonAtomic:
2605 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002606 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002607 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002608 return StmtVisitorTy::Visit(E->getSubExpr());
2609
2610 case CK_LValueToRValue: {
2611 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002612 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2613 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002614 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002615 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2616 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2617 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002618 return false;
2619 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002620 }
2621 }
2622
Richard Smithf48fdb02011-12-09 22:58:01 +00002623 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002624 }
2625
Richard Smith8327fad2011-10-24 18:44:57 +00002626 /// Visit a value which is evaluated, but whose value is ignored.
2627 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002628 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002629 if (!Evaluate(Scratch, Info, E))
2630 Info.EvalStatus.HasSideEffects = true;
2631 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002632};
2633
2634}
2635
2636//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002637// Common base class for lvalue and temporary evaluation.
2638//===----------------------------------------------------------------------===//
2639namespace {
2640template<class Derived>
2641class LValueExprEvaluatorBase
2642 : public ExprEvaluatorBase<Derived, bool> {
2643protected:
2644 LValue &Result;
2645 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2646 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2647
2648 bool Success(APValue::LValueBase B) {
2649 Result.set(B);
2650 return true;
2651 }
2652
2653public:
2654 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2655 ExprEvaluatorBaseTy(Info), Result(Result) {}
2656
Richard Smith1aa0be82012-03-03 22:46:17 +00002657 bool Success(const APValue &V, const Expr *E) {
2658 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002659 return true;
2660 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002661
Richard Smithe24f5fc2011-11-17 22:56:20 +00002662 bool VisitMemberExpr(const MemberExpr *E) {
2663 // Handle non-static data members.
2664 QualType BaseTy;
2665 if (E->isArrow()) {
2666 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2667 return false;
Ted Kremenek890f0f12012-08-23 20:46:57 +00002668 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002669 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002670 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002671 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2672 return false;
2673 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002674 } else {
2675 if (!this->Visit(E->getBase()))
2676 return false;
2677 BaseTy = E->getBase()->getType();
2678 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002679
Richard Smithd9b02e72012-01-25 22:15:11 +00002680 const ValueDecl *MD = E->getMemberDecl();
2681 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2682 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2683 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2684 (void)BaseTy;
John McCall8d59dee2012-05-01 00:38:49 +00002685 if (!HandleLValueMember(this->Info, E, Result, FD))
2686 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002687 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCall8d59dee2012-05-01 00:38:49 +00002688 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2689 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002690 } else
2691 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002692
Richard Smithd9b02e72012-01-25 22:15:11 +00002693 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002694 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002695 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002696 RefValue))
2697 return false;
2698 return Success(RefValue, E);
2699 }
2700 return true;
2701 }
2702
2703 bool VisitBinaryOperator(const BinaryOperator *E) {
2704 switch (E->getOpcode()) {
2705 default:
2706 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2707
2708 case BO_PtrMemD:
2709 case BO_PtrMemI:
2710 return HandleMemberPointerAccess(this->Info, E, Result);
2711 }
2712 }
2713
2714 bool VisitCastExpr(const CastExpr *E) {
2715 switch (E->getCastKind()) {
2716 default:
2717 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2718
2719 case CK_DerivedToBase:
2720 case CK_UncheckedDerivedToBase: {
2721 if (!this->Visit(E->getSubExpr()))
2722 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002723
2724 // Now figure out the necessary offset to add to the base LV to get from
2725 // the derived class to the base class.
2726 QualType Type = E->getSubExpr()->getType();
2727
2728 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2729 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002730 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002731 *PathI))
2732 return false;
2733 Type = (*PathI)->getType();
2734 }
2735
2736 return true;
2737 }
2738 }
2739 }
2740};
2741}
2742
2743//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002744// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002745//
2746// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2747// function designators (in C), decl references to void objects (in C), and
2748// temporaries (if building with -Wno-address-of-temporary).
2749//
2750// LValue evaluation produces values comprising a base expression of one of the
2751// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002752// - Declarations
2753// * VarDecl
2754// * FunctionDecl
2755// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002756// * CompoundLiteralExpr in C
2757// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002758// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002759// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002760// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002761// * ObjCEncodeExpr
2762// * AddrLabelExpr
2763// * BlockExpr
2764// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002765// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002766// * Any Expr, with a CallIndex indicating the function in which the temporary
2767// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002768// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002769//===----------------------------------------------------------------------===//
2770namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002771class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002772 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002773public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002774 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2775 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002776
Richard Smithc49bd112011-10-28 17:51:58 +00002777 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2778
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002779 bool VisitDeclRefExpr(const DeclRefExpr *E);
2780 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002781 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002782 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2783 bool VisitMemberExpr(const MemberExpr *E);
2784 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2785 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002786 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichete275a182012-04-16 04:08:35 +00002787 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002788 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2789 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002790 bool VisitUnaryReal(const UnaryOperator *E);
2791 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002792
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002793 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002794 switch (E->getCastKind()) {
2795 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002796 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002797
Eli Friedmandb924222011-10-11 00:13:24 +00002798 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002799 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002800 if (!Visit(E->getSubExpr()))
2801 return false;
2802 Result.Designator.setInvalid();
2803 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002804
Richard Smithe24f5fc2011-11-17 22:56:20 +00002805 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002806 if (!Visit(E->getSubExpr()))
2807 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002808 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002809 }
2810 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002811};
2812} // end anonymous namespace
2813
Richard Smithc49bd112011-10-28 17:51:58 +00002814/// Evaluate an expression as an lvalue. This can be legitimately called on
2815/// expressions which are not glvalues, in a few cases:
2816/// * function designators in C,
2817/// * "extern void" objects,
2818/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002819static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002820 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2821 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2822 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002823 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002824}
2825
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002826bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002827 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2828 return Success(FD);
2829 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002830 return VisitVarDecl(E, VD);
2831 return Error(E);
2832}
Richard Smith436c8892011-10-24 23:14:33 +00002833
Richard Smithc49bd112011-10-28 17:51:58 +00002834bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Hans Wennborgae7a66f2012-08-29 08:44:49 +00002835 if (VD->isThreadSpecified())
Hans Wennborg29f431b2012-08-29 09:17:34 +00002836 return Error(E);
Richard Smith177dce72011-11-01 16:57:24 +00002837 if (!VD->getType()->isReferenceType()) {
2838 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002839 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002840 return true;
2841 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002842 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002843 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002844
Richard Smith1aa0be82012-03-03 22:46:17 +00002845 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002846 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2847 return false;
2848 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002849}
2850
Richard Smithbd552ef2011-10-31 05:52:43 +00002851bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2852 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002853 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002854 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002855 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2856
Richard Smith83587db2012-02-15 02:18:13 +00002857 Result.set(E, Info.CurrentCall->Index);
2858 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2859 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002860 }
2861
2862 // Materialization of an lvalue temporary occurs when we need to force a copy
2863 // (for instance, if it's a bitfield).
2864 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2865 if (!Visit(E->GetTemporaryExpr()))
2866 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002867 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002868 Info.CurrentCall->Temporaries[E]))
2869 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002870 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002871 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002872}
2873
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002874bool
2875LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002876 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2877 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2878 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002879 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002880}
2881
Richard Smith47d21452011-12-27 12:18:28 +00002882bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2883 if (E->isTypeOperand())
2884 return Success(E);
2885 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
Richard Smith0d729102012-08-13 20:08:14 +00002886 // FIXME: The standard says "a typeid expression whose operand is of a
2887 // polymorphic class type" is not a constant expression, but it probably
2888 // means "a typeid expression whose operand is potentially evaluated".
Richard Smith47d21452011-12-27 12:18:28 +00002889 if (RD && RD->isPolymorphic()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002890 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith47d21452011-12-27 12:18:28 +00002891 << E->getExprOperand()->getType()
2892 << E->getExprOperand()->getSourceRange();
2893 return false;
2894 }
2895 return Success(E);
2896}
2897
Francois Pichete275a182012-04-16 04:08:35 +00002898bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2899 return Success(E);
2900}
2901
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002902bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002903 // Handle static data members.
2904 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2905 VisitIgnoredValue(E->getBase());
2906 return VisitVarDecl(E, VD);
2907 }
2908
Richard Smithd0dccea2011-10-28 22:34:42 +00002909 // Handle static member functions.
2910 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2911 if (MD->isStatic()) {
2912 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002913 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002914 }
2915 }
2916
Richard Smith180f4792011-11-10 06:34:14 +00002917 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002918 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002919}
2920
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002921bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002922 // FIXME: Deal with vectors as array subscript bases.
2923 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002924 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002925
Anders Carlsson3068d112008-11-16 19:01:22 +00002926 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002927 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002928
Anders Carlsson3068d112008-11-16 19:01:22 +00002929 APSInt Index;
2930 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002931 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002932 int64_t IndexValue
2933 = Index.isSigned() ? Index.getSExtValue()
2934 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002935
Richard Smithb4e85ed2012-01-06 16:39:00 +00002936 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002937}
Eli Friedman4efaa272008-11-12 09:44:48 +00002938
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002939bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002940 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002941}
2942
Richard Smith86024012012-02-18 22:04:06 +00002943bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2944 if (!Visit(E->getSubExpr()))
2945 return false;
2946 // __real is a no-op on scalar lvalues.
2947 if (E->getSubExpr()->getType()->isAnyComplexType())
2948 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
2949 return true;
2950}
2951
2952bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
2953 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
2954 "lvalue __imag__ on scalar?");
2955 if (!Visit(E->getSubExpr()))
2956 return false;
2957 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
2958 return true;
2959}
2960
Eli Friedman4efaa272008-11-12 09:44:48 +00002961//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002962// Pointer Evaluation
2963//===----------------------------------------------------------------------===//
2964
Anders Carlssonc754aa62008-07-08 05:13:58 +00002965namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002966class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002967 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002968 LValue &Result;
2969
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002970 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002971 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002972 return true;
2973 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002974public:
Mike Stump1eb44332009-09-09 15:08:12 +00002975
John McCallefdb83e2010-05-07 21:00:08 +00002976 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002977 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002978
Richard Smith1aa0be82012-03-03 22:46:17 +00002979 bool Success(const APValue &V, const Expr *E) {
2980 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002981 return true;
2982 }
Richard Smith51201882011-12-30 21:15:51 +00002983 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002984 return Success((Expr*)0);
2985 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002986
John McCallefdb83e2010-05-07 21:00:08 +00002987 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002988 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002989 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002990 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002991 { return Success(E); }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002992 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002993 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002994 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002995 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002996 bool VisitCallExpr(const CallExpr *E);
2997 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002998 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002999 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003000 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003001 }
Richard Smith180f4792011-11-10 06:34:14 +00003002 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3003 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003004 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003005 Result = *Info.CurrentCall->This;
3006 return true;
3007 }
John McCall56ca35d2011-02-17 10:25:35 +00003008
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003009 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003010};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003011} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003012
John McCallefdb83e2010-05-07 21:00:08 +00003013static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003014 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003015 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003016}
3017
John McCallefdb83e2010-05-07 21:00:08 +00003018bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003019 if (E->getOpcode() != BO_Add &&
3020 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003021 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003022
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003023 const Expr *PExp = E->getLHS();
3024 const Expr *IExp = E->getRHS();
3025 if (IExp->getType()->isPointerType())
3026 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003027
Richard Smith745f5142012-01-27 01:14:48 +00003028 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3029 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003030 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003031
John McCallefdb83e2010-05-07 21:00:08 +00003032 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003033 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003034 return false;
3035 int64_t AdditionalOffset
3036 = Offset.isSigned() ? Offset.getSExtValue()
3037 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003038 if (E->getOpcode() == BO_Sub)
3039 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003040
Ted Kremenek890f0f12012-08-23 20:46:57 +00003041 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003042 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3043 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003044}
Eli Friedman4efaa272008-11-12 09:44:48 +00003045
John McCallefdb83e2010-05-07 21:00:08 +00003046bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3047 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003048}
Mike Stump1eb44332009-09-09 15:08:12 +00003049
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003050bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3051 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003052
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003053 switch (E->getCastKind()) {
3054 default:
3055 break;
3056
John McCall2de56d12010-08-25 11:45:40 +00003057 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003058 case CK_CPointerToObjCPointerCast:
3059 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003060 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003061 if (!Visit(SubExpr))
3062 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003063 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3064 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3065 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003066 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003067 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003068 if (SubExpr->getType()->isVoidPointerType())
3069 CCEDiag(E, diag::note_constexpr_invalid_cast)
3070 << 3 << SubExpr->getType();
3071 else
3072 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3073 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003074 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003075
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003076 case CK_DerivedToBase:
3077 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003078 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003079 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003080 if (!Result.Base && Result.Offset.isZero())
3081 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003082
Richard Smith180f4792011-11-10 06:34:14 +00003083 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003084 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003085 QualType Type =
3086 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003087
Richard Smith180f4792011-11-10 06:34:14 +00003088 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003089 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003090 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3091 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003092 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003093 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003094 }
3095
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003096 return true;
3097 }
3098
Richard Smithe24f5fc2011-11-17 22:56:20 +00003099 case CK_BaseToDerived:
3100 if (!Visit(E->getSubExpr()))
3101 return false;
3102 if (!Result.Base && Result.Offset.isZero())
3103 return true;
3104 return HandleBaseToDerivedCast(Info, E, Result);
3105
Richard Smith47a1eed2011-10-29 20:57:55 +00003106 case CK_NullToPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003107 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003108 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003109
John McCall2de56d12010-08-25 11:45:40 +00003110 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003111 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3112
Richard Smith1aa0be82012-03-03 22:46:17 +00003113 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003114 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003115 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003116
John McCallefdb83e2010-05-07 21:00:08 +00003117 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003118 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3119 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003120 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003121 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003122 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003123 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003124 return true;
3125 } else {
3126 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003127 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003128 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003129 }
3130 }
John McCall2de56d12010-08-25 11:45:40 +00003131 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003132 if (SubExpr->isGLValue()) {
3133 if (!EvaluateLValue(SubExpr, Result, Info))
3134 return false;
3135 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003136 Result.set(SubExpr, Info.CurrentCall->Index);
3137 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3138 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003139 return false;
3140 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003141 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003142 if (const ConstantArrayType *CAT
3143 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3144 Result.addArray(Info, E, CAT);
3145 else
3146 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003147 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003148
John McCall2de56d12010-08-25 11:45:40 +00003149 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003150 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003151 }
3152
Richard Smithc49bd112011-10-28 17:51:58 +00003153 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003154}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003155
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003156bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003157 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003158 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003159
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003160 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003161}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003162
3163//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003164// Member Pointer Evaluation
3165//===----------------------------------------------------------------------===//
3166
3167namespace {
3168class MemberPointerExprEvaluator
3169 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3170 MemberPtr &Result;
3171
3172 bool Success(const ValueDecl *D) {
3173 Result = MemberPtr(D);
3174 return true;
3175 }
3176public:
3177
3178 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3179 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3180
Richard Smith1aa0be82012-03-03 22:46:17 +00003181 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003182 Result.setFrom(V);
3183 return true;
3184 }
Richard Smith51201882011-12-30 21:15:51 +00003185 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003186 return Success((const ValueDecl*)0);
3187 }
3188
3189 bool VisitCastExpr(const CastExpr *E);
3190 bool VisitUnaryAddrOf(const UnaryOperator *E);
3191};
3192} // end anonymous namespace
3193
3194static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3195 EvalInfo &Info) {
3196 assert(E->isRValue() && E->getType()->isMemberPointerType());
3197 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3198}
3199
3200bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3201 switch (E->getCastKind()) {
3202 default:
3203 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3204
3205 case CK_NullToMemberPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003206 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003207 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003208
3209 case CK_BaseToDerivedMemberPointer: {
3210 if (!Visit(E->getSubExpr()))
3211 return false;
3212 if (E->path_empty())
3213 return true;
3214 // Base-to-derived member pointer casts store the path in derived-to-base
3215 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3216 // the wrong end of the derived->base arc, so stagger the path by one class.
3217 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3218 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3219 PathI != PathE; ++PathI) {
3220 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3221 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3222 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003223 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003224 }
3225 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3226 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003227 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003228 return true;
3229 }
3230
3231 case CK_DerivedToBaseMemberPointer:
3232 if (!Visit(E->getSubExpr()))
3233 return false;
3234 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3235 PathE = E->path_end(); PathI != PathE; ++PathI) {
3236 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3237 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3238 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003239 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003240 }
3241 return true;
3242 }
3243}
3244
3245bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3246 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3247 // member can be formed.
3248 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3249}
3250
3251//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003252// Record Evaluation
3253//===----------------------------------------------------------------------===//
3254
3255namespace {
3256 class RecordExprEvaluator
3257 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3258 const LValue &This;
3259 APValue &Result;
3260 public:
3261
3262 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3263 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3264
Richard Smith1aa0be82012-03-03 22:46:17 +00003265 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003266 Result = V;
3267 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003268 }
Richard Smith51201882011-12-30 21:15:51 +00003269 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003270
Richard Smith59efe262011-11-11 04:05:33 +00003271 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003272 bool VisitInitListExpr(const InitListExpr *E);
3273 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3274 };
3275}
3276
Richard Smith51201882011-12-30 21:15:51 +00003277/// Perform zero-initialization on an object of non-union class type.
3278/// C++11 [dcl.init]p5:
3279/// To zero-initialize an object or reference of type T means:
3280/// [...]
3281/// -- if T is a (possibly cv-qualified) non-union class type,
3282/// each non-static data member and each base-class subobject is
3283/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003284static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3285 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003286 const LValue &This, APValue &Result) {
3287 assert(!RD->isUnion() && "Expected non-union class type");
3288 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3289 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3290 std::distance(RD->field_begin(), RD->field_end()));
3291
John McCall8d59dee2012-05-01 00:38:49 +00003292 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003293 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3294
3295 if (CD) {
3296 unsigned Index = 0;
3297 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003298 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003299 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3300 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003301 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3302 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003303 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003304 Result.getStructBase(Index)))
3305 return false;
3306 }
3307 }
3308
Richard Smithb4e85ed2012-01-06 16:39:00 +00003309 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3310 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003311 // -- if T is a reference type, no initialization is performed.
David Blaikie262bc182012-04-30 02:36:29 +00003312 if (I->getType()->isReferenceType())
Richard Smith51201882011-12-30 21:15:51 +00003313 continue;
3314
3315 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003316 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003317 return false;
Richard Smith51201882011-12-30 21:15:51 +00003318
David Blaikie262bc182012-04-30 02:36:29 +00003319 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003320 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003321 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003322 return false;
3323 }
3324
3325 return true;
3326}
3327
3328bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3329 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003330 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003331 if (RD->isUnion()) {
3332 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3333 // object's first non-static named data member is zero-initialized
3334 RecordDecl::field_iterator I = RD->field_begin();
3335 if (I == RD->field_end()) {
3336 Result = APValue((const FieldDecl*)0);
3337 return true;
3338 }
3339
3340 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003341 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCall8d59dee2012-05-01 00:38:49 +00003342 return false;
David Blaikie581deb32012-06-06 20:45:41 +00003343 Result = APValue(*I);
David Blaikie262bc182012-04-30 02:36:29 +00003344 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003345 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003346 }
3347
Richard Smithce582fe2012-02-17 00:44:16 +00003348 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003349 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003350 return false;
3351 }
3352
Richard Smithb4e85ed2012-01-06 16:39:00 +00003353 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003354}
3355
Richard Smith59efe262011-11-11 04:05:33 +00003356bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3357 switch (E->getCastKind()) {
3358 default:
3359 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3360
3361 case CK_ConstructorConversion:
3362 return Visit(E->getSubExpr());
3363
3364 case CK_DerivedToBase:
3365 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003366 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003367 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003368 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003369 if (!DerivedObject.isStruct())
3370 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003371
3372 // Derived-to-base rvalue conversion: just slice off the derived part.
3373 APValue *Value = &DerivedObject;
3374 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3375 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3376 PathE = E->path_end(); PathI != PathE; ++PathI) {
3377 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3378 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3379 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3380 RD = Base;
3381 }
3382 Result = *Value;
3383 return true;
3384 }
3385 }
3386}
3387
Richard Smith180f4792011-11-10 06:34:14 +00003388bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003389 // Cannot constant-evaluate std::initializer_list inits.
3390 if (E->initializesStdInitializerList())
3391 return false;
3392
Richard Smith180f4792011-11-10 06:34:14 +00003393 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003394 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00003395 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3396
3397 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003398 const FieldDecl *Field = E->getInitializedFieldInUnion();
3399 Result = APValue(Field);
3400 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003401 return true;
Richard Smithec789162012-01-12 18:54:33 +00003402
3403 // If the initializer list for a union does not contain any elements, the
3404 // first element of the union is value-initialized.
3405 ImplicitValueInitExpr VIE(Field->getType());
3406 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3407
Richard Smith180f4792011-11-10 06:34:14 +00003408 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003409 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3410 return false;
Richard Smith83587db2012-02-15 02:18:13 +00003411 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003412 }
3413
3414 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3415 "initializer list for class with base classes");
3416 Result = APValue(APValue::UninitStruct(), 0,
3417 std::distance(RD->field_begin(), RD->field_end()));
3418 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003419 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003420 for (RecordDecl::field_iterator Field = RD->field_begin(),
3421 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3422 // Anonymous bit-fields are not considered members of the class for
3423 // purposes of aggregate initialization.
3424 if (Field->isUnnamedBitfield())
3425 continue;
3426
3427 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003428
Richard Smith745f5142012-01-27 01:14:48 +00003429 bool HaveInit = ElementNo < E->getNumInits();
3430
3431 // FIXME: Diagnostics here should point to the end of the initializer
3432 // list, not the start.
John McCall8d59dee2012-05-01 00:38:49 +00003433 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie581deb32012-06-06 20:45:41 +00003434 Subobject, *Field, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003435 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003436
3437 // Perform an implicit value-initialization for members beyond the end of
3438 // the initializer list.
3439 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3440
Richard Smith83587db2012-02-15 02:18:13 +00003441 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003442 Result.getStructField(Field->getFieldIndex()),
Richard Smith745f5142012-01-27 01:14:48 +00003443 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3444 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003445 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003446 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003447 }
3448 }
3449
Richard Smith745f5142012-01-27 01:14:48 +00003450 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003451}
3452
3453bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3454 const CXXConstructorDecl *FD = E->getConstructor();
John McCall1de9d7d2012-04-26 18:10:01 +00003455 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3456
Richard Smith51201882011-12-30 21:15:51 +00003457 bool ZeroInit = E->requiresZeroInitialization();
3458 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003459 // If we've already performed zero-initialization, we're already done.
3460 if (!Result.isUninit())
3461 return true;
3462
Richard Smith51201882011-12-30 21:15:51 +00003463 if (ZeroInit)
3464 return ZeroInitialization(E);
3465
Richard Smith61802452011-12-22 02:22:31 +00003466 const CXXRecordDecl *RD = FD->getParent();
3467 if (RD->isUnion())
3468 Result = APValue((FieldDecl*)0);
3469 else
3470 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3471 std::distance(RD->field_begin(), RD->field_end()));
3472 return true;
3473 }
3474
Richard Smith180f4792011-11-10 06:34:14 +00003475 const FunctionDecl *Definition = 0;
3476 FD->getBody(Definition);
3477
Richard Smithc1c5f272011-12-13 06:39:58 +00003478 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3479 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003480
Richard Smith610a60c2012-01-10 04:32:03 +00003481 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003482 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003483 if (const MaterializeTemporaryExpr *ME
3484 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3485 return Visit(ME->GetTemporaryExpr());
3486
Richard Smith51201882011-12-30 21:15:51 +00003487 if (ZeroInit && !ZeroInitialization(E))
3488 return false;
3489
Richard Smith180f4792011-11-10 06:34:14 +00003490 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003491 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003492 cast<CXXConstructorDecl>(Definition), Info,
3493 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003494}
3495
3496static bool EvaluateRecord(const Expr *E, const LValue &This,
3497 APValue &Result, EvalInfo &Info) {
3498 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003499 "can't evaluate expression as a record rvalue");
3500 return RecordExprEvaluator(Info, This, Result).Visit(E);
3501}
3502
3503//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003504// Temporary Evaluation
3505//
3506// Temporaries are represented in the AST as rvalues, but generally behave like
3507// lvalues. The full-object of which the temporary is a subobject is implicitly
3508// materialized so that a reference can bind to it.
3509//===----------------------------------------------------------------------===//
3510namespace {
3511class TemporaryExprEvaluator
3512 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3513public:
3514 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3515 LValueExprEvaluatorBaseTy(Info, Result) {}
3516
3517 /// Visit an expression which constructs the value of this temporary.
3518 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003519 Result.set(E, Info.CurrentCall->Index);
3520 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003521 }
3522
3523 bool VisitCastExpr(const CastExpr *E) {
3524 switch (E->getCastKind()) {
3525 default:
3526 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3527
3528 case CK_ConstructorConversion:
3529 return VisitConstructExpr(E->getSubExpr());
3530 }
3531 }
3532 bool VisitInitListExpr(const InitListExpr *E) {
3533 return VisitConstructExpr(E);
3534 }
3535 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3536 return VisitConstructExpr(E);
3537 }
3538 bool VisitCallExpr(const CallExpr *E) {
3539 return VisitConstructExpr(E);
3540 }
3541};
3542} // end anonymous namespace
3543
3544/// Evaluate an expression of record type as a temporary.
3545static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003546 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003547 return TemporaryExprEvaluator(Info, Result).Visit(E);
3548}
3549
3550//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003551// Vector Evaluation
3552//===----------------------------------------------------------------------===//
3553
3554namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003555 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003556 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3557 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003558 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003559
Richard Smith07fc6572011-10-22 21:10:00 +00003560 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3561 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003562
Richard Smith07fc6572011-10-22 21:10:00 +00003563 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3564 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3565 // FIXME: remove this APValue copy.
3566 Result = APValue(V.data(), V.size());
3567 return true;
3568 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003569 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003570 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003571 Result = V;
3572 return true;
3573 }
Richard Smith51201882011-12-30 21:15:51 +00003574 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003575
Richard Smith07fc6572011-10-22 21:10:00 +00003576 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003577 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003578 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003579 bool VisitInitListExpr(const InitListExpr *E);
3580 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003581 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003582 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003583 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003584 };
3585} // end anonymous namespace
3586
3587static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003588 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003589 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003590}
3591
Richard Smith07fc6572011-10-22 21:10:00 +00003592bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3593 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003594 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003595
Richard Smithd62ca372011-12-06 22:44:34 +00003596 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003597 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003598
Eli Friedman46a52322011-03-25 00:43:55 +00003599 switch (E->getCastKind()) {
3600 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003601 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003602 if (SETy->isIntegerType()) {
3603 APSInt IntResult;
3604 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003605 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003606 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003607 } else if (SETy->isRealFloatingType()) {
3608 APFloat F(0.0);
3609 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003610 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003611 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003612 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003613 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003614 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003615
3616 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003617 SmallVector<APValue, 4> Elts(NElts, Val);
3618 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003619 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003620 case CK_BitCast: {
3621 // Evaluate the operand into an APInt we can extract from.
3622 llvm::APInt SValInt;
3623 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3624 return false;
3625 // Extract the elements
3626 QualType EltTy = VTy->getElementType();
3627 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3628 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3629 SmallVector<APValue, 4> Elts;
3630 if (EltTy->isRealFloatingType()) {
3631 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3632 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3633 unsigned FloatEltSize = EltSize;
3634 if (&Sem == &APFloat::x87DoubleExtended)
3635 FloatEltSize = 80;
3636 for (unsigned i = 0; i < NElts; i++) {
3637 llvm::APInt Elt;
3638 if (BigEndian)
3639 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3640 else
3641 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3642 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3643 }
3644 } else if (EltTy->isIntegerType()) {
3645 for (unsigned i = 0; i < NElts; i++) {
3646 llvm::APInt Elt;
3647 if (BigEndian)
3648 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3649 else
3650 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3651 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3652 }
3653 } else {
3654 return Error(E);
3655 }
3656 return Success(Elts, E);
3657 }
Eli Friedman46a52322011-03-25 00:43:55 +00003658 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003659 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003660 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003661}
3662
Richard Smith07fc6572011-10-22 21:10:00 +00003663bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003664VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003665 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003666 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003667 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003668
Nate Begeman59b5da62009-01-18 03:20:47 +00003669 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003670 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003671
Eli Friedman3edd5a92012-01-03 23:24:20 +00003672 // The number of initializers can be less than the number of
3673 // vector elements. For OpenCL, this can be due to nested vector
3674 // initialization. For GCC compatibility, missing trailing elements
3675 // should be initialized with zeroes.
3676 unsigned CountInits = 0, CountElts = 0;
3677 while (CountElts < NumElements) {
3678 // Handle nested vector initialization.
3679 if (CountInits < NumInits
3680 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3681 APValue v;
3682 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3683 return Error(E);
3684 unsigned vlen = v.getVectorLength();
3685 for (unsigned j = 0; j < vlen; j++)
3686 Elements.push_back(v.getVectorElt(j));
3687 CountElts += vlen;
3688 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003689 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003690 if (CountInits < NumInits) {
3691 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003692 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003693 } else // trailing integer zero.
3694 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3695 Elements.push_back(APValue(sInt));
3696 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003697 } else {
3698 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003699 if (CountInits < NumInits) {
3700 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003701 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003702 } else // trailing float zero.
3703 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3704 Elements.push_back(APValue(f));
3705 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003706 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003707 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003708 }
Richard Smith07fc6572011-10-22 21:10:00 +00003709 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003710}
3711
Richard Smith07fc6572011-10-22 21:10:00 +00003712bool
Richard Smith51201882011-12-30 21:15:51 +00003713VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003714 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003715 QualType EltTy = VT->getElementType();
3716 APValue ZeroElement;
3717 if (EltTy->isIntegerType())
3718 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3719 else
3720 ZeroElement =
3721 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3722
Chris Lattner5f9e2722011-07-23 10:55:15 +00003723 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003724 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003725}
3726
Richard Smith07fc6572011-10-22 21:10:00 +00003727bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003728 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003729 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003730}
3731
Nate Begeman59b5da62009-01-18 03:20:47 +00003732//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003733// Array Evaluation
3734//===----------------------------------------------------------------------===//
3735
3736namespace {
3737 class ArrayExprEvaluator
3738 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003739 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003740 APValue &Result;
3741 public:
3742
Richard Smith180f4792011-11-10 06:34:14 +00003743 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3744 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003745
3746 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003747 assert((V.isArray() || V.isLValue()) &&
3748 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003749 Result = V;
3750 return true;
3751 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003752
Richard Smith51201882011-12-30 21:15:51 +00003753 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003754 const ConstantArrayType *CAT =
3755 Info.Ctx.getAsConstantArrayType(E->getType());
3756 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003757 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003758
3759 Result = APValue(APValue::UninitArray(), 0,
3760 CAT->getSize().getZExtValue());
3761 if (!Result.hasArrayFiller()) return true;
3762
Richard Smith51201882011-12-30 21:15:51 +00003763 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003764 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003765 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003766 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003767 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003768 }
3769
Richard Smithcc5d4f62011-11-07 09:22:26 +00003770 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003771 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003772 };
3773} // end anonymous namespace
3774
Richard Smith180f4792011-11-10 06:34:14 +00003775static bool EvaluateArray(const Expr *E, const LValue &This,
3776 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003777 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003778 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003779}
3780
3781bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3782 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3783 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003784 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003785
Richard Smith974c5f92011-12-22 01:07:19 +00003786 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3787 // an appropriately-typed string literal enclosed in braces.
Richard Smithfe587202012-04-15 02:50:59 +00003788 if (E->isStringLiteralInit()) {
Richard Smith974c5f92011-12-22 01:07:19 +00003789 LValue LV;
3790 if (!EvaluateLValue(E->getInit(0), LV, Info))
3791 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003792 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003793 LV.moveInto(Val);
3794 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003795 }
3796
Richard Smith745f5142012-01-27 01:14:48 +00003797 bool Success = true;
3798
Richard Smithde31aa72012-07-07 22:48:24 +00003799 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
3800 "zero-initialized array shouldn't have any initialized elts");
3801 APValue Filler;
3802 if (Result.isArray() && Result.hasArrayFiller())
3803 Filler = Result.getArrayFiller();
3804
Richard Smithcc5d4f62011-11-07 09:22:26 +00003805 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3806 CAT->getSize().getZExtValue());
Richard Smithde31aa72012-07-07 22:48:24 +00003807
3808 // If the array was previously zero-initialized, preserve the
3809 // zero-initialized values.
3810 if (!Filler.isUninit()) {
3811 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
3812 Result.getArrayInitializedElt(I) = Filler;
3813 if (Result.hasArrayFiller())
3814 Result.getArrayFiller() = Filler;
3815 }
3816
Richard Smith180f4792011-11-10 06:34:14 +00003817 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003818 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003819 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003820 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003821 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003822 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3823 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003824 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3825 CAT->getElementType(), 1)) {
3826 if (!Info.keepEvaluatingAfterFailure())
3827 return false;
3828 Success = false;
3829 }
Richard Smith180f4792011-11-10 06:34:14 +00003830 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003831
Richard Smith745f5142012-01-27 01:14:48 +00003832 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003833 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003834 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3835 // but sometimes does:
3836 // struct S { constexpr S() : p(&p) {} void *p; };
3837 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003838 return EvaluateInPlace(Result.getArrayFiller(), Info,
3839 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003840}
3841
Richard Smithe24f5fc2011-11-17 22:56:20 +00003842bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smithde31aa72012-07-07 22:48:24 +00003843 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3844 // but sometimes does:
3845 // struct S { constexpr S() : p(&p) {} void *p; };
3846 // S s[10];
3847 LValue Subobject = This;
3848
3849 APValue *Value = &Result;
3850 bool HadZeroInit = true;
Richard Smitha4334df2012-07-10 22:12:55 +00003851 QualType ElemTy = E->getType();
3852 while (const ConstantArrayType *CAT =
3853 Info.Ctx.getAsConstantArrayType(ElemTy)) {
Richard Smithde31aa72012-07-07 22:48:24 +00003854 Subobject.addArray(Info, E, CAT);
3855 HadZeroInit &= !Value->isUninit();
3856 if (!HadZeroInit)
3857 *Value = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3858 if (!Value->hasArrayFiller())
3859 return true;
Richard Smithde31aa72012-07-07 22:48:24 +00003860 Value = &Value->getArrayFiller();
Richard Smitha4334df2012-07-10 22:12:55 +00003861 ElemTy = CAT->getElementType();
Richard Smithde31aa72012-07-07 22:48:24 +00003862 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00003863
Richard Smitha4334df2012-07-10 22:12:55 +00003864 if (!ElemTy->isRecordType())
3865 return Error(E);
3866
Richard Smithe24f5fc2011-11-17 22:56:20 +00003867 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003868
Richard Smith51201882011-12-30 21:15:51 +00003869 bool ZeroInit = E->requiresZeroInitialization();
3870 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003871 if (HadZeroInit)
3872 return true;
3873
Richard Smith51201882011-12-30 21:15:51 +00003874 if (ZeroInit) {
Richard Smitha4334df2012-07-10 22:12:55 +00003875 ImplicitValueInitExpr VIE(ElemTy);
Richard Smithde31aa72012-07-07 22:48:24 +00003876 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003877 }
3878
Richard Smith61802452011-12-22 02:22:31 +00003879 const CXXRecordDecl *RD = FD->getParent();
3880 if (RD->isUnion())
Richard Smithde31aa72012-07-07 22:48:24 +00003881 *Value = APValue((FieldDecl*)0);
Richard Smith61802452011-12-22 02:22:31 +00003882 else
Richard Smithde31aa72012-07-07 22:48:24 +00003883 *Value =
Richard Smith61802452011-12-22 02:22:31 +00003884 APValue(APValue::UninitStruct(), RD->getNumBases(),
3885 std::distance(RD->field_begin(), RD->field_end()));
3886 return true;
3887 }
3888
Richard Smithe24f5fc2011-11-17 22:56:20 +00003889 const FunctionDecl *Definition = 0;
3890 FD->getBody(Definition);
3891
Richard Smithc1c5f272011-12-13 06:39:58 +00003892 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3893 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003894
Richard Smithec789162012-01-12 18:54:33 +00003895 if (ZeroInit && !HadZeroInit) {
Richard Smitha4334df2012-07-10 22:12:55 +00003896 ImplicitValueInitExpr VIE(ElemTy);
Richard Smithde31aa72012-07-07 22:48:24 +00003897 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003898 return false;
3899 }
3900
Richard Smithe24f5fc2011-11-17 22:56:20 +00003901 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003902 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003903 cast<CXXConstructorDecl>(Definition),
Richard Smithde31aa72012-07-07 22:48:24 +00003904 Info, *Value);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003905}
3906
Richard Smithcc5d4f62011-11-07 09:22:26 +00003907//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003908// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003909//
3910// As a GNU extension, we support casting pointers to sufficiently-wide integer
3911// types and back in constant folding. Integer values are thus represented
3912// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003913//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003914
3915namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003916class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003917 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003918 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003919public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003920 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003921 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003922
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003923 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003924 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003925 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003926 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003927 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003928 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003929 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003930 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003931 return true;
3932 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003933 bool Success(const llvm::APSInt &SI, const Expr *E) {
3934 return Success(SI, E, Result);
3935 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003936
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003937 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003938 assert(E->getType()->isIntegralOrEnumerationType() &&
3939 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003940 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003941 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003942 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003943 Result.getInt().setIsUnsigned(
3944 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003945 return true;
3946 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003947 bool Success(const llvm::APInt &I, const Expr *E) {
3948 return Success(I, E, Result);
3949 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00003950
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003951 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003952 assert(E->getType()->isIntegralOrEnumerationType() &&
3953 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003954 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003955 return true;
3956 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003957 bool Success(uint64_t Value, const Expr *E) {
3958 return Success(Value, E, Result);
3959 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00003960
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003961 bool Success(CharUnits Size, const Expr *E) {
3962 return Success(Size.getQuantity(), E);
3963 }
3964
Richard Smith1aa0be82012-03-03 22:46:17 +00003965 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003966 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003967 Result = V;
3968 return true;
3969 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003970 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003971 }
Mike Stump1eb44332009-09-09 15:08:12 +00003972
Richard Smith51201882011-12-30 21:15:51 +00003973 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003974
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003975 //===--------------------------------------------------------------------===//
3976 // Visitor Methods
3977 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003978
Chris Lattner4c4867e2008-07-12 00:38:25 +00003979 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003980 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003981 }
3982 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003983 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003984 }
Eli Friedman04309752009-11-24 05:28:59 +00003985
3986 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3987 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003988 if (CheckReferencedDecl(E, E->getDecl()))
3989 return true;
3990
3991 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003992 }
3993 bool VisitMemberExpr(const MemberExpr *E) {
3994 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003995 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003996 return true;
3997 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003998
3999 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004000 }
4001
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004002 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004003 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004004 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004005 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004006
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004007 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004008 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004009
Anders Carlsson3068d112008-11-16 19:01:22 +00004010 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004011 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004012 }
Mike Stump1eb44332009-09-09 15:08:12 +00004013
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004014 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4015 return Success(E->getValue(), E);
4016 }
4017
Richard Smithf10d9172011-10-11 21:43:33 +00004018 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004019 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004020 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004021 }
4022
Sebastian Redl64b45f72009-01-05 20:52:13 +00004023 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004024 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004025 }
4026
Francois Pichet6ad6f282010-12-07 00:08:36 +00004027 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4028 return Success(E->getValue(), E);
4029 }
4030
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004031 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4032 return Success(E->getValue(), E);
4033 }
4034
John Wiegley21ff2e52011-04-28 00:16:57 +00004035 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4036 return Success(E->getValue(), E);
4037 }
4038
John Wiegley55262202011-04-25 06:54:41 +00004039 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4040 return Success(E->getValue(), E);
4041 }
4042
Eli Friedman722c7172009-02-28 03:59:05 +00004043 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004044 bool VisitUnaryImag(const UnaryOperator *E);
4045
Sebastian Redl295995c2010-09-10 20:55:47 +00004046 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004047 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004048
Chris Lattnerfcee0012008-07-11 21:24:13 +00004049private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004050 CharUnits GetAlignOfExpr(const Expr *E);
4051 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004052 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004053 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004054 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004055};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004056} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004057
Richard Smithc49bd112011-10-28 17:51:58 +00004058/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4059/// produce either the integer value or a pointer.
4060///
4061/// GCC has a heinous extension which folds casts between pointer types and
4062/// pointer-sized integral types. We support this by allowing the evaluation of
4063/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4064/// Some simple arithmetic on such values is supported (they are treated much
4065/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004066static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004067 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004068 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004069 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004070}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004071
Richard Smithf48fdb02011-12-09 22:58:01 +00004072static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004073 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004074 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004075 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004076 if (!Val.isInt()) {
4077 // FIXME: It would be better to produce the diagnostic for casting
4078 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004079 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004080 return false;
4081 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004082 Result = Val.getInt();
4083 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004084}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004085
Richard Smithf48fdb02011-12-09 22:58:01 +00004086/// Check whether the given declaration can be directly converted to an integral
4087/// rvalue. If not, no diagnostic is produced; there are other things we can
4088/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004089bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004090 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004091 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004092 // Check for signedness/width mismatches between E type and ECD value.
4093 bool SameSign = (ECD->getInitVal().isSigned()
4094 == E->getType()->isSignedIntegerOrEnumerationType());
4095 bool SameWidth = (ECD->getInitVal().getBitWidth()
4096 == Info.Ctx.getIntWidth(E->getType()));
4097 if (SameSign && SameWidth)
4098 return Success(ECD->getInitVal(), E);
4099 else {
4100 // Get rid of mismatch (otherwise Success assertions will fail)
4101 // by computing a new value matching the type of E.
4102 llvm::APSInt Val = ECD->getInitVal();
4103 if (!SameSign)
4104 Val.setIsSigned(!ECD->getInitVal().isSigned());
4105 if (!SameWidth)
4106 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4107 return Success(Val, E);
4108 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004109 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004110 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004111}
4112
Chris Lattnera4d55d82008-10-06 06:40:35 +00004113/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4114/// as GCC.
4115static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4116 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004117 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004118 enum gcc_type_class {
4119 no_type_class = -1,
4120 void_type_class, integer_type_class, char_type_class,
4121 enumeral_type_class, boolean_type_class,
4122 pointer_type_class, reference_type_class, offset_type_class,
4123 real_type_class, complex_type_class,
4124 function_type_class, method_type_class,
4125 record_type_class, union_type_class,
4126 array_type_class, string_type_class,
4127 lang_type_class
4128 };
Mike Stump1eb44332009-09-09 15:08:12 +00004129
4130 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004131 // ideal, however it is what gcc does.
4132 if (E->getNumArgs() == 0)
4133 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004134
Chris Lattnera4d55d82008-10-06 06:40:35 +00004135 QualType ArgTy = E->getArg(0)->getType();
4136 if (ArgTy->isVoidType())
4137 return void_type_class;
4138 else if (ArgTy->isEnumeralType())
4139 return enumeral_type_class;
4140 else if (ArgTy->isBooleanType())
4141 return boolean_type_class;
4142 else if (ArgTy->isCharType())
4143 return string_type_class; // gcc doesn't appear to use char_type_class
4144 else if (ArgTy->isIntegerType())
4145 return integer_type_class;
4146 else if (ArgTy->isPointerType())
4147 return pointer_type_class;
4148 else if (ArgTy->isReferenceType())
4149 return reference_type_class;
4150 else if (ArgTy->isRealType())
4151 return real_type_class;
4152 else if (ArgTy->isComplexType())
4153 return complex_type_class;
4154 else if (ArgTy->isFunctionType())
4155 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004156 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004157 return record_type_class;
4158 else if (ArgTy->isUnionType())
4159 return union_type_class;
4160 else if (ArgTy->isArrayType())
4161 return array_type_class;
4162 else if (ArgTy->isUnionType())
4163 return union_type_class;
4164 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004165 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004166}
4167
Richard Smith80d4b552011-12-28 19:48:30 +00004168/// EvaluateBuiltinConstantPForLValue - Determine the result of
4169/// __builtin_constant_p when applied to the given lvalue.
4170///
4171/// An lvalue is only "constant" if it is a pointer or reference to the first
4172/// character of a string literal.
4173template<typename LValue>
4174static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004175 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004176 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4177}
4178
4179/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4180/// GCC as we can manage.
4181static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4182 QualType ArgType = Arg->getType();
4183
4184 // __builtin_constant_p always has one operand. The rules which gcc follows
4185 // are not precisely documented, but are as follows:
4186 //
4187 // - If the operand is of integral, floating, complex or enumeration type,
4188 // and can be folded to a known value of that type, it returns 1.
4189 // - If the operand and can be folded to a pointer to the first character
4190 // of a string literal (or such a pointer cast to an integral type), it
4191 // returns 1.
4192 //
4193 // Otherwise, it returns 0.
4194 //
4195 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4196 // its support for this does not currently work.
4197 if (ArgType->isIntegralOrEnumerationType()) {
4198 Expr::EvalResult Result;
4199 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4200 return false;
4201
4202 APValue &V = Result.Val;
4203 if (V.getKind() == APValue::Int)
4204 return true;
4205
4206 return EvaluateBuiltinConstantPForLValue(V);
4207 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4208 return Arg->isEvaluatable(Ctx);
4209 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4210 LValue LV;
4211 Expr::EvalStatus Status;
4212 EvalInfo Info(Ctx, Status);
4213 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4214 : EvaluatePointer(Arg, LV, Info)) &&
4215 !Status.HasSideEffects)
4216 return EvaluateBuiltinConstantPForLValue(LV);
4217 }
4218
4219 // Anything else isn't considered to be sufficiently constant.
4220 return false;
4221}
4222
John McCall42c8f872010-05-10 23:27:23 +00004223/// Retrieves the "underlying object type" of the given expression,
4224/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004225QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4226 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4227 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004228 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004229 } else if (const Expr *E = B.get<const Expr*>()) {
4230 if (isa<CompoundLiteralExpr>(E))
4231 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004232 }
4233
4234 return QualType();
4235}
4236
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004237bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004238 LValue Base;
Richard Smithc6794852012-05-23 04:13:20 +00004239
4240 {
4241 // The operand of __builtin_object_size is never evaluated for side-effects.
4242 // If there are any, but we can determine the pointed-to object anyway, then
4243 // ignore the side-effects.
4244 SpeculativeEvaluationRAII SpeculativeEval(Info);
4245 if (!EvaluatePointer(E->getArg(0), Base, Info))
4246 return false;
4247 }
John McCall42c8f872010-05-10 23:27:23 +00004248
4249 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004250 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004251
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004252 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004253 if (T.isNull() ||
4254 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004255 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004256 T->isVariablyModifiedType() ||
4257 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004258 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004259
4260 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4261 CharUnits Offset = Base.getLValueOffset();
4262
4263 if (!Offset.isNegative() && Offset <= Size)
4264 Size -= Offset;
4265 else
4266 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004267 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004268}
4269
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004270bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith2c39d712012-04-13 00:45:38 +00004271 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004272 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004273 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004274
4275 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004276 if (TryEvaluateBuiltinObjectSize(E))
4277 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004278
Richard Smith8ae4ec22012-08-07 04:16:51 +00004279 // If evaluating the argument has side-effects, we can't determine the size
4280 // of the object, and so we lower it to unknown now. CodeGen relies on us to
4281 // handle all cases where the expression has side-effects.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004282 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004283 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004284 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004285 return Success(0, E);
4286 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004287
Richard Smithc6794852012-05-23 04:13:20 +00004288 // Expression had no side effects, but we couldn't statically determine the
4289 // size of the referenced object.
Richard Smithf48fdb02011-12-09 22:58:01 +00004290 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004291 }
4292
Chris Lattner019f4e82008-10-06 05:28:25 +00004293 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004294 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004295
Richard Smith80d4b552011-12-28 19:48:30 +00004296 case Builtin::BI__builtin_constant_p:
4297 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004298
Chris Lattner21fb98e2009-09-23 06:06:36 +00004299 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004300 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004301 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004302 return Success(Operand, E);
4303 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004304
4305 case Builtin::BI__builtin_expect:
4306 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004307
Douglas Gregor5726d402010-09-10 06:27:15 +00004308 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004309 // A call to strlen is not a constant expression.
4310 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004311 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004312 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4313 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004314 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004315 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004316 case Builtin::BI__builtin_strlen:
4317 // As an extension, we support strlen() and __builtin_strlen() as constant
4318 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004319 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004320 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4321 // The string literal may have embedded null characters. Find the first
4322 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004323 StringRef Str = S->getString();
4324 StringRef::size_type Pos = Str.find(0);
4325 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004326 Str = Str.substr(0, Pos);
4327
4328 return Success(Str.size(), E);
4329 }
4330
Richard Smithf48fdb02011-12-09 22:58:01 +00004331 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004332
Richard Smith2c39d712012-04-13 00:45:38 +00004333 case Builtin::BI__atomic_always_lock_free:
Richard Smithfafbf062012-04-11 17:55:32 +00004334 case Builtin::BI__atomic_is_lock_free:
4335 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedman454b57a2011-10-17 21:44:23 +00004336 APSInt SizeVal;
4337 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4338 return false;
4339
4340 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4341 // of two less than the maximum inline atomic width, we know it is
4342 // lock-free. If the size isn't a power of two, or greater than the
4343 // maximum alignment where we promote atomics, we know it is not lock-free
4344 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4345 // the answer can only be determined at runtime; for example, 16-byte
4346 // atomics have lock-free implementations on some, but not all,
4347 // x86-64 processors.
4348
4349 // Check power-of-two.
4350 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith2c39d712012-04-13 00:45:38 +00004351 if (Size.isPowerOfTwo()) {
4352 // Check against inlining width.
4353 unsigned InlineWidthBits =
4354 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4355 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4356 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4357 Size == CharUnits::One() ||
4358 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4359 Expr::NPC_NeverValueDependent))
4360 // OK, we will inline appropriately-aligned operations of this size,
4361 // and _Atomic(T) is appropriately-aligned.
4362 return Success(1, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004363
Richard Smith2c39d712012-04-13 00:45:38 +00004364 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4365 castAs<PointerType>()->getPointeeType();
4366 if (!PointeeType->isIncompleteType() &&
4367 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4368 // OK, we will inline operations on this object.
4369 return Success(1, E);
4370 }
4371 }
4372 }
Eli Friedman454b57a2011-10-17 21:44:23 +00004373
Richard Smith2c39d712012-04-13 00:45:38 +00004374 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4375 Success(0, E) : Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004376 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004377 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004378}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004379
Richard Smith625b8072011-10-31 01:37:14 +00004380static bool HasSameBase(const LValue &A, const LValue &B) {
4381 if (!A.getLValueBase())
4382 return !B.getLValueBase();
4383 if (!B.getLValueBase())
4384 return false;
4385
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004386 if (A.getLValueBase().getOpaqueValue() !=
4387 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004388 const Decl *ADecl = GetLValueBaseDecl(A);
4389 if (!ADecl)
4390 return false;
4391 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004392 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004393 return false;
4394 }
4395
4396 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004397 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004398}
4399
Richard Smith7b48a292012-02-01 05:53:12 +00004400/// Perform the given integer operation, which is known to need at most BitWidth
4401/// bits, and check for overflow in the original type (if that type was not an
4402/// unsigned type).
4403template<typename Operation>
4404static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4405 const APSInt &LHS, const APSInt &RHS,
4406 unsigned BitWidth, Operation Op) {
4407 if (LHS.isUnsigned())
4408 return Op(LHS, RHS);
4409
4410 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4411 APSInt Result = Value.trunc(LHS.getBitWidth());
4412 if (Result.extend(BitWidth) != Value)
4413 HandleOverflow(Info, E, Value, E->getType());
4414 return Result;
4415}
4416
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004417namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00004418
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004419/// \brief Data recursive integer evaluator of certain binary operators.
4420///
4421/// We use a data recursive algorithm for binary operators so that we are able
4422/// to handle extreme cases of chained binary operators without causing stack
4423/// overflow.
4424class DataRecursiveIntBinOpEvaluator {
4425 struct EvalResult {
4426 APValue Val;
4427 bool Failed;
4428
4429 EvalResult() : Failed(false) { }
4430
4431 void swap(EvalResult &RHS) {
4432 Val.swap(RHS.Val);
4433 Failed = RHS.Failed;
4434 RHS.Failed = false;
4435 }
4436 };
4437
4438 struct Job {
4439 const Expr *E;
4440 EvalResult LHSResult; // meaningful only for binary operator expression.
4441 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4442
4443 Job() : StoredInfo(0) { }
4444 void startSpeculativeEval(EvalInfo &Info) {
4445 OldEvalStatus = Info.EvalStatus;
4446 Info.EvalStatus.Diag = 0;
4447 StoredInfo = &Info;
4448 }
4449 ~Job() {
4450 if (StoredInfo) {
4451 StoredInfo->EvalStatus = OldEvalStatus;
4452 }
4453 }
4454 private:
4455 EvalInfo *StoredInfo; // non-null if status changed.
4456 Expr::EvalStatus OldEvalStatus;
4457 };
4458
4459 SmallVector<Job, 16> Queue;
4460
4461 IntExprEvaluator &IntEval;
4462 EvalInfo &Info;
4463 APValue &FinalResult;
4464
4465public:
4466 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4467 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4468
4469 /// \brief True if \param E is a binary operator that we are going to handle
4470 /// data recursively.
4471 /// We handle binary operators that are comma, logical, or that have operands
4472 /// with integral or enumeration type.
4473 static bool shouldEnqueue(const BinaryOperator *E) {
4474 return E->getOpcode() == BO_Comma ||
4475 E->isLogicalOp() ||
4476 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4477 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00004478 }
4479
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004480 bool Traverse(const BinaryOperator *E) {
4481 enqueue(E);
4482 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00004483 while (!Queue.empty())
4484 process(PrevResult);
4485
4486 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004487
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004488 FinalResult.swap(PrevResult.Val);
4489 return true;
4490 }
4491
4492private:
4493 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4494 return IntEval.Success(Value, E, Result);
4495 }
4496 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4497 return IntEval.Success(Value, E, Result);
4498 }
4499 bool Error(const Expr *E) {
4500 return IntEval.Error(E);
4501 }
4502 bool Error(const Expr *E, diag::kind D) {
4503 return IntEval.Error(E, D);
4504 }
4505
4506 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4507 return Info.CCEDiag(E, D);
4508 }
4509
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004510 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4511 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004512 bool &SuppressRHSDiags);
4513
4514 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4515 const BinaryOperator *E, APValue &Result);
4516
4517 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4518 Result.Failed = !Evaluate(Result.Val, Info, E);
4519 if (Result.Failed)
4520 Result.Val = APValue();
4521 }
4522
Richard Trieub7783052012-03-21 23:30:30 +00004523 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004524
4525 void enqueue(const Expr *E) {
4526 E = E->IgnoreParens();
4527 Queue.resize(Queue.size()+1);
4528 Queue.back().E = E;
4529 Queue.back().Kind = Job::AnyExprKind;
4530 }
4531};
4532
4533}
4534
4535bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004536 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004537 bool &SuppressRHSDiags) {
4538 if (E->getOpcode() == BO_Comma) {
4539 // Ignore LHS but note if we could not evaluate it.
4540 if (LHSResult.Failed)
4541 Info.EvalStatus.HasSideEffects = true;
4542 return true;
4543 }
4544
4545 if (E->isLogicalOp()) {
4546 bool lhsResult;
4547 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004548 // We were able to evaluate the LHS, see if we can get away with not
4549 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004550 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004551 Success(lhsResult, E, LHSResult.Val);
4552 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004553 }
4554 } else {
4555 // Since we weren't able to evaluate the left hand side, it
4556 // must have had side effects.
4557 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004558
4559 // We can't evaluate the LHS; however, sometimes the result
4560 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4561 // Don't ignore RHS and suppress diagnostics from this arm.
4562 SuppressRHSDiags = true;
4563 }
4564
4565 return true;
4566 }
4567
4568 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4569 E->getRHS()->getType()->isIntegralOrEnumerationType());
4570
4571 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004572 return false; // Ignore RHS;
4573
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004574 return true;
4575}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004576
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004577bool DataRecursiveIntBinOpEvaluator::
4578 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4579 const BinaryOperator *E, APValue &Result) {
4580 if (E->getOpcode() == BO_Comma) {
4581 if (RHSResult.Failed)
4582 return false;
4583 Result = RHSResult.Val;
4584 return true;
4585 }
4586
4587 if (E->isLogicalOp()) {
4588 bool lhsResult, rhsResult;
4589 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4590 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4591
4592 if (LHSIsOK) {
4593 if (RHSIsOK) {
4594 if (E->getOpcode() == BO_LOr)
4595 return Success(lhsResult || rhsResult, E, Result);
4596 else
4597 return Success(lhsResult && rhsResult, E, Result);
4598 }
4599 } else {
4600 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004601 // We can't evaluate the LHS; however, sometimes the result
4602 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4603 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004604 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004605 }
4606 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004607
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004608 return false;
4609 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004610
4611 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4612 E->getRHS()->getType()->isIntegralOrEnumerationType());
4613
4614 if (LHSResult.Failed || RHSResult.Failed)
4615 return false;
4616
4617 const APValue &LHSVal = LHSResult.Val;
4618 const APValue &RHSVal = RHSResult.Val;
4619
4620 // Handle cases like (unsigned long)&a + 4.
4621 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4622 Result = LHSVal;
4623 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4624 RHSVal.getInt().getZExtValue());
4625 if (E->getOpcode() == BO_Add)
4626 Result.getLValueOffset() += AdditionalOffset;
4627 else
4628 Result.getLValueOffset() -= AdditionalOffset;
4629 return true;
4630 }
4631
4632 // Handle cases like 4 + (unsigned long)&a
4633 if (E->getOpcode() == BO_Add &&
4634 RHSVal.isLValue() && LHSVal.isInt()) {
4635 Result = RHSVal;
4636 Result.getLValueOffset() += CharUnits::fromQuantity(
4637 LHSVal.getInt().getZExtValue());
4638 return true;
4639 }
4640
4641 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4642 // Handle (intptr_t)&&A - (intptr_t)&&B.
4643 if (!LHSVal.getLValueOffset().isZero() ||
4644 !RHSVal.getLValueOffset().isZero())
4645 return false;
4646 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4647 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4648 if (!LHSExpr || !RHSExpr)
4649 return false;
4650 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4651 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4652 if (!LHSAddrExpr || !RHSAddrExpr)
4653 return false;
4654 // Make sure both labels come from the same function.
4655 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4656 RHSAddrExpr->getLabel()->getDeclContext())
4657 return false;
4658 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4659 return true;
4660 }
4661
4662 // All the following cases expect both operands to be an integer
4663 if (!LHSVal.isInt() || !RHSVal.isInt())
4664 return Error(E);
4665
4666 const APSInt &LHS = LHSVal.getInt();
4667 APSInt RHS = RHSVal.getInt();
4668
4669 switch (E->getOpcode()) {
4670 default:
4671 return Error(E);
4672 case BO_Mul:
4673 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4674 LHS.getBitWidth() * 2,
4675 std::multiplies<APSInt>()), E,
4676 Result);
4677 case BO_Add:
4678 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4679 LHS.getBitWidth() + 1,
4680 std::plus<APSInt>()), E, Result);
4681 case BO_Sub:
4682 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4683 LHS.getBitWidth() + 1,
4684 std::minus<APSInt>()), E, Result);
4685 case BO_And: return Success(LHS & RHS, E, Result);
4686 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4687 case BO_Or: return Success(LHS | RHS, E, Result);
4688 case BO_Div:
4689 case BO_Rem:
4690 if (RHS == 0)
4691 return Error(E, diag::note_expr_divide_by_zero);
4692 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4693 // not actually undefined behavior in C++11 due to a language defect.
4694 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4695 LHS.isSigned() && LHS.isMinSignedValue())
4696 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4697 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4698 Result);
4699 case BO_Shl: {
4700 // During constant-folding, a negative shift is an opposite shift. Such
4701 // a shift is not a constant expression.
4702 if (RHS.isSigned() && RHS.isNegative()) {
4703 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4704 RHS = -RHS;
4705 goto shift_right;
4706 }
4707
4708 shift_left:
4709 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4710 // the shifted type.
4711 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4712 if (SA != RHS) {
4713 CCEDiag(E, diag::note_constexpr_large_shift)
4714 << RHS << E->getType() << LHS.getBitWidth();
4715 } else if (LHS.isSigned()) {
4716 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4717 // operand, and must not overflow the corresponding unsigned type.
4718 if (LHS.isNegative())
4719 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4720 else if (LHS.countLeadingZeros() < SA)
4721 CCEDiag(E, diag::note_constexpr_lshift_discards);
4722 }
4723
4724 return Success(LHS << SA, E, Result);
4725 }
4726 case BO_Shr: {
4727 // During constant-folding, a negative shift is an opposite shift. Such a
4728 // shift is not a constant expression.
4729 if (RHS.isSigned() && RHS.isNegative()) {
4730 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4731 RHS = -RHS;
4732 goto shift_left;
4733 }
4734
4735 shift_right:
4736 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4737 // shifted type.
4738 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4739 if (SA != RHS)
4740 CCEDiag(E, diag::note_constexpr_large_shift)
4741 << RHS << E->getType() << LHS.getBitWidth();
4742
4743 return Success(LHS >> SA, E, Result);
4744 }
4745
4746 case BO_LT: return Success(LHS < RHS, E, Result);
4747 case BO_GT: return Success(LHS > RHS, E, Result);
4748 case BO_LE: return Success(LHS <= RHS, E, Result);
4749 case BO_GE: return Success(LHS >= RHS, E, Result);
4750 case BO_EQ: return Success(LHS == RHS, E, Result);
4751 case BO_NE: return Success(LHS != RHS, E, Result);
4752 }
4753}
4754
Richard Trieub7783052012-03-21 23:30:30 +00004755void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004756 Job &job = Queue.back();
4757
4758 switch (job.Kind) {
4759 case Job::AnyExprKind: {
4760 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4761 if (shouldEnqueue(Bop)) {
4762 job.Kind = Job::BinOpKind;
4763 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00004764 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004765 }
4766 }
4767
4768 EvaluateExpr(job.E, Result);
4769 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004770 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004771 }
4772
4773 case Job::BinOpKind: {
4774 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004775 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004776 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004777 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004778 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004779 }
4780 if (SuppressRHSDiags)
4781 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004782 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004783 job.Kind = Job::BinOpVisitedLHSKind;
4784 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00004785 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004786 }
4787
4788 case Job::BinOpVisitedLHSKind: {
4789 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4790 EvalResult RHS;
4791 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00004792 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004793 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004794 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004795 }
4796 }
4797
4798 llvm_unreachable("Invalid Job::Kind!");
4799}
4800
4801bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4802 if (E->isAssignmentOp())
4803 return Error(E);
4804
4805 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4806 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004807
Anders Carlsson286f85e2008-11-16 07:17:21 +00004808 QualType LHSTy = E->getLHS()->getType();
4809 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004810
4811 if (LHSTy->isAnyComplexType()) {
4812 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004813 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004814
Richard Smith745f5142012-01-27 01:14:48 +00004815 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4816 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004817 return false;
4818
Richard Smith745f5142012-01-27 01:14:48 +00004819 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004820 return false;
4821
4822 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004823 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004824 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004825 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004826 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4827
John McCall2de56d12010-08-25 11:45:40 +00004828 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004829 return Success((CR_r == APFloat::cmpEqual &&
4830 CR_i == APFloat::cmpEqual), E);
4831 else {
John McCall2de56d12010-08-25 11:45:40 +00004832 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004833 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004834 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004835 CR_r == APFloat::cmpLessThan ||
4836 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004837 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004838 CR_i == APFloat::cmpLessThan ||
4839 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004840 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004841 } else {
John McCall2de56d12010-08-25 11:45:40 +00004842 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004843 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4844 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4845 else {
John McCall2de56d12010-08-25 11:45:40 +00004846 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004847 "Invalid compex comparison.");
4848 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4849 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4850 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004851 }
4852 }
Mike Stump1eb44332009-09-09 15:08:12 +00004853
Anders Carlsson286f85e2008-11-16 07:17:21 +00004854 if (LHSTy->isRealFloatingType() &&
4855 RHSTy->isRealFloatingType()) {
4856 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004857
Richard Smith745f5142012-01-27 01:14:48 +00004858 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4859 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004860 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004861
Richard Smith745f5142012-01-27 01:14:48 +00004862 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004863 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004864
Anders Carlsson286f85e2008-11-16 07:17:21 +00004865 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004866
Anders Carlsson286f85e2008-11-16 07:17:21 +00004867 switch (E->getOpcode()) {
4868 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004869 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004870 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004871 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004872 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004873 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004874 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004875 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004876 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004877 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004878 E);
John McCall2de56d12010-08-25 11:45:40 +00004879 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004880 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004881 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004882 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004883 || CR == APFloat::cmpLessThan
4884 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004885 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004886 }
Mike Stump1eb44332009-09-09 15:08:12 +00004887
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004888 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004889 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004890 LValue LHSValue, RHSValue;
4891
4892 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4893 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004894 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004895
Richard Smith745f5142012-01-27 01:14:48 +00004896 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004897 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004898
Richard Smith625b8072011-10-31 01:37:14 +00004899 // Reject differing bases from the normal codepath; we special-case
4900 // comparisons to null.
4901 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004902 if (E->getOpcode() == BO_Sub) {
4903 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004904 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4905 return false;
4906 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4907 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4908 if (!LHSExpr || !RHSExpr)
4909 return false;
4910 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4911 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4912 if (!LHSAddrExpr || !RHSAddrExpr)
4913 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004914 // Make sure both labels come from the same function.
4915 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4916 RHSAddrExpr->getLabel()->getDeclContext())
4917 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004918 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004919 return true;
4920 }
Richard Smith9e36b532011-10-31 05:11:32 +00004921 // Inequalities and subtractions between unrelated pointers have
4922 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004923 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004924 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004925 // A constant address may compare equal to the address of a symbol.
4926 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004927 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004928 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4929 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004930 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004931 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004932 // distinct addresses. In clang, the result of such a comparison is
4933 // unspecified, so it is not a constant expression. However, we do know
4934 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004935 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4936 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004937 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004938 // We can't tell whether weak symbols will end up pointing to the same
4939 // object.
4940 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004941 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004942 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004943 // (Note that clang defaults to -fmerge-all-constants, which can
4944 // lead to inconsistent results for comparisons involving the address
4945 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004946 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004947 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004948
Richard Smith15efc4d2012-02-01 08:10:20 +00004949 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4950 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4951
Richard Smithf15fda02012-02-02 01:16:57 +00004952 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4953 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4954
John McCall2de56d12010-08-25 11:45:40 +00004955 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004956 // C++11 [expr.add]p6:
4957 // Unless both pointers point to elements of the same array object, or
4958 // one past the last element of the array object, the behavior is
4959 // undefined.
4960 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4961 !AreElementsOfSameArray(getType(LHSValue.Base),
4962 LHSDesignator, RHSDesignator))
4963 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4964
Chris Lattner4992bdd2010-04-20 17:13:14 +00004965 QualType Type = E->getLHS()->getType();
4966 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004967
Richard Smith180f4792011-11-10 06:34:14 +00004968 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004969 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004970 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004971
Richard Smith15efc4d2012-02-01 08:10:20 +00004972 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4973 // and produce incorrect results when it overflows. Such behavior
4974 // appears to be non-conforming, but is common, so perhaps we should
4975 // assume the standard intended for such cases to be undefined behavior
4976 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004977
Richard Smith15efc4d2012-02-01 08:10:20 +00004978 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4979 // overflow in the final conversion to ptrdiff_t.
4980 APSInt LHS(
4981 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4982 APSInt RHS(
4983 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4984 APSInt ElemSize(
4985 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4986 APSInt TrueResult = (LHS - RHS) / ElemSize;
4987 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4988
4989 if (Result.extend(65) != TrueResult)
4990 HandleOverflow(Info, E, TrueResult, E->getType());
4991 return Success(Result, E);
4992 }
Richard Smith82f28582012-01-31 06:41:30 +00004993
4994 // C++11 [expr.rel]p3:
4995 // Pointers to void (after pointer conversions) can be compared, with a
4996 // result defined as follows: If both pointers represent the same
4997 // address or are both the null pointer value, the result is true if the
4998 // operator is <= or >= and false otherwise; otherwise the result is
4999 // unspecified.
5000 // We interpret this as applying to pointers to *cv* void.
5001 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00005002 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00005003 CCEDiag(E, diag::note_constexpr_void_comparison);
5004
Richard Smithf15fda02012-02-02 01:16:57 +00005005 // C++11 [expr.rel]p2:
5006 // - If two pointers point to non-static data members of the same object,
5007 // or to subobjects or array elements fo such members, recursively, the
5008 // pointer to the later declared member compares greater provided the
5009 // two members have the same access control and provided their class is
5010 // not a union.
5011 // [...]
5012 // - Otherwise pointer comparisons are unspecified.
5013 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5014 E->isRelationalOp()) {
5015 bool WasArrayIndex;
5016 unsigned Mismatch =
5017 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5018 RHSDesignator, WasArrayIndex);
5019 // At the point where the designators diverge, the comparison has a
5020 // specified value if:
5021 // - we are comparing array indices
5022 // - we are comparing fields of a union, or fields with the same access
5023 // Otherwise, the result is unspecified and thus the comparison is not a
5024 // constant expression.
5025 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5026 Mismatch < RHSDesignator.Entries.size()) {
5027 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5028 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5029 if (!LF && !RF)
5030 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5031 else if (!LF)
5032 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5033 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5034 << RF->getParent() << RF;
5035 else if (!RF)
5036 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5037 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5038 << LF->getParent() << LF;
5039 else if (!LF->getParent()->isUnion() &&
5040 LF->getAccess() != RF->getAccess())
5041 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5042 << LF << LF->getAccess() << RF << RF->getAccess()
5043 << LF->getParent();
5044 }
5045 }
5046
Eli Friedmana3169882012-04-16 04:30:08 +00005047 // The comparison here must be unsigned, and performed with the same
5048 // width as the pointer.
Eli Friedmana3169882012-04-16 04:30:08 +00005049 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5050 uint64_t CompareLHS = LHSOffset.getQuantity();
5051 uint64_t CompareRHS = RHSOffset.getQuantity();
5052 assert(PtrSize <= 64 && "Unexpected pointer width");
5053 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5054 CompareLHS &= Mask;
5055 CompareRHS &= Mask;
5056
Eli Friedman28503762012-04-16 19:23:57 +00005057 // If there is a base and this is a relational operator, we can only
5058 // compare pointers within the object in question; otherwise, the result
5059 // depends on where the object is located in memory.
5060 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5061 QualType BaseTy = getType(LHSValue.Base);
5062 if (BaseTy->isIncompleteType())
5063 return Error(E);
5064 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5065 uint64_t OffsetLimit = Size.getQuantity();
5066 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5067 return Error(E);
5068 }
5069
Richard Smith625b8072011-10-31 01:37:14 +00005070 switch (E->getOpcode()) {
5071 default: llvm_unreachable("missing comparison operator");
Eli Friedmana3169882012-04-16 04:30:08 +00005072 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5073 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5074 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5075 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5076 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5077 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00005078 }
Anders Carlsson3068d112008-11-16 19:01:22 +00005079 }
5080 }
Richard Smithb02e4622012-02-01 01:42:44 +00005081
5082 if (LHSTy->isMemberPointerType()) {
5083 assert(E->isEqualityOp() && "unexpected member pointer operation");
5084 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5085
5086 MemberPtr LHSValue, RHSValue;
5087
5088 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5089 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5090 return false;
5091
5092 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5093 return false;
5094
5095 // C++11 [expr.eq]p2:
5096 // If both operands are null, they compare equal. Otherwise if only one is
5097 // null, they compare unequal.
5098 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5099 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5100 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5101 }
5102
5103 // Otherwise if either is a pointer to a virtual member function, the
5104 // result is unspecified.
5105 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5106 if (MD->isVirtual())
5107 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5108 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5109 if (MD->isVirtual())
5110 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5111
5112 // Otherwise they compare equal if and only if they would refer to the
5113 // same member of the same most derived object or the same subobject if
5114 // they were dereferenced with a hypothetical object of the associated
5115 // class type.
5116 bool Equal = LHSValue == RHSValue;
5117 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5118 }
5119
Richard Smith26f2cac2012-02-14 22:35:28 +00005120 if (LHSTy->isNullPtrType()) {
5121 assert(E->isComparisonOp() && "unexpected nullptr operation");
5122 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5123 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5124 // are compared, the result is true of the operator is <=, >= or ==, and
5125 // false otherwise.
5126 BinaryOperator::Opcode Opcode = E->getOpcode();
5127 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5128 }
5129
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005130 assert((!LHSTy->isIntegralOrEnumerationType() ||
5131 !RHSTy->isIntegralOrEnumerationType()) &&
5132 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5133 // We can't continue from here for non-integral types.
5134 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005135}
5136
Ken Dyck8b752f12010-01-27 17:10:57 +00005137CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005138 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5139 // result shall be the alignment of the referenced type."
5140 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5141 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005142
5143 // __alignof is defined to return the preferred alignment.
5144 return Info.Ctx.toCharUnitsFromBits(
5145 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005146}
5147
Ken Dyck8b752f12010-01-27 17:10:57 +00005148CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005149 E = E->IgnoreParens();
5150
5151 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005152 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005153 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005154 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5155 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005156
Chris Lattneraf707ab2009-01-24 21:53:27 +00005157 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005158 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5159 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005160
Chris Lattnere9feb472009-01-24 21:09:06 +00005161 return GetAlignOfType(E->getType());
5162}
5163
5164
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005165/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5166/// a result as the expression's type.
5167bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5168 const UnaryExprOrTypeTraitExpr *E) {
5169 switch(E->getKind()) {
5170 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005171 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005172 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005173 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005174 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005175 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005176
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005177 case UETT_VecStep: {
5178 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005179
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005180 if (Ty->isVectorType()) {
Ted Kremenek890f0f12012-08-23 20:46:57 +00005181 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005182
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005183 // The vec_step built-in functions that take a 3-component
5184 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5185 if (n == 3)
5186 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005187
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005188 return Success(n, E);
5189 } else
5190 return Success(1, E);
5191 }
5192
5193 case UETT_SizeOf: {
5194 QualType SrcTy = E->getTypeOfArgument();
5195 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5196 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005197 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5198 SrcTy = Ref->getPointeeType();
5199
Richard Smith180f4792011-11-10 06:34:14 +00005200 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005201 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005202 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005203 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005204 }
5205 }
5206
5207 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005208}
5209
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005210bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005211 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005212 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005213 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005214 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005215 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005216 for (unsigned i = 0; i != n; ++i) {
5217 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5218 switch (ON.getKind()) {
5219 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005220 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005221 APSInt IdxResult;
5222 if (!EvaluateInteger(Idx, IdxResult, Info))
5223 return false;
5224 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5225 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005226 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005227 CurrentType = AT->getElementType();
5228 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5229 Result += IdxResult.getSExtValue() * ElementSize;
5230 break;
5231 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005232
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005233 case OffsetOfExpr::OffsetOfNode::Field: {
5234 FieldDecl *MemberDecl = ON.getField();
5235 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005236 if (!RT)
5237 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005238 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005239 if (RD->isInvalidDecl()) return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005240 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005241 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005242 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005243 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005244 CurrentType = MemberDecl->getType().getNonReferenceType();
5245 break;
5246 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005247
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005248 case OffsetOfExpr::OffsetOfNode::Identifier:
5249 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005250
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005251 case OffsetOfExpr::OffsetOfNode::Base: {
5252 CXXBaseSpecifier *BaseSpec = ON.getBase();
5253 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005254 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005255
5256 // Find the layout of the class whose base we are looking into.
5257 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005258 if (!RT)
5259 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005260 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005261 if (RD->isInvalidDecl()) return false;
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005262 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5263
5264 // Find the base class itself.
5265 CurrentType = BaseSpec->getType();
5266 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5267 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005268 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005269
5270 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005271 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005272 break;
5273 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005274 }
5275 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005276 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005277}
5278
Chris Lattnerb542afe2008-07-11 19:10:17 +00005279bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005280 switch (E->getOpcode()) {
5281 default:
5282 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5283 // See C99 6.6p3.
5284 return Error(E);
5285 case UO_Extension:
5286 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5287 // If so, we could clear the diagnostic ID.
5288 return Visit(E->getSubExpr());
5289 case UO_Plus:
5290 // The result is just the value.
5291 return Visit(E->getSubExpr());
5292 case UO_Minus: {
5293 if (!Visit(E->getSubExpr()))
5294 return false;
5295 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005296 const APSInt &Value = Result.getInt();
5297 if (Value.isSigned() && Value.isMinSignedValue())
5298 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5299 E->getType());
5300 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005301 }
5302 case UO_Not: {
5303 if (!Visit(E->getSubExpr()))
5304 return false;
5305 if (!Result.isInt()) return Error(E);
5306 return Success(~Result.getInt(), E);
5307 }
5308 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005309 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005310 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005311 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005312 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005313 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005314 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005315}
Mike Stump1eb44332009-09-09 15:08:12 +00005316
Chris Lattner732b2232008-07-12 01:15:53 +00005317/// HandleCast - This is used to evaluate implicit or explicit casts where the
5318/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005319bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5320 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005321 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005322 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005323
Eli Friedman46a52322011-03-25 00:43:55 +00005324 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005325 case CK_BaseToDerived:
5326 case CK_DerivedToBase:
5327 case CK_UncheckedDerivedToBase:
5328 case CK_Dynamic:
5329 case CK_ToUnion:
5330 case CK_ArrayToPointerDecay:
5331 case CK_FunctionToPointerDecay:
5332 case CK_NullToPointer:
5333 case CK_NullToMemberPointer:
5334 case CK_BaseToDerivedMemberPointer:
5335 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005336 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005337 case CK_ConstructorConversion:
5338 case CK_IntegralToPointer:
5339 case CK_ToVoid:
5340 case CK_VectorSplat:
5341 case CK_IntegralToFloating:
5342 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005343 case CK_CPointerToObjCPointerCast:
5344 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005345 case CK_AnyPointerToBlockPointerCast:
5346 case CK_ObjCObjectLValueCast:
5347 case CK_FloatingRealToComplex:
5348 case CK_FloatingComplexToReal:
5349 case CK_FloatingComplexCast:
5350 case CK_FloatingComplexToIntegralComplex:
5351 case CK_IntegralRealToComplex:
5352 case CK_IntegralComplexCast:
5353 case CK_IntegralComplexToFloatingComplex:
5354 llvm_unreachable("invalid cast kind for integral value");
5355
Eli Friedmane50c2972011-03-25 19:07:11 +00005356 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005357 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005358 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005359 case CK_ARCProduceObject:
5360 case CK_ARCConsumeObject:
5361 case CK_ARCReclaimReturnedObject:
5362 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005363 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005364 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005365
Richard Smith7d580a42012-01-17 21:17:26 +00005366 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005367 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005368 case CK_AtomicToNonAtomic:
5369 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005370 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005371 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005372
5373 case CK_MemberPointerToBoolean:
5374 case CK_PointerToBoolean:
5375 case CK_IntegralToBoolean:
5376 case CK_FloatingToBoolean:
5377 case CK_FloatingComplexToBoolean:
5378 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005379 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005380 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005381 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005382 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005383 }
5384
Eli Friedman46a52322011-03-25 00:43:55 +00005385 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005386 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005387 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005388
Eli Friedmanbe265702009-02-20 01:15:07 +00005389 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005390 // Allow casts of address-of-label differences if they are no-ops
5391 // or narrowing. (The narrowing case isn't actually guaranteed to
5392 // be constant-evaluatable except in some narrow cases which are hard
5393 // to detect here. We let it through on the assumption the user knows
5394 // what they are doing.)
5395 if (Result.isAddrLabelDiff())
5396 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005397 // Only allow casts of lvalues if they are lossless.
5398 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5399 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005400
Richard Smithf72fccf2012-01-30 22:27:01 +00005401 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5402 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005403 }
Mike Stump1eb44332009-09-09 15:08:12 +00005404
Eli Friedman46a52322011-03-25 00:43:55 +00005405 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005406 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5407
John McCallefdb83e2010-05-07 21:00:08 +00005408 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005409 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005410 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005411
Daniel Dunbardd211642009-02-19 22:24:01 +00005412 if (LV.getLValueBase()) {
5413 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005414 // FIXME: Allow a larger integer size than the pointer size, and allow
5415 // narrowing back down to pointer width in subsequent integral casts.
5416 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005417 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005418 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005419
Richard Smithb755a9d2011-11-16 07:18:12 +00005420 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005421 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005422 return true;
5423 }
5424
Ken Dycka7305832010-01-15 12:37:54 +00005425 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5426 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005427 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005428 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005429
Eli Friedman46a52322011-03-25 00:43:55 +00005430 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005431 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005432 if (!EvaluateComplex(SubExpr, C, Info))
5433 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005434 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005435 }
Eli Friedman2217c872009-02-22 11:46:18 +00005436
Eli Friedman46a52322011-03-25 00:43:55 +00005437 case CK_FloatingToIntegral: {
5438 APFloat F(0.0);
5439 if (!EvaluateFloat(SubExpr, F, Info))
5440 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005441
Richard Smithc1c5f272011-12-13 06:39:58 +00005442 APSInt Value;
5443 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5444 return false;
5445 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005446 }
5447 }
Mike Stump1eb44332009-09-09 15:08:12 +00005448
Eli Friedman46a52322011-03-25 00:43:55 +00005449 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005450}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005451
Eli Friedman722c7172009-02-28 03:59:05 +00005452bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5453 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005454 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005455 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5456 return false;
5457 if (!LV.isComplexInt())
5458 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005459 return Success(LV.getComplexIntReal(), E);
5460 }
5461
5462 return Visit(E->getSubExpr());
5463}
5464
Eli Friedman664a1042009-02-27 04:45:43 +00005465bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005466 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005467 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005468 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5469 return false;
5470 if (!LV.isComplexInt())
5471 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005472 return Success(LV.getComplexIntImag(), E);
5473 }
5474
Richard Smith8327fad2011-10-24 18:44:57 +00005475 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005476 return Success(0, E);
5477}
5478
Douglas Gregoree8aff02011-01-04 17:33:58 +00005479bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5480 return Success(E->getPackLength(), E);
5481}
5482
Sebastian Redl295995c2010-09-10 20:55:47 +00005483bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5484 return Success(E->getValue(), E);
5485}
5486
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005487//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005488// Float Evaluation
5489//===----------------------------------------------------------------------===//
5490
5491namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005492class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005493 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005494 APFloat &Result;
5495public:
5496 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005497 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005498
Richard Smith1aa0be82012-03-03 22:46:17 +00005499 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005500 Result = V.getFloat();
5501 return true;
5502 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005503
Richard Smith51201882011-12-30 21:15:51 +00005504 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005505 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5506 return true;
5507 }
5508
Chris Lattner019f4e82008-10-06 05:28:25 +00005509 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005510
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005511 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005512 bool VisitBinaryOperator(const BinaryOperator *E);
5513 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005514 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005515
John McCallabd3a852010-05-07 22:08:54 +00005516 bool VisitUnaryReal(const UnaryOperator *E);
5517 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005518
Richard Smith51201882011-12-30 21:15:51 +00005519 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005520};
5521} // end anonymous namespace
5522
5523static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005524 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005525 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005526}
5527
Jay Foad4ba2a172011-01-12 09:06:06 +00005528static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005529 QualType ResultTy,
5530 const Expr *Arg,
5531 bool SNaN,
5532 llvm::APFloat &Result) {
5533 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5534 if (!S) return false;
5535
5536 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5537
5538 llvm::APInt fill;
5539
5540 // Treat empty strings as if they were zero.
5541 if (S->getString().empty())
5542 fill = llvm::APInt(32, 0);
5543 else if (S->getString().getAsInteger(0, fill))
5544 return false;
5545
5546 if (SNaN)
5547 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5548 else
5549 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5550 return true;
5551}
5552
Chris Lattner019f4e82008-10-06 05:28:25 +00005553bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005554 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005555 default:
5556 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5557
Chris Lattner019f4e82008-10-06 05:28:25 +00005558 case Builtin::BI__builtin_huge_val:
5559 case Builtin::BI__builtin_huge_valf:
5560 case Builtin::BI__builtin_huge_vall:
5561 case Builtin::BI__builtin_inf:
5562 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005563 case Builtin::BI__builtin_infl: {
5564 const llvm::fltSemantics &Sem =
5565 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005566 Result = llvm::APFloat::getInf(Sem);
5567 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005568 }
Mike Stump1eb44332009-09-09 15:08:12 +00005569
John McCalldb7b72a2010-02-28 13:00:19 +00005570 case Builtin::BI__builtin_nans:
5571 case Builtin::BI__builtin_nansf:
5572 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005573 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5574 true, Result))
5575 return Error(E);
5576 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005577
Chris Lattner9e621712008-10-06 06:31:58 +00005578 case Builtin::BI__builtin_nan:
5579 case Builtin::BI__builtin_nanf:
5580 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005581 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005582 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005583 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5584 false, Result))
5585 return Error(E);
5586 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005587
5588 case Builtin::BI__builtin_fabs:
5589 case Builtin::BI__builtin_fabsf:
5590 case Builtin::BI__builtin_fabsl:
5591 if (!EvaluateFloat(E->getArg(0), Result, Info))
5592 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005593
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005594 if (Result.isNegative())
5595 Result.changeSign();
5596 return true;
5597
Mike Stump1eb44332009-09-09 15:08:12 +00005598 case Builtin::BI__builtin_copysign:
5599 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005600 case Builtin::BI__builtin_copysignl: {
5601 APFloat RHS(0.);
5602 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5603 !EvaluateFloat(E->getArg(1), RHS, Info))
5604 return false;
5605 Result.copySign(RHS);
5606 return true;
5607 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005608 }
5609}
5610
John McCallabd3a852010-05-07 22:08:54 +00005611bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005612 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5613 ComplexValue CV;
5614 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5615 return false;
5616 Result = CV.FloatReal;
5617 return true;
5618 }
5619
5620 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005621}
5622
5623bool FloatExprEvaluator::VisitUnaryImag(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.FloatImag;
5629 return true;
5630 }
5631
Richard Smith8327fad2011-10-24 18:44:57 +00005632 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005633 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5634 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005635 return true;
5636}
5637
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005638bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005639 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005640 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005641 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005642 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005643 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005644 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5645 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005646 Result.changeSign();
5647 return true;
5648 }
5649}
Chris Lattner019f4e82008-10-06 05:28:25 +00005650
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005651bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005652 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5653 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005654
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005655 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005656 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5657 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005658 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005659 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005660 return false;
5661
5662 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005663 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005664 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005665 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005666 break;
John McCall2de56d12010-08-25 11:45:40 +00005667 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005668 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005669 break;
John McCall2de56d12010-08-25 11:45:40 +00005670 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005671 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005672 break;
John McCall2de56d12010-08-25 11:45:40 +00005673 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005674 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005675 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005676 }
Richard Smith7b48a292012-02-01 05:53:12 +00005677
5678 if (Result.isInfinity() || Result.isNaN())
5679 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5680 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005681}
5682
5683bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5684 Result = E->getValue();
5685 return true;
5686}
5687
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005688bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5689 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005690
Eli Friedman2a523ee2011-03-25 00:54:52 +00005691 switch (E->getCastKind()) {
5692 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005693 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005694
5695 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005696 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005697 return EvaluateInteger(SubExpr, IntResult, Info) &&
5698 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5699 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005700 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005701
5702 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005703 if (!Visit(SubExpr))
5704 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005705 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5706 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005707 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005708
Eli Friedman2a523ee2011-03-25 00:54:52 +00005709 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005710 ComplexValue V;
5711 if (!EvaluateComplex(SubExpr, V, Info))
5712 return false;
5713 Result = V.getComplexFloatReal();
5714 return true;
5715 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005716 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005717}
5718
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005719//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005720// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005721//===----------------------------------------------------------------------===//
5722
5723namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005724class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005725 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005726 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005727
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005728public:
John McCallf4cf1a12010-05-07 17:22:02 +00005729 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005730 : ExprEvaluatorBaseTy(info), Result(Result) {}
5731
Richard Smith1aa0be82012-03-03 22:46:17 +00005732 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005733 Result.setFrom(V);
5734 return true;
5735 }
Mike Stump1eb44332009-09-09 15:08:12 +00005736
Eli Friedman7ead5c72012-01-10 04:58:17 +00005737 bool ZeroInitialization(const Expr *E);
5738
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005739 //===--------------------------------------------------------------------===//
5740 // Visitor Methods
5741 //===--------------------------------------------------------------------===//
5742
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005743 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005744 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005745 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005746 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005747 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005748};
5749} // end anonymous namespace
5750
John McCallf4cf1a12010-05-07 17:22:02 +00005751static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5752 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005753 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005754 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005755}
5756
Eli Friedman7ead5c72012-01-10 04:58:17 +00005757bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek890f0f12012-08-23 20:46:57 +00005758 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005759 if (ElemTy->isRealFloatingType()) {
5760 Result.makeComplexFloat();
5761 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5762 Result.FloatReal = Zero;
5763 Result.FloatImag = Zero;
5764 } else {
5765 Result.makeComplexInt();
5766 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5767 Result.IntReal = Zero;
5768 Result.IntImag = Zero;
5769 }
5770 return true;
5771}
5772
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005773bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5774 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005775
5776 if (SubExpr->getType()->isRealFloatingType()) {
5777 Result.makeComplexFloat();
5778 APFloat &Imag = Result.FloatImag;
5779 if (!EvaluateFloat(SubExpr, Imag, Info))
5780 return false;
5781
5782 Result.FloatReal = APFloat(Imag.getSemantics());
5783 return true;
5784 } else {
5785 assert(SubExpr->getType()->isIntegerType() &&
5786 "Unexpected imaginary literal.");
5787
5788 Result.makeComplexInt();
5789 APSInt &Imag = Result.IntImag;
5790 if (!EvaluateInteger(SubExpr, Imag, Info))
5791 return false;
5792
5793 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5794 return true;
5795 }
5796}
5797
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005798bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005799
John McCall8786da72010-12-14 17:51:41 +00005800 switch (E->getCastKind()) {
5801 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005802 case CK_BaseToDerived:
5803 case CK_DerivedToBase:
5804 case CK_UncheckedDerivedToBase:
5805 case CK_Dynamic:
5806 case CK_ToUnion:
5807 case CK_ArrayToPointerDecay:
5808 case CK_FunctionToPointerDecay:
5809 case CK_NullToPointer:
5810 case CK_NullToMemberPointer:
5811 case CK_BaseToDerivedMemberPointer:
5812 case CK_DerivedToBaseMemberPointer:
5813 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005814 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005815 case CK_ConstructorConversion:
5816 case CK_IntegralToPointer:
5817 case CK_PointerToIntegral:
5818 case CK_PointerToBoolean:
5819 case CK_ToVoid:
5820 case CK_VectorSplat:
5821 case CK_IntegralCast:
5822 case CK_IntegralToBoolean:
5823 case CK_IntegralToFloating:
5824 case CK_FloatingToIntegral:
5825 case CK_FloatingToBoolean:
5826 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005827 case CK_CPointerToObjCPointerCast:
5828 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005829 case CK_AnyPointerToBlockPointerCast:
5830 case CK_ObjCObjectLValueCast:
5831 case CK_FloatingComplexToReal:
5832 case CK_FloatingComplexToBoolean:
5833 case CK_IntegralComplexToReal:
5834 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005835 case CK_ARCProduceObject:
5836 case CK_ARCConsumeObject:
5837 case CK_ARCReclaimReturnedObject:
5838 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005839 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005840 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005841
John McCall8786da72010-12-14 17:51:41 +00005842 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005843 case CK_AtomicToNonAtomic:
5844 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005845 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005846 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005847
5848 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005849 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005850 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005851 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005852
5853 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005854 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005855 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005856 return false;
5857
John McCall8786da72010-12-14 17:51:41 +00005858 Result.makeComplexFloat();
5859 Result.FloatImag = APFloat(Real.getSemantics());
5860 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005861 }
5862
John McCall8786da72010-12-14 17:51:41 +00005863 case CK_FloatingComplexCast: {
5864 if (!Visit(E->getSubExpr()))
5865 return false;
5866
5867 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5868 QualType From
5869 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5870
Richard Smithc1c5f272011-12-13 06:39:58 +00005871 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5872 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005873 }
5874
5875 case CK_FloatingComplexToIntegralComplex: {
5876 if (!Visit(E->getSubExpr()))
5877 return false;
5878
5879 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5880 QualType From
5881 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5882 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005883 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5884 To, Result.IntReal) &&
5885 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5886 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005887 }
5888
5889 case CK_IntegralRealToComplex: {
5890 APSInt &Real = Result.IntReal;
5891 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5892 return false;
5893
5894 Result.makeComplexInt();
5895 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5896 return true;
5897 }
5898
5899 case CK_IntegralComplexCast: {
5900 if (!Visit(E->getSubExpr()))
5901 return false;
5902
5903 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5904 QualType From
5905 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5906
Richard Smithf72fccf2012-01-30 22:27:01 +00005907 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5908 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005909 return true;
5910 }
5911
5912 case CK_IntegralComplexToFloatingComplex: {
5913 if (!Visit(E->getSubExpr()))
5914 return false;
5915
Ted Kremenek890f0f12012-08-23 20:46:57 +00005916 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005917 QualType From
Ted Kremenek890f0f12012-08-23 20:46:57 +00005918 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005919 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005920 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5921 To, Result.FloatReal) &&
5922 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5923 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005924 }
5925 }
5926
5927 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005928}
5929
John McCallf4cf1a12010-05-07 17:22:02 +00005930bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005931 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005932 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5933
Richard Smith745f5142012-01-27 01:14:48 +00005934 bool LHSOK = Visit(E->getLHS());
5935 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005936 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005937
John McCallf4cf1a12010-05-07 17:22:02 +00005938 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005939 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005940 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005941
Daniel Dunbar3f279872009-01-29 01:32:56 +00005942 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5943 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005944 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005945 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005946 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005947 if (Result.isComplexFloat()) {
5948 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5949 APFloat::rmNearestTiesToEven);
5950 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5951 APFloat::rmNearestTiesToEven);
5952 } else {
5953 Result.getComplexIntReal() += RHS.getComplexIntReal();
5954 Result.getComplexIntImag() += RHS.getComplexIntImag();
5955 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005956 break;
John McCall2de56d12010-08-25 11:45:40 +00005957 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005958 if (Result.isComplexFloat()) {
5959 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5960 APFloat::rmNearestTiesToEven);
5961 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5962 APFloat::rmNearestTiesToEven);
5963 } else {
5964 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5965 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5966 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005967 break;
John McCall2de56d12010-08-25 11:45:40 +00005968 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005969 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005970 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005971 APFloat &LHS_r = LHS.getComplexFloatReal();
5972 APFloat &LHS_i = LHS.getComplexFloatImag();
5973 APFloat &RHS_r = RHS.getComplexFloatReal();
5974 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005975
Daniel Dunbar3f279872009-01-29 01:32:56 +00005976 APFloat Tmp = LHS_r;
5977 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5978 Result.getComplexFloatReal() = Tmp;
5979 Tmp = LHS_i;
5980 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5981 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5982
5983 Tmp = LHS_r;
5984 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5985 Result.getComplexFloatImag() = Tmp;
5986 Tmp = LHS_i;
5987 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5988 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5989 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005990 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005991 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005992 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5993 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005994 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005995 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5996 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5997 }
5998 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005999 case BO_Div:
6000 if (Result.isComplexFloat()) {
6001 ComplexValue LHS = Result;
6002 APFloat &LHS_r = LHS.getComplexFloatReal();
6003 APFloat &LHS_i = LHS.getComplexFloatImag();
6004 APFloat &RHS_r = RHS.getComplexFloatReal();
6005 APFloat &RHS_i = RHS.getComplexFloatImag();
6006 APFloat &Res_r = Result.getComplexFloatReal();
6007 APFloat &Res_i = Result.getComplexFloatImag();
6008
6009 APFloat Den = RHS_r;
6010 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6011 APFloat Tmp = RHS_i;
6012 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6013 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6014
6015 Res_r = LHS_r;
6016 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6017 Tmp = LHS_i;
6018 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6019 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6020 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6021
6022 Res_i = LHS_i;
6023 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6024 Tmp = LHS_r;
6025 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6026 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6027 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6028 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00006029 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6030 return Error(E, diag::note_expr_divide_by_zero);
6031
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006032 ComplexValue LHS = Result;
6033 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6034 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6035 Result.getComplexIntReal() =
6036 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6037 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6038 Result.getComplexIntImag() =
6039 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6040 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6041 }
6042 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006043 }
6044
John McCallf4cf1a12010-05-07 17:22:02 +00006045 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006046}
6047
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006048bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6049 // Get the operand value into 'Result'.
6050 if (!Visit(E->getSubExpr()))
6051 return false;
6052
6053 switch (E->getOpcode()) {
6054 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00006055 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006056 case UO_Extension:
6057 return true;
6058 case UO_Plus:
6059 // The result is always just the subexpr.
6060 return true;
6061 case UO_Minus:
6062 if (Result.isComplexFloat()) {
6063 Result.getComplexFloatReal().changeSign();
6064 Result.getComplexFloatImag().changeSign();
6065 }
6066 else {
6067 Result.getComplexIntReal() = -Result.getComplexIntReal();
6068 Result.getComplexIntImag() = -Result.getComplexIntImag();
6069 }
6070 return true;
6071 case UO_Not:
6072 if (Result.isComplexFloat())
6073 Result.getComplexFloatImag().changeSign();
6074 else
6075 Result.getComplexIntImag() = -Result.getComplexIntImag();
6076 return true;
6077 }
6078}
6079
Eli Friedman7ead5c72012-01-10 04:58:17 +00006080bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6081 if (E->getNumInits() == 2) {
6082 if (E->getType()->isComplexType()) {
6083 Result.makeComplexFloat();
6084 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6085 return false;
6086 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6087 return false;
6088 } else {
6089 Result.makeComplexInt();
6090 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6091 return false;
6092 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6093 return false;
6094 }
6095 return true;
6096 }
6097 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6098}
6099
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00006100//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00006101// Void expression evaluation, primarily for a cast to void on the LHS of a
6102// comma operator
6103//===----------------------------------------------------------------------===//
6104
6105namespace {
6106class VoidExprEvaluator
6107 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6108public:
6109 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6110
Richard Smith1aa0be82012-03-03 22:46:17 +00006111 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00006112
6113 bool VisitCastExpr(const CastExpr *E) {
6114 switch (E->getCastKind()) {
6115 default:
6116 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6117 case CK_ToVoid:
6118 VisitIgnoredValue(E->getSubExpr());
6119 return true;
6120 }
6121 }
6122};
6123} // end anonymous namespace
6124
6125static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6126 assert(E->isRValue() && E->getType()->isVoidType());
6127 return VoidExprEvaluator(Info).Visit(E);
6128}
6129
6130//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006131// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006132//===----------------------------------------------------------------------===//
6133
Richard Smith1aa0be82012-03-03 22:46:17 +00006134static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006135 // In C, function designators are not lvalues, but we evaluate them as if they
6136 // are.
6137 if (E->isGLValue() || E->getType()->isFunctionType()) {
6138 LValue LV;
6139 if (!EvaluateLValue(E, LV, Info))
6140 return false;
6141 LV.moveInto(Result);
6142 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006143 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006144 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006145 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006146 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006147 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006148 } else if (E->getType()->hasPointerRepresentation()) {
6149 LValue LV;
6150 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006151 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006152 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006153 } else if (E->getType()->isRealFloatingType()) {
6154 llvm::APFloat F(0.0);
6155 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006156 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006157 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006158 } else if (E->getType()->isAnyComplexType()) {
6159 ComplexValue C;
6160 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006161 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006162 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006163 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006164 MemberPtr P;
6165 if (!EvaluateMemberPointer(E, P, Info))
6166 return false;
6167 P.moveInto(Result);
6168 return true;
Richard Smith51201882011-12-30 21:15:51 +00006169 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006170 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006171 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006172 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006173 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006174 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006175 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006176 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006177 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006178 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6179 return false;
6180 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006181 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00006182 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006183 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00006184 << E->getType();
6185 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00006186 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00006187 if (!EvaluateVoid(E, Info))
6188 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006189 } else if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006190 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006191 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006192 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006193 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006194 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006195 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006196
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006197 return true;
6198}
6199
Richard Smith83587db2012-02-15 02:18:13 +00006200/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6201/// cases, the in-place evaluation is essential, since later initializers for
6202/// an object can indirectly refer to subobjects which were initialized earlier.
6203static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6204 const Expr *E, CheckConstantExpressionKind CCEK,
6205 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006206 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006207 return false;
6208
6209 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006210 // Evaluate arrays and record types in-place, so that later initializers can
6211 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006212 if (E->getType()->isArrayType())
6213 return EvaluateArray(E, This, Result, Info);
6214 else if (E->getType()->isRecordType())
6215 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006216 }
6217
6218 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006219 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006220}
6221
Richard Smithf48fdb02011-12-09 22:58:01 +00006222/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6223/// lvalue-to-rvalue cast if it is an lvalue.
6224static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006225 if (!CheckLiteralType(Info, E))
6226 return false;
6227
Richard Smith1aa0be82012-03-03 22:46:17 +00006228 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006229 return false;
6230
6231 if (E->isGLValue()) {
6232 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006233 LV.setFrom(Info.Ctx, Result);
6234 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006235 return false;
6236 }
6237
Richard Smith1aa0be82012-03-03 22:46:17 +00006238 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006239 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006240}
Richard Smithc49bd112011-10-28 17:51:58 +00006241
Richard Smith51f47082011-10-29 00:50:52 +00006242/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006243/// any crazy technique (that has nothing to do with language standards) that
6244/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006245/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6246/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006247bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006248 // Fast-path evaluations of integer literals, since we sometimes see files
6249 // containing vast quantities of these.
6250 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6251 Result.Val = APValue(APSInt(L->getValue(),
6252 L->getType()->isUnsignedIntegerType()));
6253 return true;
6254 }
6255
Richard Smith2d6a5672012-01-14 04:30:29 +00006256 // FIXME: Evaluating values of large array and record types can cause
6257 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006258 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006259 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006260 return false;
6261
Richard Smithf48fdb02011-12-09 22:58:01 +00006262 EvalInfo Info(Ctx, Result);
6263 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006264}
6265
Jay Foad4ba2a172011-01-12 09:06:06 +00006266bool Expr::EvaluateAsBooleanCondition(bool &Result,
6267 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006268 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006269 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006270 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006271}
6272
Richard Smith80d4b552011-12-28 19:48:30 +00006273bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6274 SideEffectsKind AllowSideEffects) const {
6275 if (!getType()->isIntegralOrEnumerationType())
6276 return false;
6277
Richard Smithc49bd112011-10-28 17:51:58 +00006278 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006279 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6280 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006281 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006282
Richard Smithc49bd112011-10-28 17:51:58 +00006283 Result = ExprResult.Val.getInt();
6284 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006285}
6286
Jay Foad4ba2a172011-01-12 09:06:06 +00006287bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006288 EvalInfo Info(Ctx, Result);
6289
John McCallefdb83e2010-05-07 21:00:08 +00006290 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006291 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6292 !CheckLValueConstantExpression(Info, getExprLoc(),
6293 Ctx.getLValueReferenceType(getType()), LV))
6294 return false;
6295
Richard Smith1aa0be82012-03-03 22:46:17 +00006296 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006297 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006298}
6299
Richard Smith099e7f62011-12-19 06:19:21 +00006300bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6301 const VarDecl *VD,
6302 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006303 // FIXME: Evaluating initializers for large array and record types can cause
6304 // performance problems. Only do so in C++11 for now.
6305 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006306 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith2d6a5672012-01-14 04:30:29 +00006307 return false;
6308
Richard Smith099e7f62011-12-19 06:19:21 +00006309 Expr::EvalStatus EStatus;
6310 EStatus.Diag = &Notes;
6311
6312 EvalInfo InitInfo(Ctx, EStatus);
6313 InitInfo.setEvaluatingDecl(VD, Value);
6314
6315 LValue LVal;
6316 LVal.set(VD);
6317
Richard Smith51201882011-12-30 21:15:51 +00006318 // C++11 [basic.start.init]p2:
6319 // Variables with static storage duration or thread storage duration shall be
6320 // zero-initialized before any other initialization takes place.
6321 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006322 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006323 !VD->getType()->isReferenceType()) {
6324 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006325 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6326 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006327 return false;
6328 }
6329
Richard Smith83587db2012-02-15 02:18:13 +00006330 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6331 /*AllowNonLiteralTypes=*/true) ||
6332 EStatus.HasSideEffects)
6333 return false;
6334
6335 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6336 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006337}
6338
Richard Smith51f47082011-10-29 00:50:52 +00006339/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6340/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006341bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006342 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006343 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006344}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006345
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006346APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006347 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006348 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006349 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006350 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006351 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006352
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006353 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006354}
John McCalld905f5a2010-05-07 05:32:02 +00006355
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006356 bool Expr::EvalResult::isGlobalLValue() const {
6357 assert(Val.isLValue());
6358 return IsGlobalLValue(Val.getLValueBase());
6359 }
6360
6361
John McCalld905f5a2010-05-07 05:32:02 +00006362/// isIntegerConstantExpr - this recursive routine will test if an expression is
6363/// an integer constant expression.
6364
6365/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6366/// comma, etc
6367///
6368/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6369/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6370/// cast+dereference.
6371
6372// CheckICE - This function does the fundamental ICE checking: the returned
6373// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6374// Note that to reduce code duplication, this helper does no evaluation
6375// itself; the caller checks whether the expression is evaluatable, and
6376// in the rare cases where CheckICE actually cares about the evaluated
6377// value, it calls into Evalute.
6378//
6379// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006380// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006381// 1: This expression is not an ICE, but if it isn't evaluated, it's
6382// a legal subexpression for an ICE. This return value is used to handle
6383// the comma operator in C99 mode.
6384// 2: This expression is not an ICE, and is not a legal subexpression for one.
6385
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006386namespace {
6387
John McCalld905f5a2010-05-07 05:32:02 +00006388struct ICEDiag {
6389 unsigned Val;
6390 SourceLocation Loc;
6391
6392 public:
6393 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6394 ICEDiag() : Val(0) {}
6395};
6396
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006397}
6398
6399static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006400
6401static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6402 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006403 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006404 !EVResult.Val.isInt()) {
6405 return ICEDiag(2, E->getLocStart());
6406 }
6407 return NoDiag();
6408}
6409
6410static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6411 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006412 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006413 return ICEDiag(2, E->getLocStart());
6414 }
6415
6416 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006417#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006418#define STMT(Node, Base) case Expr::Node##Class:
6419#define EXPR(Node, Base)
6420#include "clang/AST/StmtNodes.inc"
6421 case Expr::PredefinedExprClass:
6422 case Expr::FloatingLiteralClass:
6423 case Expr::ImaginaryLiteralClass:
6424 case Expr::StringLiteralClass:
6425 case Expr::ArraySubscriptExprClass:
6426 case Expr::MemberExprClass:
6427 case Expr::CompoundAssignOperatorClass:
6428 case Expr::CompoundLiteralExprClass:
6429 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006430 case Expr::DesignatedInitExprClass:
6431 case Expr::ImplicitValueInitExprClass:
6432 case Expr::ParenListExprClass:
6433 case Expr::VAArgExprClass:
6434 case Expr::AddrLabelExprClass:
6435 case Expr::StmtExprClass:
6436 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006437 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006438 case Expr::CXXDynamicCastExprClass:
6439 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006440 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006441 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006442 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006443 case Expr::CXXThisExprClass:
6444 case Expr::CXXThrowExprClass:
6445 case Expr::CXXNewExprClass:
6446 case Expr::CXXDeleteExprClass:
6447 case Expr::CXXPseudoDestructorExprClass:
6448 case Expr::UnresolvedLookupExprClass:
6449 case Expr::DependentScopeDeclRefExprClass:
6450 case Expr::CXXConstructExprClass:
6451 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006452 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006453 case Expr::CXXTemporaryObjectExprClass:
6454 case Expr::CXXUnresolvedConstructExprClass:
6455 case Expr::CXXDependentScopeMemberExprClass:
6456 case Expr::UnresolvedMemberExprClass:
6457 case Expr::ObjCStringLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +00006458 case Expr::ObjCBoxedExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006459 case Expr::ObjCArrayLiteralClass:
6460 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006461 case Expr::ObjCEncodeExprClass:
6462 case Expr::ObjCMessageExprClass:
6463 case Expr::ObjCSelectorExprClass:
6464 case Expr::ObjCProtocolExprClass:
6465 case Expr::ObjCIvarRefExprClass:
6466 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006467 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006468 case Expr::ObjCIsaExprClass:
6469 case Expr::ShuffleVectorExprClass:
6470 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006471 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006472 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006473 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006474 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006475 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006476 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006477 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006478 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006479 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006480 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006481 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006482 return ICEDiag(2, E->getLocStart());
6483
Douglas Gregoree8aff02011-01-04 17:33:58 +00006484 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006485 case Expr::GNUNullExprClass:
6486 // GCC considers the GNU __null value to be an integral constant expression.
6487 return NoDiag();
6488
John McCall91a57552011-07-15 05:09:51 +00006489 case Expr::SubstNonTypeTemplateParmExprClass:
6490 return
6491 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6492
John McCalld905f5a2010-05-07 05:32:02 +00006493 case Expr::ParenExprClass:
6494 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006495 case Expr::GenericSelectionExprClass:
6496 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006497 case Expr::IntegerLiteralClass:
6498 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006499 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006500 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006501 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006502 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006503 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006504 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006505 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006506 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006507 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006508 return NoDiag();
6509 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006510 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006511 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6512 // constant expressions, but they can never be ICEs because an ICE cannot
6513 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006514 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006515 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006516 return CheckEvalInICE(E, Ctx);
6517 return ICEDiag(2, E->getLocStart());
6518 }
Richard Smith359c89d2012-02-24 22:12:32 +00006519 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006520 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6521 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006522 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006523 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006524 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006525 // Parameter variables are never constants. Without this check,
6526 // getAnyInitializer() can find a default argument, which leads
6527 // to chaos.
6528 if (isa<ParmVarDecl>(D))
6529 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6530
6531 // C++ 7.1.5.1p2
6532 // A variable of non-volatile const-qualified integral or enumeration
6533 // type initialized by an ICE can be used in ICEs.
6534 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006535 if (!Dcl->getType()->isIntegralOrEnumerationType())
6536 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6537
Richard Smith099e7f62011-12-19 06:19:21 +00006538 const VarDecl *VD;
6539 // Look for a declaration of this variable that has an initializer, and
6540 // check whether it is an ICE.
6541 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6542 return NoDiag();
6543 else
6544 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006545 }
6546 }
6547 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006548 }
John McCalld905f5a2010-05-07 05:32:02 +00006549 case Expr::UnaryOperatorClass: {
6550 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6551 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006552 case UO_PostInc:
6553 case UO_PostDec:
6554 case UO_PreInc:
6555 case UO_PreDec:
6556 case UO_AddrOf:
6557 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006558 // C99 6.6/3 allows increment and decrement within unevaluated
6559 // subexpressions of constant expressions, but they can never be ICEs
6560 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006561 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006562 case UO_Extension:
6563 case UO_LNot:
6564 case UO_Plus:
6565 case UO_Minus:
6566 case UO_Not:
6567 case UO_Real:
6568 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006569 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006570 }
6571
6572 // OffsetOf falls through here.
6573 }
6574 case Expr::OffsetOfExprClass: {
6575 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006576 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006577 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006578 // compliance: we should warn earlier for offsetof expressions with
6579 // array subscripts that aren't ICEs, and if the array subscripts
6580 // are ICEs, the value of the offsetof must be an integer constant.
6581 return CheckEvalInICE(E, Ctx);
6582 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006583 case Expr::UnaryExprOrTypeTraitExprClass: {
6584 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6585 if ((Exp->getKind() == UETT_SizeOf) &&
6586 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006587 return ICEDiag(2, E->getLocStart());
6588 return NoDiag();
6589 }
6590 case Expr::BinaryOperatorClass: {
6591 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6592 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006593 case BO_PtrMemD:
6594 case BO_PtrMemI:
6595 case BO_Assign:
6596 case BO_MulAssign:
6597 case BO_DivAssign:
6598 case BO_RemAssign:
6599 case BO_AddAssign:
6600 case BO_SubAssign:
6601 case BO_ShlAssign:
6602 case BO_ShrAssign:
6603 case BO_AndAssign:
6604 case BO_XorAssign:
6605 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006606 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6607 // constant expressions, but they can never be ICEs because an ICE cannot
6608 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006609 return ICEDiag(2, E->getLocStart());
6610
John McCall2de56d12010-08-25 11:45:40 +00006611 case BO_Mul:
6612 case BO_Div:
6613 case BO_Rem:
6614 case BO_Add:
6615 case BO_Sub:
6616 case BO_Shl:
6617 case BO_Shr:
6618 case BO_LT:
6619 case BO_GT:
6620 case BO_LE:
6621 case BO_GE:
6622 case BO_EQ:
6623 case BO_NE:
6624 case BO_And:
6625 case BO_Xor:
6626 case BO_Or:
6627 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006628 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6629 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006630 if (Exp->getOpcode() == BO_Div ||
6631 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006632 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006633 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006634 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006635 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006636 if (REval == 0)
6637 return ICEDiag(1, E->getLocStart());
6638 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006639 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006640 if (LEval.isMinSignedValue())
6641 return ICEDiag(1, E->getLocStart());
6642 }
6643 }
6644 }
John McCall2de56d12010-08-25 11:45:40 +00006645 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006646 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006647 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6648 // if it isn't evaluated.
6649 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6650 return ICEDiag(1, E->getLocStart());
6651 } else {
6652 // In both C89 and C++, commas in ICEs are illegal.
6653 return ICEDiag(2, E->getLocStart());
6654 }
6655 }
6656 if (LHSResult.Val >= RHSResult.Val)
6657 return LHSResult;
6658 return RHSResult;
6659 }
John McCall2de56d12010-08-25 11:45:40 +00006660 case BO_LAnd:
6661 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006662 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6663 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6664 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6665 // Rare case where the RHS has a comma "side-effect"; we need
6666 // to actually check the condition to see whether the side
6667 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006668 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006669 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006670 return RHSResult;
6671 return NoDiag();
6672 }
6673
6674 if (LHSResult.Val >= RHSResult.Val)
6675 return LHSResult;
6676 return RHSResult;
6677 }
6678 }
6679 }
6680 case Expr::ImplicitCastExprClass:
6681 case Expr::CStyleCastExprClass:
6682 case Expr::CXXFunctionalCastExprClass:
6683 case Expr::CXXStaticCastExprClass:
6684 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006685 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006686 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006687 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006688 if (isa<ExplicitCastExpr>(E)) {
6689 if (const FloatingLiteral *FL
6690 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6691 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6692 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6693 APSInt IgnoredVal(DestWidth, !DestSigned);
6694 bool Ignored;
6695 // If the value does not fit in the destination type, the behavior is
6696 // undefined, so we are not required to treat it as a constant
6697 // expression.
6698 if (FL->getValue().convertToInteger(IgnoredVal,
6699 llvm::APFloat::rmTowardZero,
6700 &Ignored) & APFloat::opInvalidOp)
6701 return ICEDiag(2, E->getLocStart());
6702 return NoDiag();
6703 }
6704 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006705 switch (cast<CastExpr>(E)->getCastKind()) {
6706 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006707 case CK_AtomicToNonAtomic:
6708 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006709 case CK_NoOp:
6710 case CK_IntegralToBoolean:
6711 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006712 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006713 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006714 return ICEDiag(2, E->getLocStart());
6715 }
John McCalld905f5a2010-05-07 05:32:02 +00006716 }
John McCall56ca35d2011-02-17 10:25:35 +00006717 case Expr::BinaryConditionalOperatorClass: {
6718 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6719 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6720 if (CommonResult.Val == 2) return CommonResult;
6721 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6722 if (FalseResult.Val == 2) return FalseResult;
6723 if (CommonResult.Val == 1) return CommonResult;
6724 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006725 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006726 return FalseResult;
6727 }
John McCalld905f5a2010-05-07 05:32:02 +00006728 case Expr::ConditionalOperatorClass: {
6729 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6730 // If the condition (ignoring parens) is a __builtin_constant_p call,
6731 // then only the true side is actually considered in an integer constant
6732 // expression, and it is fully evaluated. This is an important GNU
6733 // extension. See GCC PR38377 for discussion.
6734 if (const CallExpr *CallCE
6735 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006736 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6737 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006738 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006739 if (CondResult.Val == 2)
6740 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006741
Richard Smithf48fdb02011-12-09 22:58:01 +00006742 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6743 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006744
John McCalld905f5a2010-05-07 05:32:02 +00006745 if (TrueResult.Val == 2)
6746 return TrueResult;
6747 if (FalseResult.Val == 2)
6748 return FalseResult;
6749 if (CondResult.Val == 1)
6750 return CondResult;
6751 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6752 return NoDiag();
6753 // Rare case where the diagnostics depend on which side is evaluated
6754 // Note that if we get here, CondResult is 0, and at least one of
6755 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006756 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006757 return FalseResult;
6758 }
6759 return TrueResult;
6760 }
6761 case Expr::CXXDefaultArgExprClass:
6762 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6763 case Expr::ChooseExprClass: {
6764 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6765 }
6766 }
6767
David Blaikie30263482012-01-20 21:50:17 +00006768 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006769}
6770
Richard Smithf48fdb02011-12-09 22:58:01 +00006771/// Evaluate an expression as a C++11 integral constant expression.
6772static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6773 const Expr *E,
6774 llvm::APSInt *Value,
6775 SourceLocation *Loc) {
6776 if (!E->getType()->isIntegralOrEnumerationType()) {
6777 if (Loc) *Loc = E->getExprLoc();
6778 return false;
6779 }
6780
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006781 APValue Result;
6782 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006783 return false;
6784
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006785 assert(Result.isInt() && "pointer cast to int is not an ICE");
6786 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006787 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006788}
6789
Richard Smithdd1f29b2011-12-12 09:28:41 +00006790bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006791 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006792 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6793
John McCalld905f5a2010-05-07 05:32:02 +00006794 ICEDiag d = CheckICE(this, Ctx);
6795 if (d.Val != 0) {
6796 if (Loc) *Loc = d.Loc;
6797 return false;
6798 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006799 return true;
6800}
6801
6802bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6803 SourceLocation *Loc, bool isEvaluated) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006804 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006805 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6806
6807 if (!isIntegerConstantExpr(Ctx, Loc))
6808 return false;
6809 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006810 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006811 return true;
6812}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006813
Richard Smith70488e22012-02-14 21:38:30 +00006814bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6815 return CheckICE(this, Ctx).Val == 0;
6816}
6817
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006818bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6819 SourceLocation *Loc) const {
6820 // We support this checking in C++98 mode in order to diagnose compatibility
6821 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006822 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006823
Richard Smith70488e22012-02-14 21:38:30 +00006824 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006825 Expr::EvalStatus Status;
6826 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6827 Status.Diag = &Diags;
6828 EvalInfo Info(Ctx, Status);
6829
6830 APValue Scratch;
6831 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6832
6833 if (!Diags.empty()) {
6834 IsConstExpr = false;
6835 if (Loc) *Loc = Diags[0].first;
6836 } else if (!IsConstExpr) {
6837 // FIXME: This shouldn't happen.
6838 if (Loc) *Loc = getExprLoc();
6839 }
6840
6841 return IsConstExpr;
6842}
Richard Smith745f5142012-01-27 01:14:48 +00006843
6844bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6845 llvm::SmallVectorImpl<
6846 PartialDiagnosticAt> &Diags) {
6847 // FIXME: It would be useful to check constexpr function templates, but at the
6848 // moment the constant expression evaluator cannot cope with the non-rigorous
6849 // ASTs which we build for dependent expressions.
6850 if (FD->isDependentContext())
6851 return true;
6852
6853 Expr::EvalStatus Status;
6854 Status.Diag = &Diags;
6855
6856 EvalInfo Info(FD->getASTContext(), Status);
6857 Info.CheckingPotentialConstantExpression = true;
6858
6859 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6860 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6861
6862 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6863 // is a temporary being used as the 'this' pointer.
6864 LValue This;
6865 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006866 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006867
Richard Smith745f5142012-01-27 01:14:48 +00006868 ArrayRef<const Expr*> Args;
6869
6870 SourceLocation Loc = FD->getLocation();
6871
Richard Smith1aa0be82012-03-03 22:46:17 +00006872 APValue Scratch;
6873 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006874 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006875 else
Richard Smith745f5142012-01-27 01:14:48 +00006876 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6877 Args, FD->getBody(), Info, Scratch);
6878
6879 return Diags.empty();
6880}