blob: ae86150ee2a41fa109ce64bf8ed3bfd283546d85 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith745f5142012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlssonc44eec62008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump4572bab2009-05-30 03:56:50 +000048#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000049#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000050
Anders Carlssonc44eec62008-07-03 04:20:39 +000051using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000054
Richard Smith83587db2012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCallf4cf1a12010-05-07 17:22:02 +000057namespace {
Richard Smith180f4792011-11-10 06:34:14 +000058 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000061
Richard Smith83587db2012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
66 return B.get<const Expr*>()->getType();
67 }
68
Richard Smith180f4792011-11-10 06:34:14 +000069 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000070 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000071 static
Richard Smithf15fda02012-02-02 01:16:57 +000072 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000073 APValue::BaseOrMemberType Value;
74 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000075 return Value;
76 }
77
78 /// Get an LValue path entry, which is known to not be an array index, as a
79 /// field declaration.
Richard Smith83587db2012-02-15 02:18:13 +000080 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000081 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000082 }
83 /// Get an LValue path entry, which is known to not be an array index, as a
84 /// base class declaration.
Richard Smith83587db2012-02-15 02:18:13 +000085 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000086 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000087 }
88 /// Determine whether this LValue path entry for a base class names a virtual
89 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +000090 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000091 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +000092 }
93
Richard Smithb4e85ed2012-01-06 16:39:00 +000094 /// Find the path length and type of the most-derived subobject in the given
95 /// path, and find the size of the containing array, if any.
96 static
97 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
98 ArrayRef<APValue::LValuePathEntry> Path,
99 uint64_t &ArraySize, QualType &Type) {
100 unsigned MostDerivedLength = 0;
101 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000102 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000103 if (Type->isArrayType()) {
104 const ConstantArrayType *CAT =
105 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
106 Type = CAT->getElementType();
107 ArraySize = CAT->getSize().getZExtValue();
108 MostDerivedLength = I + 1;
Richard Smith86024012012-02-18 22:04:06 +0000109 } else if (Type->isAnyComplexType()) {
110 const ComplexType *CT = Type->castAs<ComplexType>();
111 Type = CT->getElementType();
112 ArraySize = 2;
113 MostDerivedLength = I + 1;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000114 } else if (const FieldDecl *FD = getAsField(Path[I])) {
115 Type = FD->getType();
116 ArraySize = 0;
117 MostDerivedLength = I + 1;
118 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000119 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000120 ArraySize = 0;
121 }
Richard Smith9a17a682011-11-07 05:07:52 +0000122 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000123 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000124 }
125
Richard Smithb4e85ed2012-01-06 16:39:00 +0000126 // The order of this enum is important for diagnostics.
127 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000128 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith86024012012-02-18 22:04:06 +0000129 CSK_This, CSK_Real, CSK_Imag
Richard Smithb4e85ed2012-01-06 16:39:00 +0000130 };
131
Richard Smith0a3bdb62011-11-04 02:25:55 +0000132 /// A path from a glvalue to a subobject of that glvalue.
133 struct SubobjectDesignator {
134 /// True if the subobject was named in a manner not supported by C++11. Such
135 /// lvalues can still be folded, but they are not core constant expressions
136 /// and we cannot perform lvalue-to-rvalue conversions on them.
137 bool Invalid : 1;
138
Richard Smithb4e85ed2012-01-06 16:39:00 +0000139 /// Is this a pointer one past the end of an object?
140 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000141
Richard Smithb4e85ed2012-01-06 16:39:00 +0000142 /// The length of the path to the most-derived object of which this is a
143 /// subobject.
144 unsigned MostDerivedPathLength : 30;
145
146 /// The size of the array of which the most-derived object is an element, or
147 /// 0 if the most-derived object is not an array element.
148 uint64_t MostDerivedArraySize;
149
150 /// The type of the most derived object referred to by this address.
151 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000152
Richard Smith9a17a682011-11-07 05:07:52 +0000153 typedef APValue::LValuePathEntry PathEntry;
154
Richard Smith0a3bdb62011-11-04 02:25:55 +0000155 /// The entries on the path from the glvalue to the designated subobject.
156 SmallVector<PathEntry, 8> Entries;
157
Richard Smithb4e85ed2012-01-06 16:39:00 +0000158 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000159
Richard Smithb4e85ed2012-01-06 16:39:00 +0000160 explicit SubobjectDesignator(QualType T)
161 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
162 MostDerivedArraySize(0), MostDerivedType(T) {}
163
164 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
165 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
166 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000167 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000168 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000169 ArrayRef<PathEntry> VEntries = V.getLValuePath();
170 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
171 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000172 MostDerivedPathLength =
173 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
174 V.getLValuePath(), MostDerivedArraySize,
175 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000176 }
177 }
178
Richard Smith0a3bdb62011-11-04 02:25:55 +0000179 void setInvalid() {
180 Invalid = true;
181 Entries.clear();
182 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000183
184 /// Determine whether this is a one-past-the-end pointer.
185 bool isOnePastTheEnd() const {
186 if (IsOnePastTheEnd)
187 return true;
188 if (MostDerivedArraySize &&
189 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
190 return true;
191 return false;
192 }
193
194 /// Check that this refers to a valid subobject.
195 bool isValidSubobject() const {
196 if (Invalid)
197 return false;
198 return !isOnePastTheEnd();
199 }
200 /// Check that this refers to a valid subobject, and if not, produce a
201 /// relevant diagnostic and set the designator as invalid.
202 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
203
204 /// Update this designator to refer to the first element within this array.
205 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000206 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000207 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000208 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000209
210 // This is a most-derived object.
211 MostDerivedType = CAT->getElementType();
212 MostDerivedArraySize = CAT->getSize().getZExtValue();
213 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000214 }
215 /// Update this designator to refer to the given base or member of this
216 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000217 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000218 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000219 APValue::BaseOrMemberType Value(D, Virtual);
220 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000221 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000222
223 // If this isn't a base class, it's a new most-derived object.
224 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
225 MostDerivedType = FD->getType();
226 MostDerivedArraySize = 0;
227 MostDerivedPathLength = Entries.size();
228 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000229 }
Richard Smith86024012012-02-18 22:04:06 +0000230 /// Update this designator to refer to the given complex component.
231 void addComplexUnchecked(QualType EltTy, bool Imag) {
232 PathEntry Entry;
233 Entry.ArrayIndex = Imag;
234 Entries.push_back(Entry);
235
236 // This is technically a most-derived object, though in practice this
237 // is unlikely to matter.
238 MostDerivedType = EltTy;
239 MostDerivedArraySize = 2;
240 MostDerivedPathLength = Entries.size();
241 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000242 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000243 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000244 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000245 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000246 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000247 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000248 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
249 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
250 setInvalid();
251 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000252 return;
253 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000254 // [expr.add]p4: For the purposes of these operators, a pointer to a
255 // nonarray object behaves the same as a pointer to the first element of
256 // an array of length one with the type of the object as its element type.
257 if (IsOnePastTheEnd && N == (uint64_t)-1)
258 IsOnePastTheEnd = false;
259 else if (!IsOnePastTheEnd && N == 1)
260 IsOnePastTheEnd = true;
261 else if (N != 0) {
262 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000263 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000264 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000265 }
266 };
267
Richard Smithd0dccea2011-10-28 22:34:42 +0000268 /// A stack frame in the constexpr call stack.
269 struct CallStackFrame {
270 EvalInfo &Info;
271
272 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000273 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000274
Richard Smith08d6e032011-12-16 19:06:07 +0000275 /// CallLoc - The location of the call expression for this call.
276 SourceLocation CallLoc;
277
278 /// Callee - The function which was called.
279 const FunctionDecl *Callee;
280
Richard Smith83587db2012-02-15 02:18:13 +0000281 /// Index - The call index of this call.
282 unsigned Index;
283
Richard Smith180f4792011-11-10 06:34:14 +0000284 /// This - The binding for the this pointer in this call, if any.
285 const LValue *This;
286
Richard Smithd0dccea2011-10-28 22:34:42 +0000287 /// ParmBindings - Parameter bindings for this function call, indexed by
288 /// parameters' function scope indices.
Richard Smith1aa0be82012-03-03 22:46:17 +0000289 const APValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000290
Eli Friedmanf6172ae2012-06-25 21:21:08 +0000291 // Note that we intentionally use std::map here so that references to
292 // values are stable.
293 typedef std::map<const Expr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000294 typedef MapTy::const_iterator temp_iterator;
295 /// Temporaries - Temporary lvalues materialized within this stack frame.
296 MapTy Temporaries;
297
Richard Smith08d6e032011-12-16 19:06:07 +0000298 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
299 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000300 const APValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000301 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000302 };
303
Richard Smithdd1f29b2011-12-12 09:28:41 +0000304 /// A partial diagnostic which we might know in advance that we are not going
305 /// to emit.
306 class OptionalDiagnostic {
307 PartialDiagnostic *Diag;
308
309 public:
310 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
311
312 template<typename T>
313 OptionalDiagnostic &operator<<(const T &v) {
314 if (Diag)
315 *Diag << v;
316 return *this;
317 }
Richard Smith789f9b62012-01-31 04:08:20 +0000318
319 OptionalDiagnostic &operator<<(const APSInt &I) {
320 if (Diag) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000321 SmallVector<char, 32> Buffer;
Richard Smith789f9b62012-01-31 04:08:20 +0000322 I.toString(Buffer);
323 *Diag << StringRef(Buffer.data(), Buffer.size());
324 }
325 return *this;
326 }
327
328 OptionalDiagnostic &operator<<(const APFloat &F) {
329 if (Diag) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000330 SmallVector<char, 32> Buffer;
Richard Smith789f9b62012-01-31 04:08:20 +0000331 F.toString(Buffer);
332 *Diag << StringRef(Buffer.data(), Buffer.size());
333 }
334 return *this;
335 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000336 };
337
Richard Smith83587db2012-02-15 02:18:13 +0000338 /// EvalInfo - This is a private struct used by the evaluator to capture
339 /// information about a subexpression as it is folded. It retains information
340 /// about the AST context, but also maintains information about the folded
341 /// expression.
342 ///
343 /// If an expression could be evaluated, it is still possible it is not a C
344 /// "integer constant expression" or constant expression. If not, this struct
345 /// captures information about how and why not.
346 ///
347 /// One bit of information passed *into* the request for constant folding
348 /// indicates whether the subexpression is "evaluated" or not according to C
349 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
350 /// evaluate the expression regardless of what the RHS is, but C only allows
351 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000352 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000353 ASTContext &Ctx;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000354
Richard Smithbd552ef2011-10-31 05:52:43 +0000355 /// EvalStatus - Contains information about the evaluation.
356 Expr::EvalStatus &EvalStatus;
357
358 /// CurrentCall - The top of the constexpr call stack.
359 CallStackFrame *CurrentCall;
360
Richard Smithbd552ef2011-10-31 05:52:43 +0000361 /// CallStackDepth - The number of calls in the call stack right now.
362 unsigned CallStackDepth;
363
Richard Smith83587db2012-02-15 02:18:13 +0000364 /// NextCallIndex - The next call index to assign.
365 unsigned NextCallIndex;
366
Richard Smithbd552ef2011-10-31 05:52:43 +0000367 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000368 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000369 CallStackFrame BottomFrame;
370
Richard Smith180f4792011-11-10 06:34:14 +0000371 /// EvaluatingDecl - This is the declaration whose initializer is being
372 /// evaluated, if any.
373 const VarDecl *EvaluatingDecl;
374
375 /// EvaluatingDeclValue - This is the value being constructed for the
376 /// declaration whose initializer is being evaluated, if any.
377 APValue *EvaluatingDeclValue;
378
Richard Smithc1c5f272011-12-13 06:39:58 +0000379 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
380 /// notes attached to it will also be stored, otherwise they will not be.
381 bool HasActiveDiagnostic;
382
Richard Smith745f5142012-01-27 01:14:48 +0000383 /// CheckingPotentialConstantExpression - Are we checking whether the
384 /// expression is a potential constant expression? If so, some diagnostics
385 /// are suppressed.
386 bool CheckingPotentialConstantExpression;
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000387
388 bool IntOverflowCheckMode;
Richard Smith745f5142012-01-27 01:14:48 +0000389
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000390 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
391 bool OverflowCheckMode=false)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000392 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000393 CallStackDepth(0), NextCallIndex(1),
394 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000395 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000396 CheckingPotentialConstantExpression(false),
397 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000398
Richard Smith180f4792011-11-10 06:34:14 +0000399 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
400 EvaluatingDecl = VD;
401 EvaluatingDeclValue = &Value;
402 }
403
David Blaikie4e4d0842012-03-11 07:00:24 +0000404 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000405
Richard Smithc1c5f272011-12-13 06:39:58 +0000406 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000407 // Don't perform any constexpr calls (other than the call we're checking)
408 // when checking a potential constant expression.
409 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
410 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000411 if (NextCallIndex == 0) {
412 // NextCallIndex has wrapped around.
413 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
414 return false;
415 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000416 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
417 return true;
418 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
419 << getLangOpts().ConstexprCallDepth;
420 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000421 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000422
Richard Smith83587db2012-02-15 02:18:13 +0000423 CallStackFrame *getCallFrame(unsigned CallIndex) {
424 assert(CallIndex && "no call index in getCallFrame");
425 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
426 // be null in this loop.
427 CallStackFrame *Frame = CurrentCall;
428 while (Frame->Index > CallIndex)
429 Frame = Frame->Caller;
430 return (Frame->Index == CallIndex) ? Frame : 0;
431 }
432
Richard Smithc1c5f272011-12-13 06:39:58 +0000433 private:
434 /// Add a diagnostic to the diagnostics list.
435 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
436 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
437 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
438 return EvalStatus.Diag->back().second;
439 }
440
Richard Smith08d6e032011-12-16 19:06:07 +0000441 /// Add notes containing a call stack to the current point of evaluation.
442 void addCallStack(unsigned Limit);
443
Richard Smithc1c5f272011-12-13 06:39:58 +0000444 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000445 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000446 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
447 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000448 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000449 // If we have a prior diagnostic, it will be noting that the expression
450 // isn't a constant expression. This diagnostic is more important.
451 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000452 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000453 unsigned CallStackNotes = CallStackDepth - 1;
454 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
455 if (Limit)
456 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000457 if (CheckingPotentialConstantExpression)
458 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000459
Richard Smithc1c5f272011-12-13 06:39:58 +0000460 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000461 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000462 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
463 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000464 if (!CheckingPotentialConstantExpression)
465 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000466 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000467 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000468 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000469 return OptionalDiagnostic();
470 }
471
Richard Smith5cfc7d82012-03-15 04:53:45 +0000472 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
473 = diag::note_invalid_subexpr_in_const_expr,
474 unsigned ExtraNotes = 0) {
475 if (EvalStatus.Diag)
476 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
477 HasActiveDiagnostic = false;
478 return OptionalDiagnostic();
479 }
480
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000481 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
482
Richard Smithdd1f29b2011-12-12 09:28:41 +0000483 /// Diagnose that the evaluation does not produce a C++11 core constant
484 /// expression.
Richard Smith5cfc7d82012-03-15 04:53:45 +0000485 template<typename LocArg>
486 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000487 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000488 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000489 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000490 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
491 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000492 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000493 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000494 return Diag(Loc, DiagId, ExtraNotes);
495 }
496
497 /// Add a note to a prior diagnostic.
498 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
499 if (!HasActiveDiagnostic)
500 return OptionalDiagnostic();
501 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000502 }
Richard Smith099e7f62011-12-19 06:19:21 +0000503
504 /// Add a stack of notes to a prior diagnostic.
505 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
506 if (HasActiveDiagnostic) {
507 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
508 Diags.begin(), Diags.end());
509 }
510 }
Richard Smith745f5142012-01-27 01:14:48 +0000511
512 /// Should we continue evaluation as much as possible after encountering a
513 /// construct which can't be folded?
514 bool keepEvaluatingAfterFailure() {
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000515 // Should return true in IntOverflowCheckMode, so that we check for
516 // overflow even if some subexpressions can't be evaluated as constants.
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000517 return IntOverflowCheckMode ||
518 (CheckingPotentialConstantExpression &&
519 EvalStatus.Diag && EvalStatus.Diag->empty());
Richard Smith745f5142012-01-27 01:14:48 +0000520 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000521 };
Richard Smithf15fda02012-02-02 01:16:57 +0000522
523 /// Object used to treat all foldable expressions as constant expressions.
524 struct FoldConstant {
525 bool Enabled;
526
527 explicit FoldConstant(EvalInfo &Info)
528 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
529 !Info.EvalStatus.HasSideEffects) {
530 }
531 // Treat the value we've computed since this object was created as constant.
532 void Fold(EvalInfo &Info) {
533 if (Enabled && !Info.EvalStatus.Diag->empty() &&
534 !Info.EvalStatus.HasSideEffects)
535 Info.EvalStatus.Diag->clear();
536 }
537 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000538
539 /// RAII object used to suppress diagnostics and side-effects from a
540 /// speculative evaluation.
541 class SpeculativeEvaluationRAII {
542 EvalInfo &Info;
543 Expr::EvalStatus Old;
544
545 public:
546 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000547 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith74e1ad92012-02-16 02:46:34 +0000548 : Info(Info), Old(Info.EvalStatus) {
549 Info.EvalStatus.Diag = NewDiag;
550 }
551 ~SpeculativeEvaluationRAII() {
552 Info.EvalStatus = Old;
553 }
554 };
Richard Smith08d6e032011-12-16 19:06:07 +0000555}
Richard Smithbd552ef2011-10-31 05:52:43 +0000556
Richard Smithb4e85ed2012-01-06 16:39:00 +0000557bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
558 CheckSubobjectKind CSK) {
559 if (Invalid)
560 return false;
561 if (isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000562 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000563 << CSK;
564 setInvalid();
565 return false;
566 }
567 return true;
568}
569
570void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
571 const Expr *E, uint64_t N) {
572 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000573 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000574 << static_cast<int>(N) << /*array*/ 0
575 << static_cast<unsigned>(MostDerivedArraySize);
576 else
Richard Smith5cfc7d82012-03-15 04:53:45 +0000577 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000578 << static_cast<int>(N) << /*non-array*/ 1;
579 setInvalid();
580}
581
Richard Smith08d6e032011-12-16 19:06:07 +0000582CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
583 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000584 const APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000585 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000586 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000587 Info.CurrentCall = this;
588 ++Info.CallStackDepth;
589}
590
591CallStackFrame::~CallStackFrame() {
592 assert(Info.CurrentCall == this && "calls retired out of order");
593 --Info.CallStackDepth;
594 Info.CurrentCall = Caller;
595}
596
597/// Produce a string describing the given constexpr call.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000598static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
Richard Smith08d6e032011-12-16 19:06:07 +0000599 unsigned ArgIndex = 0;
600 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000601 !isa<CXXConstructorDecl>(Frame->Callee) &&
602 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000603
604 if (!IsMemberCall)
605 Out << *Frame->Callee << '(';
606
607 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
608 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000609 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000610 Out << ", ";
611
612 const ParmVarDecl *Param = *I;
Richard Smith1aa0be82012-03-03 22:46:17 +0000613 const APValue &Arg = Frame->Arguments[ArgIndex];
614 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smith08d6e032011-12-16 19:06:07 +0000615
616 if (ArgIndex == 0 && IsMemberCall)
617 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000618 }
619
Richard Smith08d6e032011-12-16 19:06:07 +0000620 Out << ')';
621}
622
623void EvalInfo::addCallStack(unsigned Limit) {
624 // Determine which calls to skip, if any.
625 unsigned ActiveCalls = CallStackDepth - 1;
626 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
627 if (Limit && Limit < ActiveCalls) {
628 SkipStart = Limit / 2 + Limit % 2;
629 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000630 }
631
Richard Smith08d6e032011-12-16 19:06:07 +0000632 // Walk the call stack and add the diagnostics.
633 unsigned CallIdx = 0;
634 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
635 Frame = Frame->Caller, ++CallIdx) {
636 // Skip this call?
637 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
638 if (CallIdx == SkipStart) {
639 // Note that we're skipping calls.
640 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
641 << unsigned(ActiveCalls - Limit);
642 }
643 continue;
644 }
645
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000646 SmallVector<char, 128> Buffer;
Richard Smith08d6e032011-12-16 19:06:07 +0000647 llvm::raw_svector_ostream Out(Buffer);
648 describeCall(Frame, Out);
649 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
650 }
651}
652
653namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000654 struct ComplexValue {
655 private:
656 bool IsInt;
657
658 public:
659 APSInt IntReal, IntImag;
660 APFloat FloatReal, FloatImag;
661
662 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
663
664 void makeComplexFloat() { IsInt = false; }
665 bool isComplexFloat() const { return !IsInt; }
666 APFloat &getComplexFloatReal() { return FloatReal; }
667 APFloat &getComplexFloatImag() { return FloatImag; }
668
669 void makeComplexInt() { IsInt = true; }
670 bool isComplexInt() const { return IsInt; }
671 APSInt &getComplexIntReal() { return IntReal; }
672 APSInt &getComplexIntImag() { return IntImag; }
673
Richard Smith1aa0be82012-03-03 22:46:17 +0000674 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000675 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000676 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000677 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000678 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000679 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000680 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000681 assert(v.isComplexFloat() || v.isComplexInt());
682 if (v.isComplexFloat()) {
683 makeComplexFloat();
684 FloatReal = v.getComplexFloatReal();
685 FloatImag = v.getComplexFloatImag();
686 } else {
687 makeComplexInt();
688 IntReal = v.getComplexIntReal();
689 IntImag = v.getComplexIntImag();
690 }
691 }
John McCallf4cf1a12010-05-07 17:22:02 +0000692 };
John McCallefdb83e2010-05-07 21:00:08 +0000693
694 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000695 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000696 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000697 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000698 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000699
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000700 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000701 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000702 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000703 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000704 SubobjectDesignator &getLValueDesignator() { return Designator; }
705 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000706
Richard Smith1aa0be82012-03-03 22:46:17 +0000707 void moveInto(APValue &V) const {
708 if (Designator.Invalid)
709 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
710 else
711 V = APValue(Base, Offset, Designator.Entries,
712 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000713 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000714 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000715 assert(V.isLValue());
716 Base = V.getLValueBase();
717 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000718 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000719 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000720 }
721
Richard Smith83587db2012-02-15 02:18:13 +0000722 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000723 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000724 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000725 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000726 Designator = SubobjectDesignator(getType(B));
727 }
728
729 // Check that this LValue is not based on a null pointer. If it is, produce
730 // a diagnostic and mark the designator as invalid.
731 bool checkNullPointer(EvalInfo &Info, const Expr *E,
732 CheckSubobjectKind CSK) {
733 if (Designator.Invalid)
734 return false;
735 if (!Base) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000736 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000737 << CSK;
738 Designator.setInvalid();
739 return false;
740 }
741 return true;
742 }
743
744 // Check this LValue refers to an object. If not, set the designator to be
745 // invalid and emit a diagnostic.
746 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000747 // Outside C++11, do not build a designator referring to a subobject of
748 // any object: we won't use such a designator for anything.
Richard Smith80ad52f2013-01-02 11:42:31 +0000749 if (!Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000750 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000751 return checkNullPointer(Info, E, CSK) &&
752 Designator.checkSubobject(Info, E, CSK);
753 }
754
755 void addDecl(EvalInfo &Info, const Expr *E,
756 const Decl *D, bool Virtual = false) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000757 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
758 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000759 }
760 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000761 if (checkSubobject(Info, E, CSK_ArrayToPointer))
762 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000763 }
Richard Smith86024012012-02-18 22:04:06 +0000764 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000765 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
766 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000767 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000768 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000769 if (checkNullPointer(Info, E, CSK_ArrayIndex))
770 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000771 }
John McCallefdb83e2010-05-07 21:00:08 +0000772 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000773
774 struct MemberPtr {
775 MemberPtr() {}
776 explicit MemberPtr(const ValueDecl *Decl) :
777 DeclAndIsDerivedMember(Decl, false), Path() {}
778
779 /// The member or (direct or indirect) field referred to by this member
780 /// pointer, or 0 if this is a null member pointer.
781 const ValueDecl *getDecl() const {
782 return DeclAndIsDerivedMember.getPointer();
783 }
784 /// Is this actually a member of some type derived from the relevant class?
785 bool isDerivedMember() const {
786 return DeclAndIsDerivedMember.getInt();
787 }
788 /// Get the class which the declaration actually lives in.
789 const CXXRecordDecl *getContainingRecord() const {
790 return cast<CXXRecordDecl>(
791 DeclAndIsDerivedMember.getPointer()->getDeclContext());
792 }
793
Richard Smith1aa0be82012-03-03 22:46:17 +0000794 void moveInto(APValue &V) const {
795 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000796 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000797 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000798 assert(V.isMemberPointer());
799 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
800 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
801 Path.clear();
802 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
803 Path.insert(Path.end(), P.begin(), P.end());
804 }
805
806 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
807 /// whether the member is a member of some class derived from the class type
808 /// of the member pointer.
809 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
810 /// Path - The path of base/derived classes from the member declaration's
811 /// class (exclusive) to the class type of the member pointer (inclusive).
812 SmallVector<const CXXRecordDecl*, 4> Path;
813
814 /// Perform a cast towards the class of the Decl (either up or down the
815 /// hierarchy).
816 bool castBack(const CXXRecordDecl *Class) {
817 assert(!Path.empty());
818 const CXXRecordDecl *Expected;
819 if (Path.size() >= 2)
820 Expected = Path[Path.size() - 2];
821 else
822 Expected = getContainingRecord();
823 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
824 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
825 // if B does not contain the original member and is not a base or
826 // derived class of the class containing the original member, the result
827 // of the cast is undefined.
828 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
829 // (D::*). We consider that to be a language defect.
830 return false;
831 }
832 Path.pop_back();
833 return true;
834 }
835 /// Perform a base-to-derived member pointer cast.
836 bool castToDerived(const CXXRecordDecl *Derived) {
837 if (!getDecl())
838 return true;
839 if (!isDerivedMember()) {
840 Path.push_back(Derived);
841 return true;
842 }
843 if (!castBack(Derived))
844 return false;
845 if (Path.empty())
846 DeclAndIsDerivedMember.setInt(false);
847 return true;
848 }
849 /// Perform a derived-to-base member pointer cast.
850 bool castToBase(const CXXRecordDecl *Base) {
851 if (!getDecl())
852 return true;
853 if (Path.empty())
854 DeclAndIsDerivedMember.setInt(true);
855 if (isDerivedMember()) {
856 Path.push_back(Base);
857 return true;
858 }
859 return castBack(Base);
860 }
861 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000862
Richard Smithb02e4622012-02-01 01:42:44 +0000863 /// Compare two member pointers, which are assumed to be of the same type.
864 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
865 if (!LHS.getDecl() || !RHS.getDecl())
866 return !LHS.getDecl() && !RHS.getDecl();
867 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
868 return false;
869 return LHS.Path == RHS.Path;
870 }
871
Richard Smithc1c5f272011-12-13 06:39:58 +0000872 /// Kinds of constant expression checking, for diagnostics.
873 enum CheckConstantExpressionKind {
874 CCEK_Constant, ///< A normal constant.
875 CCEK_ReturnValue, ///< A constexpr function return value.
876 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
877 };
John McCallf4cf1a12010-05-07 17:22:02 +0000878}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000879
Richard Smith1aa0be82012-03-03 22:46:17 +0000880static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000881static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
882 const LValue &This, const Expr *E,
883 CheckConstantExpressionKind CCEK = CCEK_Constant,
884 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000885static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
886static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000887static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
888 EvalInfo &Info);
889static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000890static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000891static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000892 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000893static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000894static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000895
896//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000897// Misc utilities
898//===----------------------------------------------------------------------===//
899
Richard Smith180f4792011-11-10 06:34:14 +0000900/// Should this call expression be treated as a string literal?
901static bool IsStringLiteralCall(const CallExpr *E) {
902 unsigned Builtin = E->isBuiltinCall();
903 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
904 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
905}
906
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000907static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000908 // C++11 [expr.const]p3 An address constant expression is a prvalue core
909 // constant expression of pointer type that evaluates to...
910
911 // ... a null pointer value, or a prvalue core constant expression of type
912 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000913 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000914
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000915 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
916 // ... the address of an object with static storage duration,
917 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
918 return VD->hasGlobalStorage();
919 // ... the address of a function,
920 return isa<FunctionDecl>(D);
921 }
922
923 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000924 switch (E->getStmtClass()) {
925 default:
926 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000927 case Expr::CompoundLiteralExprClass: {
928 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
929 return CLE->isFileScope() && CLE->isLValue();
930 }
Richard Smith180f4792011-11-10 06:34:14 +0000931 // A string literal has static storage duration.
932 case Expr::StringLiteralClass:
933 case Expr::PredefinedExprClass:
934 case Expr::ObjCStringLiteralClass:
935 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000936 case Expr::CXXTypeidExprClass:
Francois Pichete275a182012-04-16 04:08:35 +0000937 case Expr::CXXUuidofExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000938 return true;
939 case Expr::CallExprClass:
940 return IsStringLiteralCall(cast<CallExpr>(E));
941 // For GCC compatibility, &&label has static storage duration.
942 case Expr::AddrLabelExprClass:
943 return true;
944 // A Block literal expression may be used as the initialization value for
945 // Block variables at global or local static scope.
946 case Expr::BlockExprClass:
947 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000948 case Expr::ImplicitValueInitExprClass:
949 // FIXME:
950 // We can never form an lvalue with an implicit value initialization as its
951 // base through expression evaluation, so these only appear in one case: the
952 // implicit variable declaration we invent when checking whether a constexpr
953 // constructor can produce a constant expression. We must assume that such
954 // an expression might be a global lvalue.
955 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000956 }
John McCall42c8f872010-05-10 23:27:23 +0000957}
958
Richard Smith83587db2012-02-15 02:18:13 +0000959static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
960 assert(Base && "no location for a null lvalue");
961 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
962 if (VD)
963 Info.Note(VD->getLocation(), diag::note_declared_at);
964 else
Ted Kremenek890f0f12012-08-23 20:46:57 +0000965 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smith83587db2012-02-15 02:18:13 +0000966 diag::note_constexpr_temporary_here);
967}
968
Richard Smith9a17a682011-11-07 05:07:52 +0000969/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000970/// value for an address or reference constant expression. Return true if we
971/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000972static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
973 QualType Type, const LValue &LVal) {
974 bool IsReferenceType = Type->isReferenceType();
975
Richard Smithc1c5f272011-12-13 06:39:58 +0000976 APValue::LValueBase Base = LVal.getLValueBase();
977 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
978
Richard Smithb78ae972012-02-18 04:58:18 +0000979 // Check that the object is a global. Note that the fake 'this' object we
980 // manufacture when checking potential constant expressions is conservatively
981 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000982 if (!IsGlobalLValue(Base)) {
Richard Smith80ad52f2013-01-02 11:42:31 +0000983 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000984 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000985 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
986 << IsReferenceType << !Designator.Entries.empty()
987 << !!VD << VD;
988 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000989 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000990 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000991 }
Richard Smith61e61622012-01-12 06:08:57 +0000992 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000993 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000994 }
Richard Smith83587db2012-02-15 02:18:13 +0000995 assert((Info.CheckingPotentialConstantExpression ||
996 LVal.getLValueCallIndex() == 0) &&
997 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +0000998
Hans Wennborg48def652012-08-29 18:27:29 +0000999 // Check if this is a thread-local variable.
1000 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1001 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1002 if (Var->isThreadSpecified())
1003 return false;
1004 }
1005 }
1006
Richard Smithb4e85ed2012-01-06 16:39:00 +00001007 // Allow address constant expressions to be past-the-end pointers. This is
1008 // an extension: the standard requires them to point to an object.
1009 if (!IsReferenceType)
1010 return true;
1011
1012 // A reference constant expression must refer to an object.
1013 if (!Base) {
1014 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001015 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001016 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001017 }
1018
Richard Smithc1c5f272011-12-13 06:39:58 +00001019 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001020 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001021 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001022 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001023 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001024 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001025 }
1026
Richard Smith9a17a682011-11-07 05:07:52 +00001027 return true;
1028}
1029
Richard Smith51201882011-12-30 21:15:51 +00001030/// Check that this core constant expression is of literal type, and if not,
1031/// produce an appropriate diagnostic.
1032static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1033 if (!E->isRValue() || E->getType()->isLiteralType())
1034 return true;
1035
1036 // Prvalue constant expressions must be of literal types.
Richard Smith80ad52f2013-01-02 11:42:31 +00001037 if (Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001038 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001039 << E->getType();
1040 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001041 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001042 return false;
1043}
1044
Richard Smith47a1eed2011-10-29 20:57:55 +00001045/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001046/// constant expression. If not, report an appropriate diagnostic. Does not
1047/// check that the expression is of literal type.
1048static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1049 QualType Type, const APValue &Value) {
1050 // Core issue 1454: For a literal constant expression of array or class type,
1051 // each subobject of its value shall have been initialized by a constant
1052 // expression.
1053 if (Value.isArray()) {
1054 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1055 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1056 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1057 Value.getArrayInitializedElt(I)))
1058 return false;
1059 }
1060 if (!Value.hasArrayFiller())
1061 return true;
1062 return CheckConstantExpression(Info, DiagLoc, EltTy,
1063 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001064 }
Richard Smith83587db2012-02-15 02:18:13 +00001065 if (Value.isUnion() && Value.getUnionField()) {
1066 return CheckConstantExpression(Info, DiagLoc,
1067 Value.getUnionField()->getType(),
1068 Value.getUnionValue());
1069 }
1070 if (Value.isStruct()) {
1071 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1072 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1073 unsigned BaseIndex = 0;
1074 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1075 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1076 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1077 Value.getStructBase(BaseIndex)))
1078 return false;
1079 }
1080 }
1081 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1082 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001083 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1084 Value.getStructField(I->getFieldIndex())))
Richard Smith83587db2012-02-15 02:18:13 +00001085 return false;
1086 }
1087 }
1088
1089 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001090 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001091 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001092 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1093 }
1094
1095 // Everything else is fine.
1096 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001097}
1098
Richard Smith9e36b532011-10-31 05:11:32 +00001099const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001100 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001101}
1102
1103static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001104 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001105}
1106
Richard Smith65ac5982011-11-01 21:06:14 +00001107static bool IsWeakLValue(const LValue &Value) {
1108 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001109 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001110}
1111
Richard Smith1aa0be82012-03-03 22:46:17 +00001112static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001113 // A null base expression indicates a null pointer. These are always
1114 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001115 if (!Value.getLValueBase()) {
1116 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001117 return true;
1118 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001119
Richard Smithe24f5fc2011-11-17 22:56:20 +00001120 // We have a non-null base. These are generally known to be true, but if it's
1121 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001122 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001123 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001124 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001125}
1126
Richard Smith1aa0be82012-03-03 22:46:17 +00001127static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001128 switch (Val.getKind()) {
1129 case APValue::Uninitialized:
1130 return false;
1131 case APValue::Int:
1132 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001133 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001134 case APValue::Float:
1135 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001136 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001137 case APValue::ComplexInt:
1138 Result = Val.getComplexIntReal().getBoolValue() ||
1139 Val.getComplexIntImag().getBoolValue();
1140 return true;
1141 case APValue::ComplexFloat:
1142 Result = !Val.getComplexFloatReal().isZero() ||
1143 !Val.getComplexFloatImag().isZero();
1144 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001145 case APValue::LValue:
1146 return EvalPointerValueAsBool(Val, Result);
1147 case APValue::MemberPointer:
1148 Result = Val.getMemberPointerDecl();
1149 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001150 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001151 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001152 case APValue::Struct:
1153 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001154 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001155 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001156 }
1157
Richard Smithc49bd112011-10-28 17:51:58 +00001158 llvm_unreachable("unknown APValue kind");
1159}
1160
1161static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1162 EvalInfo &Info) {
1163 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001164 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001165 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001166 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001167 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001168}
1169
Richard Smithc1c5f272011-12-13 06:39:58 +00001170template<typename T>
Eli Friedman26dc97c2012-07-17 21:03:05 +00001171static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +00001172 const T &SrcValue, QualType DestType) {
Eli Friedman26dc97c2012-07-17 21:03:05 +00001173 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001174 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001175}
1176
1177static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1178 QualType SrcType, const APFloat &Value,
1179 QualType DestType, APSInt &Result) {
1180 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001181 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001182 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Richard Smithc1c5f272011-12-13 06:39:58 +00001184 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001185 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001186 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1187 & APFloat::opInvalidOp)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001188 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001189 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001190}
1191
Richard Smithc1c5f272011-12-13 06:39:58 +00001192static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1193 QualType SrcType, QualType DestType,
1194 APFloat &Result) {
1195 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001196 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001197 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1198 APFloat::rmNearestTiesToEven, &ignored)
1199 & APFloat::opOverflow)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001200 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001201 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001202}
1203
Richard Smithf72fccf2012-01-30 22:27:01 +00001204static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1205 QualType DestType, QualType SrcType,
1206 APSInt &Value) {
1207 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001208 APSInt Result = Value;
1209 // Figure out if this is a truncate, extend or noop cast.
1210 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001211 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001212 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001213 return Result;
1214}
1215
Richard Smithc1c5f272011-12-13 06:39:58 +00001216static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1217 QualType SrcType, const APSInt &Value,
1218 QualType DestType, APFloat &Result) {
1219 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1220 if (Result.convertFromAPInt(Value, Value.isSigned(),
1221 APFloat::rmNearestTiesToEven)
1222 & APFloat::opOverflow)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001223 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001224 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001225}
1226
Eli Friedmane6a24e82011-12-22 03:51:45 +00001227static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1228 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001229 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001230 if (!Evaluate(SVal, Info, E))
1231 return false;
1232 if (SVal.isInt()) {
1233 Res = SVal.getInt();
1234 return true;
1235 }
1236 if (SVal.isFloat()) {
1237 Res = SVal.getFloat().bitcastToAPInt();
1238 return true;
1239 }
1240 if (SVal.isVector()) {
1241 QualType VecTy = E->getType();
1242 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1243 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1244 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1245 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1246 Res = llvm::APInt::getNullValue(VecSize);
1247 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1248 APValue &Elt = SVal.getVectorElt(i);
1249 llvm::APInt EltAsInt;
1250 if (Elt.isInt()) {
1251 EltAsInt = Elt.getInt();
1252 } else if (Elt.isFloat()) {
1253 EltAsInt = Elt.getFloat().bitcastToAPInt();
1254 } else {
1255 // Don't try to handle vectors of anything other than int or float
1256 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001257 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001258 return false;
1259 }
1260 unsigned BaseEltSize = EltAsInt.getBitWidth();
1261 if (BigEndian)
1262 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1263 else
1264 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1265 }
1266 return true;
1267 }
1268 // Give up if the input isn't an int, float, or vector. For example, we
1269 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001270 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001271 return false;
1272}
1273
Richard Smithb4e85ed2012-01-06 16:39:00 +00001274/// Cast an lvalue referring to a base subobject to a derived class, by
1275/// truncating the lvalue's path to the given length.
1276static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1277 const RecordDecl *TruncatedType,
1278 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001279 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001280
1281 // Check we actually point to a derived class object.
1282 if (TruncatedElements == D.Entries.size())
1283 return true;
1284 assert(TruncatedElements >= D.MostDerivedPathLength &&
1285 "not casting to a derived class");
1286 if (!Result.checkSubobject(Info, E, CSK_Derived))
1287 return false;
1288
1289 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001290 const RecordDecl *RD = TruncatedType;
1291 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCall8d59dee2012-05-01 00:38:49 +00001292 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001293 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1294 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001295 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001296 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001297 else
Richard Smith180f4792011-11-10 06:34:14 +00001298 Result.Offset -= Layout.getBaseClassOffset(Base);
1299 RD = Base;
1300 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001301 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001302 return true;
1303}
1304
John McCall8d59dee2012-05-01 00:38:49 +00001305static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001306 const CXXRecordDecl *Derived,
1307 const CXXRecordDecl *Base,
1308 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001309 if (!RL) {
1310 if (Derived->isInvalidDecl()) return false;
1311 RL = &Info.Ctx.getASTRecordLayout(Derived);
1312 }
1313
Richard Smith180f4792011-11-10 06:34:14 +00001314 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001315 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCall8d59dee2012-05-01 00:38:49 +00001316 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001317}
1318
Richard Smithb4e85ed2012-01-06 16:39:00 +00001319static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001320 const CXXRecordDecl *DerivedDecl,
1321 const CXXBaseSpecifier *Base) {
1322 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1323
John McCall8d59dee2012-05-01 00:38:49 +00001324 if (!Base->isVirtual())
1325 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001326
Richard Smithb4e85ed2012-01-06 16:39:00 +00001327 SubobjectDesignator &D = Obj.Designator;
1328 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001329 return false;
1330
Richard Smithb4e85ed2012-01-06 16:39:00 +00001331 // Extract most-derived object and corresponding type.
1332 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1333 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1334 return false;
1335
1336 // Find the virtual base class.
John McCall8d59dee2012-05-01 00:38:49 +00001337 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001338 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1339 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001340 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001341 return true;
1342}
1343
1344/// Update LVal to refer to the given field, which must be a member of the type
1345/// currently described by LVal.
John McCall8d59dee2012-05-01 00:38:49 +00001346static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001347 const FieldDecl *FD,
1348 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001349 if (!RL) {
1350 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001351 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCall8d59dee2012-05-01 00:38:49 +00001352 }
Richard Smith180f4792011-11-10 06:34:14 +00001353
1354 unsigned I = FD->getFieldIndex();
1355 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001356 LVal.addDecl(Info, E, FD);
John McCall8d59dee2012-05-01 00:38:49 +00001357 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001358}
1359
Richard Smithd9b02e72012-01-25 22:15:11 +00001360/// Update LVal to refer to the given indirect field.
John McCall8d59dee2012-05-01 00:38:49 +00001361static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smithd9b02e72012-01-25 22:15:11 +00001362 LValue &LVal,
1363 const IndirectFieldDecl *IFD) {
1364 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1365 CE = IFD->chain_end(); C != CE; ++C)
John McCall8d59dee2012-05-01 00:38:49 +00001366 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1367 return false;
1368 return true;
Richard Smithd9b02e72012-01-25 22:15:11 +00001369}
1370
Richard Smith180f4792011-11-10 06:34:14 +00001371/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001372static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1373 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001374 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1375 // extension.
1376 if (Type->isVoidType() || Type->isFunctionType()) {
1377 Size = CharUnits::One();
1378 return true;
1379 }
1380
1381 if (!Type->isConstantSizeType()) {
1382 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001383 // FIXME: Better diagnostic.
1384 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001385 return false;
1386 }
1387
1388 Size = Info.Ctx.getTypeSizeInChars(Type);
1389 return true;
1390}
1391
1392/// Update a pointer value to model pointer arithmetic.
1393/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001394/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001395/// \param LVal - The pointer value to be updated.
1396/// \param EltTy - The pointee type represented by LVal.
1397/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001398static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1399 LValue &LVal, QualType EltTy,
1400 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001401 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001402 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001403 return false;
1404
1405 // Compute the new offset in the appropriate width.
1406 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001407 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001408 return true;
1409}
1410
Richard Smith86024012012-02-18 22:04:06 +00001411/// Update an lvalue to refer to a component of a complex number.
1412/// \param Info - Information about the ongoing evaluation.
1413/// \param LVal - The lvalue to be updated.
1414/// \param EltTy - The complex number's component type.
1415/// \param Imag - False for the real component, true for the imaginary.
1416static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1417 LValue &LVal, QualType EltTy,
1418 bool Imag) {
1419 if (Imag) {
1420 CharUnits SizeOfComponent;
1421 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1422 return false;
1423 LVal.Offset += SizeOfComponent;
1424 }
1425 LVal.addComplex(Info, E, EltTy, Imag);
1426 return true;
1427}
1428
Richard Smith03f96112011-10-24 17:54:18 +00001429/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001430static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1431 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001432 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001433 // If this is a parameter to an active constexpr function call, perform
1434 // argument substitution.
1435 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001436 // Assume arguments of a potential constant expression are unknown
1437 // constant expressions.
1438 if (Info.CheckingPotentialConstantExpression)
1439 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001440 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001441 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001442 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001443 }
Richard Smith177dce72011-11-01 16:57:24 +00001444 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1445 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001446 }
Richard Smith03f96112011-10-24 17:54:18 +00001447
Richard Smith099e7f62011-12-19 06:19:21 +00001448 // Dig out the initializer, and use the declaration which it's attached to.
1449 const Expr *Init = VD->getAnyInitializer(VD);
1450 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001451 // If we're checking a potential constant expression, the variable could be
1452 // initialized later.
1453 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001454 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001455 return false;
1456 }
1457
Richard Smith180f4792011-11-10 06:34:14 +00001458 // If we're currently evaluating the initializer of this declaration, use that
1459 // in-flight value.
1460 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001461 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001462 return !Result.isUninit();
1463 }
1464
Richard Smith65ac5982011-11-01 21:06:14 +00001465 // Never evaluate the initializer of a weak variable. We can't be sure that
1466 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001467 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001468 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001469 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001470 }
Richard Smith65ac5982011-11-01 21:06:14 +00001471
Richard Smith099e7f62011-12-19 06:19:21 +00001472 // Check that we can fold the initializer. In C++, we will have already done
1473 // this in the cases where it matters for conformance.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001474 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00001475 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001476 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001477 Notes.size() + 1) << VD;
1478 Info.Note(VD->getLocation(), diag::note_declared_at);
1479 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001480 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001481 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001482 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001483 Notes.size() + 1) << VD;
1484 Info.Note(VD->getLocation(), diag::note_declared_at);
1485 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001486 }
Richard Smith03f96112011-10-24 17:54:18 +00001487
Richard Smith1aa0be82012-03-03 22:46:17 +00001488 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001489 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001490}
1491
Richard Smithc49bd112011-10-28 17:51:58 +00001492static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001493 Qualifiers Quals = T.getQualifiers();
1494 return Quals.hasConst() && !Quals.hasVolatile();
1495}
1496
Richard Smith59efe262011-11-11 04:05:33 +00001497/// Get the base index of the given base class within an APValue representing
1498/// the given derived class.
1499static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1500 const CXXRecordDecl *Base) {
1501 Base = Base->getCanonicalDecl();
1502 unsigned Index = 0;
1503 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1504 E = Derived->bases_end(); I != E; ++I, ++Index) {
1505 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1506 return Index;
1507 }
1508
1509 llvm_unreachable("base class missing from derived class's bases list");
1510}
1511
Richard Smithfe587202012-04-15 02:50:59 +00001512/// Extract the value of a character from a string literal. CharType is used to
1513/// determine the expected signedness of the result -- a string literal used to
1514/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1515/// of the wrong signedness.
Richard Smithf3908f22012-02-17 03:35:37 +00001516static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smithfe587202012-04-15 02:50:59 +00001517 uint64_t Index, QualType CharType) {
Richard Smithf3908f22012-02-17 03:35:37 +00001518 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1519 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1520 assert(S && "unexpected string literal expression kind");
Richard Smithfe587202012-04-15 02:50:59 +00001521 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smithf3908f22012-02-17 03:35:37 +00001522
1523 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smithfe587202012-04-15 02:50:59 +00001524 CharType->isUnsignedIntegerType());
Richard Smithf3908f22012-02-17 03:35:37 +00001525 if (Index < S->getLength())
1526 Value = S->getCodeUnit(Index);
1527 return Value;
1528}
1529
Richard Smithcc5d4f62011-11-07 09:22:26 +00001530/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001531static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001532 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001533 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001534 if (Sub.Invalid)
1535 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001536 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001537 if (Sub.isOnePastTheEnd()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001538 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001539 (unsigned)diag::note_constexpr_read_past_end :
1540 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001541 return false;
1542 }
Richard Smithf64699e2011-11-11 08:28:03 +00001543 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001544 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001545 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1546 // This object might be initialized later.
1547 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001548
Richard Smith0069b842012-03-10 00:28:11 +00001549 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001550 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001551 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001552 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001553 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001554 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001555 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001556 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001557 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001558 // Note, it should not be possible to form a pointer with a valid
1559 // designator which points more than one past the end of the array.
Richard Smith80ad52f2013-01-02 11:42:31 +00001560 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001561 (unsigned)diag::note_constexpr_read_past_end :
1562 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001563 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001564 }
Richard Smithf3908f22012-02-17 03:35:37 +00001565 // An array object is represented as either an Array APValue or as an
1566 // LValue which refers to a string literal.
1567 if (O->isLValue()) {
1568 assert(I == N - 1 && "extracting subobject of character?");
1569 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001570 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithfe587202012-04-15 02:50:59 +00001571 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smithf3908f22012-02-17 03:35:37 +00001572 return true;
1573 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001574 O = &O->getArrayInitializedElt(Index);
1575 else
1576 O = &O->getArrayFiller();
1577 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001578 } else if (ObjType->isAnyComplexType()) {
1579 // Next subobject is a complex number.
1580 uint64_t Index = Sub.Entries[I].ArrayIndex;
1581 if (Index > 1) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001582 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Richard Smith86024012012-02-18 22:04:06 +00001583 (unsigned)diag::note_constexpr_read_past_end :
1584 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1585 return false;
1586 }
1587 assert(I == N - 1 && "extracting subobject of scalar?");
1588 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001589 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001590 : O->getComplexIntReal());
1591 } else {
1592 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001593 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001594 : O->getComplexFloatReal());
1595 }
1596 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001597 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001598 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001599 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001600 << Field;
1601 Info.Note(Field->getLocation(), diag::note_declared_at);
1602 return false;
1603 }
1604
Richard Smith180f4792011-11-10 06:34:14 +00001605 // Next subobject is a class, struct or union field.
1606 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1607 if (RD->isUnion()) {
1608 const FieldDecl *UnionField = O->getUnionField();
1609 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001610 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001611 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001612 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001613 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001614 }
Richard Smith180f4792011-11-10 06:34:14 +00001615 O = &O->getUnionValue();
1616 } else
1617 O = &O->getStructField(Field->getFieldIndex());
1618 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001619
1620 if (ObjType.isVolatileQualified()) {
1621 if (Info.getLangOpts().CPlusPlus) {
1622 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001623 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001624 << 2 << Field;
1625 Info.Note(Field->getLocation(), diag::note_declared_at);
1626 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001627 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001628 }
1629 return false;
1630 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001631 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001632 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001633 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1634 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1635 O = &O->getStructBase(getBaseIndex(Derived, Base));
1636 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001637 }
Richard Smith180f4792011-11-10 06:34:14 +00001638
Richard Smithf48fdb02011-12-09 22:58:01 +00001639 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001640 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001641 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001642 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001643 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001644 }
1645
Richard Smith0069b842012-03-10 00:28:11 +00001646 // This may look super-stupid, but it serves an important purpose: if we just
1647 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1648 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1649 // object, which is destroyed by Tmp's destructor.
1650 APValue Tmp;
1651 O->swap(Tmp);
1652 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001653 return true;
1654}
1655
Richard Smithf15fda02012-02-02 01:16:57 +00001656/// Find the position where two subobject designators diverge, or equivalently
1657/// the length of the common initial subsequence.
1658static unsigned FindDesignatorMismatch(QualType ObjType,
1659 const SubobjectDesignator &A,
1660 const SubobjectDesignator &B,
1661 bool &WasArrayIndex) {
1662 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1663 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001664 if (!ObjType.isNull() &&
1665 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001666 // Next subobject is an array element.
1667 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1668 WasArrayIndex = true;
1669 return I;
1670 }
Richard Smith86024012012-02-18 22:04:06 +00001671 if (ObjType->isAnyComplexType())
1672 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1673 else
1674 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001675 } else {
1676 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1677 WasArrayIndex = false;
1678 return I;
1679 }
1680 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1681 // Next subobject is a field.
1682 ObjType = FD->getType();
1683 else
1684 // Next subobject is a base class.
1685 ObjType = QualType();
1686 }
1687 }
1688 WasArrayIndex = false;
1689 return I;
1690}
1691
1692/// Determine whether the given subobject designators refer to elements of the
1693/// same array object.
1694static bool AreElementsOfSameArray(QualType ObjType,
1695 const SubobjectDesignator &A,
1696 const SubobjectDesignator &B) {
1697 if (A.Entries.size() != B.Entries.size())
1698 return false;
1699
1700 bool IsArray = A.MostDerivedArraySize != 0;
1701 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1702 // A is a subobject of the array element.
1703 return false;
1704
1705 // If A (and B) designates an array element, the last entry will be the array
1706 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1707 // of length 1' case, and the entire path must match.
1708 bool WasArrayIndex;
1709 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1710 return CommonLength >= A.Entries.size() - IsArray;
1711}
1712
Richard Smith180f4792011-11-10 06:34:14 +00001713/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1714/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1715/// for looking up the glvalue referred to by an entity of reference type.
1716///
1717/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001718/// \param Conv - The expression for which we are performing the conversion.
1719/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001720/// \param Type - The type we expect this conversion to produce, before
1721/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001722/// \param LVal - The glvalue on which we are attempting to perform this action.
1723/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001724static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1725 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001726 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001727 if (LVal.Designator.Invalid)
1728 // A diagnostic will have already been produced.
1729 return false;
1730
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001731 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001732
Richard Smithf48fdb02011-12-09 22:58:01 +00001733 if (!LVal.Base) {
1734 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001735 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001736 return false;
1737 }
1738
Richard Smith83587db2012-02-15 02:18:13 +00001739 CallStackFrame *Frame = 0;
1740 if (LVal.CallIndex) {
1741 Frame = Info.getCallFrame(LVal.CallIndex);
1742 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001743 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001744 NoteLValueLocation(Info, LVal.Base);
1745 return false;
1746 }
1747 }
1748
Richard Smith7098cbd2011-12-21 05:04:46 +00001749 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1750 // is not a constant expression (even if the object is non-volatile). We also
1751 // apply this rule to C++98, in order to conform to the expected 'volatile'
1752 // semantics.
1753 if (Type.isVolatileQualified()) {
1754 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001755 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001756 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001757 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001758 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001759 }
Richard Smithc49bd112011-10-28 17:51:58 +00001760
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001761 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001762 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1763 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001764 // expressions are constant expressions too. Inside constexpr functions,
1765 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001766 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001767 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregord2008e22012-04-06 22:40:38 +00001768 if (VD) {
1769 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1770 VD = VDef;
1771 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001772 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001773 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001774 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001775 }
1776
Richard Smith7098cbd2011-12-21 05:04:46 +00001777 // DR1313: If the object is volatile-qualified but the glvalue was not,
1778 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001779 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001780 if (VT.isVolatileQualified()) {
1781 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001782 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001783 Info.Note(VD->getLocation(), diag::note_declared_at);
1784 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001785 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001786 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001787 return false;
1788 }
1789
1790 if (!isa<ParmVarDecl>(VD)) {
1791 if (VD->isConstexpr()) {
1792 // OK, we can read this variable.
1793 } else if (VT->isIntegralOrEnumerationType()) {
1794 if (!VT.isConstQualified()) {
1795 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001796 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001797 Info.Note(VD->getLocation(), diag::note_declared_at);
1798 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001799 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001800 }
1801 return false;
1802 }
1803 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1804 // We support folding of const floating-point types, in order to make
1805 // static const data members of such types (supported as an extension)
1806 // more useful.
Richard Smith80ad52f2013-01-02 11:42:31 +00001807 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001808 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001809 Info.Note(VD->getLocation(), diag::note_declared_at);
1810 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001811 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001812 }
1813 } else {
1814 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smith80ad52f2013-01-02 11:42:31 +00001815 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001816 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001817 Info.Note(VD->getLocation(), diag::note_declared_at);
1818 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001819 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001820 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001821 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001822 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001823 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001824
Richard Smithf48fdb02011-12-09 22:58:01 +00001825 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001826 return false;
1827
Richard Smith47a1eed2011-10-29 20:57:55 +00001828 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001829 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001830
1831 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1832 // conversion. This happens when the declaration and the lvalue should be
1833 // considered synonymous, for instance when initializing an array of char
1834 // from a string literal. Continue as if the initializer lvalue was the
1835 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001836 assert(RVal.getLValueOffset().isZero() &&
1837 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001838 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001839
1840 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1841 Frame = Info.getCallFrame(CallIndex);
1842 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001843 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001844 NoteLValueLocation(Info, RVal.getLValueBase());
1845 return false;
1846 }
1847 } else {
1848 Frame = 0;
1849 }
Richard Smithc49bd112011-10-28 17:51:58 +00001850 }
1851
Richard Smith7098cbd2011-12-21 05:04:46 +00001852 // Volatile temporary objects cannot be read in constant expressions.
1853 if (Base->getType().isVolatileQualified()) {
1854 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001855 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001856 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1857 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001858 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001859 }
1860 return false;
1861 }
1862
Richard Smithcc5d4f62011-11-07 09:22:26 +00001863 if (Frame) {
1864 // If this is a temporary expression with a nontrivial initializer, grab the
1865 // value from the relevant stack frame.
1866 RVal = Frame->Temporaries[Base];
1867 } else if (const CompoundLiteralExpr *CLE
1868 = dyn_cast<CompoundLiteralExpr>(Base)) {
1869 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1870 // initializer until now for such expressions. Such an expression can't be
1871 // an ICE in C, so this only matters for fold.
1872 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1873 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1874 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001875 } else if (isa<StringLiteral>(Base)) {
1876 // We represent a string literal array as an lvalue pointing at the
1877 // corresponding expression, rather than building an array of chars.
1878 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001879 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001880 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001881 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001882 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001883 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001884
Richard Smithf48fdb02011-12-09 22:58:01 +00001885 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1886 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001887}
1888
Richard Smith59efe262011-11-11 04:05:33 +00001889/// Build an lvalue for the object argument of a member function call.
1890static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1891 LValue &This) {
1892 if (Object->getType()->isPointerType())
1893 return EvaluatePointer(Object, This, Info);
1894
1895 if (Object->isGLValue())
1896 return EvaluateLValue(Object, This, Info);
1897
Richard Smithe24f5fc2011-11-17 22:56:20 +00001898 if (Object->getType()->isLiteralType())
1899 return EvaluateTemporary(Object, This, Info);
1900
1901 return false;
1902}
1903
1904/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1905/// lvalue referring to the result.
1906///
1907/// \param Info - Information about the ongoing evaluation.
1908/// \param BO - The member pointer access operation.
1909/// \param LV - Filled in with a reference to the resulting object.
1910/// \param IncludeMember - Specifies whether the member itself is included in
1911/// the resulting LValue subobject designator. This is not possible when
1912/// creating a bound member function.
1913/// \return The field or method declaration to which the member pointer refers,
1914/// or 0 if evaluation fails.
1915static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1916 const BinaryOperator *BO,
1917 LValue &LV,
1918 bool IncludeMember = true) {
1919 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1920
Richard Smith745f5142012-01-27 01:14:48 +00001921 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1922 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001923 return 0;
1924
1925 MemberPtr MemPtr;
1926 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1927 return 0;
1928
1929 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1930 // member value, the behavior is undefined.
1931 if (!MemPtr.getDecl())
1932 return 0;
1933
Richard Smith745f5142012-01-27 01:14:48 +00001934 if (!EvalObjOK)
1935 return 0;
1936
Richard Smithe24f5fc2011-11-17 22:56:20 +00001937 if (MemPtr.isDerivedMember()) {
1938 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001939 // The end of the derived-to-base path for the base object must match the
1940 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001941 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001942 LV.Designator.Entries.size())
1943 return 0;
1944 unsigned PathLengthToMember =
1945 LV.Designator.Entries.size() - MemPtr.Path.size();
1946 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1947 const CXXRecordDecl *LVDecl = getAsBaseClass(
1948 LV.Designator.Entries[PathLengthToMember + I]);
1949 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1950 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1951 return 0;
1952 }
1953
1954 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001955 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1956 PathLengthToMember))
1957 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001958 } else if (!MemPtr.Path.empty()) {
1959 // Extend the LValue path with the member pointer's path.
1960 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1961 MemPtr.Path.size() + IncludeMember);
1962
1963 // Walk down to the appropriate base class.
1964 QualType LVType = BO->getLHS()->getType();
1965 if (const PointerType *PT = LVType->getAs<PointerType>())
1966 LVType = PT->getPointeeType();
1967 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1968 assert(RD && "member pointer access on non-class-type expression");
1969 // The first class in the path is that of the lvalue.
1970 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1971 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCall8d59dee2012-05-01 00:38:49 +00001972 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1973 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001974 RD = Base;
1975 }
1976 // Finally cast to the class containing the member.
John McCall8d59dee2012-05-01 00:38:49 +00001977 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1978 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001979 }
1980
1981 // Add the member. Note that we cannot build bound member functions here.
1982 if (IncludeMember) {
John McCall8d59dee2012-05-01 00:38:49 +00001983 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
1984 if (!HandleLValueMember(Info, BO, LV, FD))
1985 return 0;
1986 } else if (const IndirectFieldDecl *IFD =
1987 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
1988 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
1989 return 0;
1990 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00001991 llvm_unreachable("can't construct reference to bound member function");
John McCall8d59dee2012-05-01 00:38:49 +00001992 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001993 }
1994
1995 return MemPtr.getDecl();
1996}
1997
1998/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1999/// the provided lvalue, which currently refers to the base object.
2000static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2001 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002002 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002003 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002004 return false;
2005
Richard Smithb4e85ed2012-01-06 16:39:00 +00002006 QualType TargetQT = E->getType();
2007 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2008 TargetQT = PT->getPointeeType();
2009
2010 // Check this cast lands within the final derived-to-base subobject path.
2011 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002012 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002013 << D.MostDerivedType << TargetQT;
2014 return false;
2015 }
2016
Richard Smithe24f5fc2011-11-17 22:56:20 +00002017 // Check the type of the final cast. We don't need to check the path,
2018 // since a cast can only be formed if the path is unique.
2019 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002020 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2021 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002022 if (NewEntriesSize == D.MostDerivedPathLength)
2023 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2024 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002025 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002026 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002027 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002028 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002029 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002030 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002031
2032 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002033 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002034}
2035
Mike Stumpc4c90452009-10-27 22:09:17 +00002036namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002037enum EvalStmtResult {
2038 /// Evaluation failed.
2039 ESR_Failed,
2040 /// Hit a 'return' statement.
2041 ESR_Returned,
2042 /// Evaluation succeeded.
2043 ESR_Succeeded
2044};
2045}
2046
2047// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002048static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002049 const Stmt *S) {
2050 switch (S->getStmtClass()) {
2051 default:
2052 return ESR_Failed;
2053
2054 case Stmt::NullStmtClass:
2055 case Stmt::DeclStmtClass:
2056 return ESR_Succeeded;
2057
Richard Smithc1c5f272011-12-13 06:39:58 +00002058 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002059 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002060 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002061 return ESR_Failed;
2062 return ESR_Returned;
2063 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002064
2065 case Stmt::CompoundStmtClass: {
2066 const CompoundStmt *CS = cast<CompoundStmt>(S);
2067 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2068 BE = CS->body_end(); BI != BE; ++BI) {
2069 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2070 if (ESR != ESR_Succeeded)
2071 return ESR;
2072 }
2073 return ESR_Succeeded;
2074 }
2075 }
2076}
2077
Richard Smith61802452011-12-22 02:22:31 +00002078/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2079/// default constructor. If so, we'll fold it whether or not it's marked as
2080/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2081/// so we need special handling.
2082static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002083 const CXXConstructorDecl *CD,
2084 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002085 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2086 return false;
2087
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002088 // Value-initialization does not call a trivial default constructor, so such a
2089 // call is a core constant expression whether or not the constructor is
2090 // constexpr.
2091 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith80ad52f2013-01-02 11:42:31 +00002092 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002093 // FIXME: If DiagDecl is an implicitly-declared special member function,
2094 // we should be much more explicit about why it's not constexpr.
2095 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2096 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2097 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002098 } else {
2099 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2100 }
2101 }
2102 return true;
2103}
2104
Richard Smithc1c5f272011-12-13 06:39:58 +00002105/// CheckConstexprFunction - Check that a function can be called in a constant
2106/// expression.
2107static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2108 const FunctionDecl *Declaration,
2109 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002110 // Potential constant expressions can contain calls to declared, but not yet
2111 // defined, constexpr functions.
2112 if (Info.CheckingPotentialConstantExpression && !Definition &&
2113 Declaration->isConstexpr())
2114 return false;
2115
Richard Smithc1c5f272011-12-13 06:39:58 +00002116 // Can we evaluate this function call?
2117 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2118 return true;
2119
Richard Smith80ad52f2013-01-02 11:42:31 +00002120 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithc1c5f272011-12-13 06:39:58 +00002121 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002122 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2123 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002124 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2125 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2126 << DiagDecl;
2127 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2128 } else {
2129 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2130 }
2131 return false;
2132}
2133
Richard Smith180f4792011-11-10 06:34:14 +00002134namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002135typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002136}
2137
2138/// EvaluateArgs - Evaluate the arguments to a function call.
2139static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2140 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002141 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002142 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002143 I != E; ++I) {
2144 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2145 // If we're checking for a potential constant expression, evaluate all
2146 // initializers even if some of them fail.
2147 if (!Info.keepEvaluatingAfterFailure())
2148 return false;
2149 Success = false;
2150 }
2151 }
2152 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002153}
2154
Richard Smithd0dccea2011-10-28 22:34:42 +00002155/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002156static bool HandleFunctionCall(SourceLocation CallLoc,
2157 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002158 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002159 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002160 ArgVector ArgValues(Args.size());
2161 if (!EvaluateArgs(Args, ArgValues, Info))
2162 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002163
Richard Smith745f5142012-01-27 01:14:48 +00002164 if (!Info.CheckCallLimit(CallLoc))
2165 return false;
2166
2167 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002168 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2169}
2170
Richard Smith180f4792011-11-10 06:34:14 +00002171/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002172static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002173 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002174 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002175 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002176 ArgVector ArgValues(Args.size());
2177 if (!EvaluateArgs(Args, ArgValues, Info))
2178 return false;
2179
Richard Smith745f5142012-01-27 01:14:48 +00002180 if (!Info.CheckCallLimit(CallLoc))
2181 return false;
2182
Richard Smith86c3ae42012-02-13 03:54:03 +00002183 const CXXRecordDecl *RD = Definition->getParent();
2184 if (RD->getNumVBases()) {
2185 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2186 return false;
2187 }
2188
Richard Smith745f5142012-01-27 01:14:48 +00002189 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002190
2191 // If it's a delegating constructor, just delegate.
2192 if (Definition->isDelegatingConstructor()) {
2193 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002194 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002195 }
2196
Richard Smith610a60c2012-01-10 04:32:03 +00002197 // For a trivial copy or move constructor, perform an APValue copy. This is
2198 // essential for unions, where the operations performed by the constructor
2199 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002200 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002201 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2202 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002203 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002204 RHS.setFrom(Info.Ctx, ArgValues[0]);
2205 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2206 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002207 }
2208
2209 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002210 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002211 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2212 std::distance(RD->field_begin(), RD->field_end()));
2213
John McCall8d59dee2012-05-01 00:38:49 +00002214 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00002215 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2216
Richard Smith745f5142012-01-27 01:14:48 +00002217 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002218 unsigned BasesSeen = 0;
2219#ifndef NDEBUG
2220 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2221#endif
2222 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2223 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002224 LValue Subobject = This;
2225 APValue *Value = &Result;
2226
2227 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002228 if ((*I)->isBaseInitializer()) {
2229 QualType BaseType((*I)->getBaseClass(), 0);
2230#ifndef NDEBUG
2231 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002232 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002233 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2234 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2235 "base class initializers not in expected order");
2236 ++BaseIt;
2237#endif
John McCall8d59dee2012-05-01 00:38:49 +00002238 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2239 BaseType->getAsCXXRecordDecl(), &Layout))
2240 return false;
Richard Smith745f5142012-01-27 01:14:48 +00002241 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002242 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCall8d59dee2012-05-01 00:38:49 +00002243 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2244 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002245 if (RD->isUnion()) {
2246 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002247 Value = &Result.getUnionValue();
2248 } else {
2249 Value = &Result.getStructField(FD->getFieldIndex());
2250 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002251 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002252 // Walk the indirect field decl's chain to find the object to initialize,
2253 // and make sure we've initialized every step along it.
2254 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2255 CE = IFD->chain_end();
2256 C != CE; ++C) {
2257 FieldDecl *FD = cast<FieldDecl>(*C);
2258 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2259 // Switch the union field if it differs. This happens if we had
2260 // preceding zero-initialization, and we're now initializing a union
2261 // subobject other than the first.
2262 // FIXME: In this case, the values of the other subobjects are
2263 // specified, since zero-initialization sets all padding bits to zero.
2264 if (Value->isUninit() ||
2265 (Value->isUnion() && Value->getUnionField() != FD)) {
2266 if (CD->isUnion())
2267 *Value = APValue(FD);
2268 else
2269 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2270 std::distance(CD->field_begin(), CD->field_end()));
2271 }
John McCall8d59dee2012-05-01 00:38:49 +00002272 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2273 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002274 if (CD->isUnion())
2275 Value = &Value->getUnionValue();
2276 else
2277 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002278 }
Richard Smith180f4792011-11-10 06:34:14 +00002279 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002280 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002281 }
Richard Smith745f5142012-01-27 01:14:48 +00002282
Richard Smith83587db2012-02-15 02:18:13 +00002283 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2284 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002285 ? CCEK_Constant : CCEK_MemberInit)) {
2286 // If we're checking for a potential constant expression, evaluate all
2287 // initializers even if some of them fail.
2288 if (!Info.keepEvaluatingAfterFailure())
2289 return false;
2290 Success = false;
2291 }
Richard Smith180f4792011-11-10 06:34:14 +00002292 }
2293
Richard Smith745f5142012-01-27 01:14:48 +00002294 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002295}
2296
Eli Friedman4efaa272008-11-12 09:44:48 +00002297//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002298// Generic Evaluation
2299//===----------------------------------------------------------------------===//
2300namespace {
2301
Richard Smithf48fdb02011-12-09 22:58:01 +00002302// FIXME: RetTy is always bool. Remove it.
2303template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002304class ExprEvaluatorBase
2305 : public ConstStmtVisitor<Derived, RetTy> {
2306private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002307 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002308 return static_cast<Derived*>(this)->Success(V, E);
2309 }
Richard Smith51201882011-12-30 21:15:51 +00002310 RetTy DerivedZeroInitialization(const Expr *E) {
2311 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002312 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002313
Richard Smith74e1ad92012-02-16 02:46:34 +00002314 // Check whether a conditional operator with a non-constant condition is a
2315 // potential constant expression. If neither arm is a potential constant
2316 // expression, then the conditional operator is not either.
2317 template<typename ConditionalOperator>
2318 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2319 assert(Info.CheckingPotentialConstantExpression);
2320
2321 // Speculatively evaluate both arms.
2322 {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002323 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith74e1ad92012-02-16 02:46:34 +00002324 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2325
2326 StmtVisitorTy::Visit(E->getFalseExpr());
2327 if (Diag.empty())
2328 return;
2329
2330 Diag.clear();
2331 StmtVisitorTy::Visit(E->getTrueExpr());
2332 if (Diag.empty())
2333 return;
2334 }
2335
2336 Error(E, diag::note_constexpr_conditional_never_const);
2337 }
2338
2339
2340 template<typename ConditionalOperator>
2341 bool HandleConditionalOperator(const ConditionalOperator *E) {
2342 bool BoolResult;
2343 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2344 if (Info.CheckingPotentialConstantExpression)
2345 CheckPotentialConstantConditional(E);
2346 return false;
2347 }
2348
2349 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2350 return StmtVisitorTy::Visit(EvalExpr);
2351 }
2352
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002353protected:
2354 EvalInfo &Info;
2355 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2356 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2357
Richard Smithdd1f29b2011-12-12 09:28:41 +00002358 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002359 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002360 }
2361
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00002362 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2363
2364public:
2365 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2366
2367 EvalInfo &getEvalInfo() { return Info; }
2368
Richard Smithf48fdb02011-12-09 22:58:01 +00002369 /// Report an evaluation error. This should only be called when an error is
2370 /// first discovered. When propagating an error, just return false.
2371 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002372 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002373 return false;
2374 }
2375 bool Error(const Expr *E) {
2376 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2377 }
2378
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002379 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002380 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002381 }
2382 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002383 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002384 }
2385
2386 RetTy VisitParenExpr(const ParenExpr *E)
2387 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2388 RetTy VisitUnaryExtension(const UnaryOperator *E)
2389 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2390 RetTy VisitUnaryPlus(const UnaryOperator *E)
2391 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2392 RetTy VisitChooseExpr(const ChooseExpr *E)
2393 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2394 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2395 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002396 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2397 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002398 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2399 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002400 // We cannot create any objects for which cleanups are required, so there is
2401 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2402 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2403 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002404
Richard Smithc216a012011-12-12 12:46:16 +00002405 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2406 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2407 return static_cast<Derived*>(this)->VisitCastExpr(E);
2408 }
2409 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2410 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2411 return static_cast<Derived*>(this)->VisitCastExpr(E);
2412 }
2413
Richard Smithe24f5fc2011-11-17 22:56:20 +00002414 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2415 switch (E->getOpcode()) {
2416 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002417 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002418
2419 case BO_Comma:
2420 VisitIgnoredValue(E->getLHS());
2421 return StmtVisitorTy::Visit(E->getRHS());
2422
2423 case BO_PtrMemD:
2424 case BO_PtrMemI: {
2425 LValue Obj;
2426 if (!HandleMemberPointerAccess(Info, E, Obj))
2427 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002428 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002429 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002430 return false;
2431 return DerivedSuccess(Result, E);
2432 }
2433 }
2434 }
2435
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002436 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002437 // Evaluate and cache the common expression. We treat it as a temporary,
2438 // even though it's not quite the same thing.
2439 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2440 Info, E->getCommon()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002441 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002442
Richard Smith74e1ad92012-02-16 02:46:34 +00002443 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002444 }
2445
2446 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002447 bool IsBcpCall = false;
2448 // If the condition (ignoring parens) is a __builtin_constant_p call,
2449 // the result is a constant expression if it can be folded without
2450 // side-effects. This is an important GNU extension. See GCC PR38377
2451 // for discussion.
2452 if (const CallExpr *CallCE =
2453 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2454 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2455 IsBcpCall = true;
2456
2457 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2458 // constant expression; we can't check whether it's potentially foldable.
2459 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2460 return false;
2461
2462 FoldConstant Fold(Info);
2463
Richard Smith74e1ad92012-02-16 02:46:34 +00002464 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002465 return false;
2466
2467 if (IsBcpCall)
2468 Fold.Fold(Info);
2469
2470 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002471 }
2472
2473 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002474 APValue &Value = Info.CurrentCall->Temporaries[E];
2475 if (Value.isUninit()) {
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002476 const Expr *Source = E->getSourceExpr();
2477 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002478 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002479 if (Source == E) { // sanity checking.
2480 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002481 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002482 }
2483 return StmtVisitorTy::Visit(Source);
2484 }
Richard Smithe92b1f42012-06-26 08:12:11 +00002485 return DerivedSuccess(Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002486 }
Richard Smithf10d9172011-10-11 21:43:33 +00002487
Richard Smithd0dccea2011-10-28 22:34:42 +00002488 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002489 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002490 QualType CalleeType = Callee->getType();
2491
Richard Smithd0dccea2011-10-28 22:34:42 +00002492 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002493 LValue *This = 0, ThisVal;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002494 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002495 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002496
Richard Smith59efe262011-11-11 04:05:33 +00002497 // Extract function decl and 'this' pointer from the callee.
2498 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002499 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002500 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2501 // Explicit bound member calls, such as x.f() or p->g();
2502 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002503 return false;
2504 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002505 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002506 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002507 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2508 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002509 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2510 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002511 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002512 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002513 return Error(Callee);
2514
2515 FD = dyn_cast<FunctionDecl>(Member);
2516 if (!FD)
2517 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002518 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002519 LValue Call;
2520 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002521 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002522
Richard Smithb4e85ed2012-01-06 16:39:00 +00002523 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002524 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002525 FD = dyn_cast_or_null<FunctionDecl>(
2526 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002527 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002528 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002529
2530 // Overloaded operator calls to member functions are represented as normal
2531 // calls with '*this' as the first argument.
2532 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2533 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002534 // FIXME: When selecting an implicit conversion for an overloaded
2535 // operator delete, we sometimes try to evaluate calls to conversion
2536 // operators without a 'this' parameter!
2537 if (Args.empty())
2538 return Error(E);
2539
Richard Smith59efe262011-11-11 04:05:33 +00002540 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2541 return false;
2542 This = &ThisVal;
2543 Args = Args.slice(1);
2544 }
2545
2546 // Don't call function pointers which have been cast to some other type.
2547 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002548 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002549 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002550 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002551
Richard Smithb04035a2012-02-01 02:39:43 +00002552 if (This && !This->checkSubobject(Info, E, CSK_This))
2553 return false;
2554
Richard Smith86c3ae42012-02-13 03:54:03 +00002555 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2556 // calls to such functions in constant expressions.
2557 if (This && !HasQualifier &&
2558 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2559 return Error(E, diag::note_constexpr_virtual_call);
2560
Richard Smithc1c5f272011-12-13 06:39:58 +00002561 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002562 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002563 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002564
Richard Smithc1c5f272011-12-13 06:39:58 +00002565 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002566 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2567 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002568 return false;
2569
Richard Smith83587db2012-02-15 02:18:13 +00002570 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002571 }
2572
Richard Smithc49bd112011-10-28 17:51:58 +00002573 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2574 return StmtVisitorTy::Visit(E->getInitializer());
2575 }
Richard Smithf10d9172011-10-11 21:43:33 +00002576 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002577 if (E->getNumInits() == 0)
2578 return DerivedZeroInitialization(E);
2579 if (E->getNumInits() == 1)
2580 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002581 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002582 }
2583 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002584 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002585 }
2586 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002587 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002588 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002589 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002590 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002591 }
Richard Smithf10d9172011-10-11 21:43:33 +00002592
Richard Smith180f4792011-11-10 06:34:14 +00002593 /// A member expression where the object is a prvalue is itself a prvalue.
2594 RetTy VisitMemberExpr(const MemberExpr *E) {
2595 assert(!E->isArrow() && "missing call to bound member function?");
2596
Richard Smith1aa0be82012-03-03 22:46:17 +00002597 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002598 if (!Evaluate(Val, Info, E->getBase()))
2599 return false;
2600
2601 QualType BaseTy = E->getBase()->getType();
2602
2603 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002604 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002605 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek890f0f12012-08-23 20:46:57 +00002606 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smith180f4792011-11-10 06:34:14 +00002607 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2608
Richard Smithb4e85ed2012-01-06 16:39:00 +00002609 SubobjectDesignator Designator(BaseTy);
2610 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002611
Richard Smithf48fdb02011-12-09 22:58:01 +00002612 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002613 DerivedSuccess(Val, E);
2614 }
2615
Richard Smithc49bd112011-10-28 17:51:58 +00002616 RetTy VisitCastExpr(const CastExpr *E) {
2617 switch (E->getCastKind()) {
2618 default:
2619 break;
2620
David Chisnall7a7ee302012-01-16 17:27:18 +00002621 case CK_AtomicToNonAtomic:
2622 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002623 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002624 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002625 return StmtVisitorTy::Visit(E->getSubExpr());
2626
2627 case CK_LValueToRValue: {
2628 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002629 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2630 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002631 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002632 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2633 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2634 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002635 return false;
2636 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002637 }
2638 }
2639
Richard Smithf48fdb02011-12-09 22:58:01 +00002640 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002641 }
2642
Richard Smith8327fad2011-10-24 18:44:57 +00002643 /// Visit a value which is evaluated, but whose value is ignored.
2644 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002645 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002646 if (!Evaluate(Scratch, Info, E))
2647 Info.EvalStatus.HasSideEffects = true;
2648 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002649};
2650
2651}
2652
2653//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002654// Common base class for lvalue and temporary evaluation.
2655//===----------------------------------------------------------------------===//
2656namespace {
2657template<class Derived>
2658class LValueExprEvaluatorBase
2659 : public ExprEvaluatorBase<Derived, bool> {
2660protected:
2661 LValue &Result;
2662 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2663 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2664
2665 bool Success(APValue::LValueBase B) {
2666 Result.set(B);
2667 return true;
2668 }
2669
2670public:
2671 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2672 ExprEvaluatorBaseTy(Info), Result(Result) {}
2673
Richard Smith1aa0be82012-03-03 22:46:17 +00002674 bool Success(const APValue &V, const Expr *E) {
2675 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002676 return true;
2677 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002678
Richard Smithe24f5fc2011-11-17 22:56:20 +00002679 bool VisitMemberExpr(const MemberExpr *E) {
2680 // Handle non-static data members.
2681 QualType BaseTy;
2682 if (E->isArrow()) {
2683 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2684 return false;
Ted Kremenek890f0f12012-08-23 20:46:57 +00002685 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002686 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002687 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002688 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2689 return false;
2690 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002691 } else {
2692 if (!this->Visit(E->getBase()))
2693 return false;
2694 BaseTy = E->getBase()->getType();
2695 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002696
Richard Smithd9b02e72012-01-25 22:15:11 +00002697 const ValueDecl *MD = E->getMemberDecl();
2698 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2699 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2700 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2701 (void)BaseTy;
John McCall8d59dee2012-05-01 00:38:49 +00002702 if (!HandleLValueMember(this->Info, E, Result, FD))
2703 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002704 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCall8d59dee2012-05-01 00:38:49 +00002705 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2706 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002707 } else
2708 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002709
Richard Smithd9b02e72012-01-25 22:15:11 +00002710 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002711 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002712 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002713 RefValue))
2714 return false;
2715 return Success(RefValue, E);
2716 }
2717 return true;
2718 }
2719
2720 bool VisitBinaryOperator(const BinaryOperator *E) {
2721 switch (E->getOpcode()) {
2722 default:
2723 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2724
2725 case BO_PtrMemD:
2726 case BO_PtrMemI:
2727 return HandleMemberPointerAccess(this->Info, E, Result);
2728 }
2729 }
2730
2731 bool VisitCastExpr(const CastExpr *E) {
2732 switch (E->getCastKind()) {
2733 default:
2734 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2735
2736 case CK_DerivedToBase:
2737 case CK_UncheckedDerivedToBase: {
2738 if (!this->Visit(E->getSubExpr()))
2739 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002740
2741 // Now figure out the necessary offset to add to the base LV to get from
2742 // the derived class to the base class.
2743 QualType Type = E->getSubExpr()->getType();
2744
2745 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2746 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002747 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002748 *PathI))
2749 return false;
2750 Type = (*PathI)->getType();
2751 }
2752
2753 return true;
2754 }
2755 }
2756 }
2757};
2758}
2759
2760//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002761// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002762//
2763// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2764// function designators (in C), decl references to void objects (in C), and
2765// temporaries (if building with -Wno-address-of-temporary).
2766//
2767// LValue evaluation produces values comprising a base expression of one of the
2768// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002769// - Declarations
2770// * VarDecl
2771// * FunctionDecl
2772// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002773// * CompoundLiteralExpr in C
2774// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002775// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002776// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002777// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002778// * ObjCEncodeExpr
2779// * AddrLabelExpr
2780// * BlockExpr
2781// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002782// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002783// * Any Expr, with a CallIndex indicating the function in which the temporary
2784// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002785// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002786//===----------------------------------------------------------------------===//
2787namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002788class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002789 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002790public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002791 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2792 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002793
Richard Smithc49bd112011-10-28 17:51:58 +00002794 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2795
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002796 bool VisitDeclRefExpr(const DeclRefExpr *E);
2797 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002798 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002799 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2800 bool VisitMemberExpr(const MemberExpr *E);
2801 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2802 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002803 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichete275a182012-04-16 04:08:35 +00002804 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002805 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2806 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002807 bool VisitUnaryReal(const UnaryOperator *E);
2808 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002809
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002810 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002811 switch (E->getCastKind()) {
2812 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002813 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002814
Eli Friedmandb924222011-10-11 00:13:24 +00002815 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002816 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002817 if (!Visit(E->getSubExpr()))
2818 return false;
2819 Result.Designator.setInvalid();
2820 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002821
Richard Smithe24f5fc2011-11-17 22:56:20 +00002822 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002823 if (!Visit(E->getSubExpr()))
2824 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002825 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002826 }
2827 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002828};
2829} // end anonymous namespace
2830
Richard Smithc49bd112011-10-28 17:51:58 +00002831/// Evaluate an expression as an lvalue. This can be legitimately called on
2832/// expressions which are not glvalues, in a few cases:
2833/// * function designators in C,
2834/// * "extern void" objects,
2835/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002836static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002837 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2838 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2839 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002840 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002841}
2842
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002843bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002844 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2845 return Success(FD);
2846 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002847 return VisitVarDecl(E, VD);
2848 return Error(E);
2849}
Richard Smith436c8892011-10-24 23:14:33 +00002850
Richard Smithc49bd112011-10-28 17:51:58 +00002851bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002852 if (!VD->getType()->isReferenceType()) {
2853 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002854 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002855 return true;
2856 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002857 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002858 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002859
Richard Smith1aa0be82012-03-03 22:46:17 +00002860 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002861 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2862 return false;
2863 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002864}
2865
Richard Smithbd552ef2011-10-31 05:52:43 +00002866bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2867 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002868 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002869 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002870 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2871
Richard Smith83587db2012-02-15 02:18:13 +00002872 Result.set(E, Info.CurrentCall->Index);
2873 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2874 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002875 }
2876
2877 // Materialization of an lvalue temporary occurs when we need to force a copy
2878 // (for instance, if it's a bitfield).
2879 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2880 if (!Visit(E->GetTemporaryExpr()))
2881 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002882 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002883 Info.CurrentCall->Temporaries[E]))
2884 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002885 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002886 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002887}
2888
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002889bool
2890LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002891 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2892 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2893 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002894 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002895}
2896
Richard Smith47d21452011-12-27 12:18:28 +00002897bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith9be36ab2012-10-17 23:52:07 +00002898 if (!E->isPotentiallyEvaluated())
Richard Smith47d21452011-12-27 12:18:28 +00002899 return Success(E);
Richard Smith9be36ab2012-10-17 23:52:07 +00002900
2901 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
2902 << E->getExprOperand()->getType()
2903 << E->getExprOperand()->getSourceRange();
2904 return false;
Richard Smith47d21452011-12-27 12:18:28 +00002905}
2906
Francois Pichete275a182012-04-16 04:08:35 +00002907bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2908 return Success(E);
2909}
2910
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002911bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002912 // Handle static data members.
2913 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2914 VisitIgnoredValue(E->getBase());
2915 return VisitVarDecl(E, VD);
2916 }
2917
Richard Smithd0dccea2011-10-28 22:34:42 +00002918 // Handle static member functions.
2919 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2920 if (MD->isStatic()) {
2921 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002922 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002923 }
2924 }
2925
Richard Smith180f4792011-11-10 06:34:14 +00002926 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002927 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002928}
2929
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002930bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002931 // FIXME: Deal with vectors as array subscript bases.
2932 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002933 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002934
Anders Carlsson3068d112008-11-16 19:01:22 +00002935 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002936 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002937
Anders Carlsson3068d112008-11-16 19:01:22 +00002938 APSInt Index;
2939 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002940 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002941 int64_t IndexValue
2942 = Index.isSigned() ? Index.getSExtValue()
2943 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002944
Richard Smithb4e85ed2012-01-06 16:39:00 +00002945 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002946}
Eli Friedman4efaa272008-11-12 09:44:48 +00002947
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002948bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002949 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002950}
2951
Richard Smith86024012012-02-18 22:04:06 +00002952bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2953 if (!Visit(E->getSubExpr()))
2954 return false;
2955 // __real is a no-op on scalar lvalues.
2956 if (E->getSubExpr()->getType()->isAnyComplexType())
2957 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
2958 return true;
2959}
2960
2961bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
2962 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
2963 "lvalue __imag__ on scalar?");
2964 if (!Visit(E->getSubExpr()))
2965 return false;
2966 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
2967 return true;
2968}
2969
Eli Friedman4efaa272008-11-12 09:44:48 +00002970//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002971// Pointer Evaluation
2972//===----------------------------------------------------------------------===//
2973
Anders Carlssonc754aa62008-07-08 05:13:58 +00002974namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002975class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002976 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002977 LValue &Result;
2978
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002979 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002980 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002981 return true;
2982 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002983public:
Mike Stump1eb44332009-09-09 15:08:12 +00002984
John McCallefdb83e2010-05-07 21:00:08 +00002985 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002986 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002987
Richard Smith1aa0be82012-03-03 22:46:17 +00002988 bool Success(const APValue &V, const Expr *E) {
2989 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002990 return true;
2991 }
Richard Smith51201882011-12-30 21:15:51 +00002992 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002993 return Success((Expr*)0);
2994 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002995
John McCallefdb83e2010-05-07 21:00:08 +00002996 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002997 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002998 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002999 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003000 { return Success(E); }
Patrick Beardeb382ec2012-04-19 00:25:12 +00003001 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003002 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003003 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003004 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003005 bool VisitCallExpr(const CallExpr *E);
3006 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003007 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003008 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003009 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003010 }
Richard Smith180f4792011-11-10 06:34:14 +00003011 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3012 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003013 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003014 Result = *Info.CurrentCall->This;
3015 return true;
3016 }
John McCall56ca35d2011-02-17 10:25:35 +00003017
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003018 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003019};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003020} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003021
John McCallefdb83e2010-05-07 21:00:08 +00003022static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003023 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003024 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003025}
3026
John McCallefdb83e2010-05-07 21:00:08 +00003027bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003028 if (E->getOpcode() != BO_Add &&
3029 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003030 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003031
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003032 const Expr *PExp = E->getLHS();
3033 const Expr *IExp = E->getRHS();
3034 if (IExp->getType()->isPointerType())
3035 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003036
Richard Smith745f5142012-01-27 01:14:48 +00003037 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3038 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003039 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003040
John McCallefdb83e2010-05-07 21:00:08 +00003041 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003042 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003043 return false;
3044 int64_t AdditionalOffset
3045 = Offset.isSigned() ? Offset.getSExtValue()
3046 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003047 if (E->getOpcode() == BO_Sub)
3048 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003049
Ted Kremenek890f0f12012-08-23 20:46:57 +00003050 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003051 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3052 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003053}
Eli Friedman4efaa272008-11-12 09:44:48 +00003054
John McCallefdb83e2010-05-07 21:00:08 +00003055bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3056 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003057}
Mike Stump1eb44332009-09-09 15:08:12 +00003058
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003059bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3060 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003061
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003062 switch (E->getCastKind()) {
3063 default:
3064 break;
3065
John McCall2de56d12010-08-25 11:45:40 +00003066 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003067 case CK_CPointerToObjCPointerCast:
3068 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003069 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003070 if (!Visit(SubExpr))
3071 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003072 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3073 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3074 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003075 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003076 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003077 if (SubExpr->getType()->isVoidPointerType())
3078 CCEDiag(E, diag::note_constexpr_invalid_cast)
3079 << 3 << SubExpr->getType();
3080 else
3081 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3082 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003083 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003084
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003085 case CK_DerivedToBase:
3086 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003087 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003088 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003089 if (!Result.Base && Result.Offset.isZero())
3090 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003091
Richard Smith180f4792011-11-10 06:34:14 +00003092 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003093 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003094 QualType Type =
3095 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003096
Richard Smith180f4792011-11-10 06:34:14 +00003097 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003098 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003099 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3100 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003101 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003102 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003103 }
3104
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003105 return true;
3106 }
3107
Richard Smithe24f5fc2011-11-17 22:56:20 +00003108 case CK_BaseToDerived:
3109 if (!Visit(E->getSubExpr()))
3110 return false;
3111 if (!Result.Base && Result.Offset.isZero())
3112 return true;
3113 return HandleBaseToDerivedCast(Info, E, Result);
3114
Richard Smith47a1eed2011-10-29 20:57:55 +00003115 case CK_NullToPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003116 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003117 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003118
John McCall2de56d12010-08-25 11:45:40 +00003119 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003120 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3121
Richard Smith1aa0be82012-03-03 22:46:17 +00003122 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003123 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003124 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003125
John McCallefdb83e2010-05-07 21:00:08 +00003126 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003127 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3128 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003129 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003130 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003131 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003132 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003133 return true;
3134 } else {
3135 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003136 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003137 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003138 }
3139 }
John McCall2de56d12010-08-25 11:45:40 +00003140 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003141 if (SubExpr->isGLValue()) {
3142 if (!EvaluateLValue(SubExpr, Result, Info))
3143 return false;
3144 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003145 Result.set(SubExpr, Info.CurrentCall->Index);
3146 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3147 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003148 return false;
3149 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003150 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003151 if (const ConstantArrayType *CAT
3152 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3153 Result.addArray(Info, E, CAT);
3154 else
3155 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003156 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003157
John McCall2de56d12010-08-25 11:45:40 +00003158 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003159 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003160 }
3161
Richard Smithc49bd112011-10-28 17:51:58 +00003162 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003163}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003164
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003165bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003166 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003167 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003168
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003169 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003170}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003171
3172//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003173// Member Pointer Evaluation
3174//===----------------------------------------------------------------------===//
3175
3176namespace {
3177class MemberPointerExprEvaluator
3178 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3179 MemberPtr &Result;
3180
3181 bool Success(const ValueDecl *D) {
3182 Result = MemberPtr(D);
3183 return true;
3184 }
3185public:
3186
3187 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3188 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3189
Richard Smith1aa0be82012-03-03 22:46:17 +00003190 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003191 Result.setFrom(V);
3192 return true;
3193 }
Richard Smith51201882011-12-30 21:15:51 +00003194 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003195 return Success((const ValueDecl*)0);
3196 }
3197
3198 bool VisitCastExpr(const CastExpr *E);
3199 bool VisitUnaryAddrOf(const UnaryOperator *E);
3200};
3201} // end anonymous namespace
3202
3203static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3204 EvalInfo &Info) {
3205 assert(E->isRValue() && E->getType()->isMemberPointerType());
3206 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3207}
3208
3209bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3210 switch (E->getCastKind()) {
3211 default:
3212 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3213
3214 case CK_NullToMemberPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003215 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003216 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003217
3218 case CK_BaseToDerivedMemberPointer: {
3219 if (!Visit(E->getSubExpr()))
3220 return false;
3221 if (E->path_empty())
3222 return true;
3223 // Base-to-derived member pointer casts store the path in derived-to-base
3224 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3225 // the wrong end of the derived->base arc, so stagger the path by one class.
3226 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3227 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3228 PathI != PathE; ++PathI) {
3229 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3230 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3231 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003232 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003233 }
3234 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3235 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003236 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003237 return true;
3238 }
3239
3240 case CK_DerivedToBaseMemberPointer:
3241 if (!Visit(E->getSubExpr()))
3242 return false;
3243 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3244 PathE = E->path_end(); PathI != PathE; ++PathI) {
3245 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3246 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3247 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003248 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003249 }
3250 return true;
3251 }
3252}
3253
3254bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3255 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3256 // member can be formed.
3257 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3258}
3259
3260//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003261// Record Evaluation
3262//===----------------------------------------------------------------------===//
3263
3264namespace {
3265 class RecordExprEvaluator
3266 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3267 const LValue &This;
3268 APValue &Result;
3269 public:
3270
3271 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3272 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3273
Richard Smith1aa0be82012-03-03 22:46:17 +00003274 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003275 Result = V;
3276 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003277 }
Richard Smith51201882011-12-30 21:15:51 +00003278 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003279
Richard Smith59efe262011-11-11 04:05:33 +00003280 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003281 bool VisitInitListExpr(const InitListExpr *E);
3282 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3283 };
3284}
3285
Richard Smith51201882011-12-30 21:15:51 +00003286/// Perform zero-initialization on an object of non-union class type.
3287/// C++11 [dcl.init]p5:
3288/// To zero-initialize an object or reference of type T means:
3289/// [...]
3290/// -- if T is a (possibly cv-qualified) non-union class type,
3291/// each non-static data member and each base-class subobject is
3292/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003293static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3294 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003295 const LValue &This, APValue &Result) {
3296 assert(!RD->isUnion() && "Expected non-union class type");
3297 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3298 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3299 std::distance(RD->field_begin(), RD->field_end()));
3300
John McCall8d59dee2012-05-01 00:38:49 +00003301 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003302 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3303
3304 if (CD) {
3305 unsigned Index = 0;
3306 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003307 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003308 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3309 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003310 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3311 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003312 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003313 Result.getStructBase(Index)))
3314 return false;
3315 }
3316 }
3317
Richard Smithb4e85ed2012-01-06 16:39:00 +00003318 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3319 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003320 // -- if T is a reference type, no initialization is performed.
David Blaikie262bc182012-04-30 02:36:29 +00003321 if (I->getType()->isReferenceType())
Richard Smith51201882011-12-30 21:15:51 +00003322 continue;
3323
3324 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003325 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003326 return false;
Richard Smith51201882011-12-30 21:15:51 +00003327
David Blaikie262bc182012-04-30 02:36:29 +00003328 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003329 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003330 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003331 return false;
3332 }
3333
3334 return true;
3335}
3336
3337bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3338 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003339 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003340 if (RD->isUnion()) {
3341 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3342 // object's first non-static named data member is zero-initialized
3343 RecordDecl::field_iterator I = RD->field_begin();
3344 if (I == RD->field_end()) {
3345 Result = APValue((const FieldDecl*)0);
3346 return true;
3347 }
3348
3349 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003350 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCall8d59dee2012-05-01 00:38:49 +00003351 return false;
David Blaikie581deb32012-06-06 20:45:41 +00003352 Result = APValue(*I);
David Blaikie262bc182012-04-30 02:36:29 +00003353 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003354 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003355 }
3356
Richard Smithce582fe2012-02-17 00:44:16 +00003357 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003358 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003359 return false;
3360 }
3361
Richard Smithb4e85ed2012-01-06 16:39:00 +00003362 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003363}
3364
Richard Smith59efe262011-11-11 04:05:33 +00003365bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3366 switch (E->getCastKind()) {
3367 default:
3368 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3369
3370 case CK_ConstructorConversion:
3371 return Visit(E->getSubExpr());
3372
3373 case CK_DerivedToBase:
3374 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003375 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003376 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003377 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003378 if (!DerivedObject.isStruct())
3379 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003380
3381 // Derived-to-base rvalue conversion: just slice off the derived part.
3382 APValue *Value = &DerivedObject;
3383 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3384 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3385 PathE = E->path_end(); PathI != PathE; ++PathI) {
3386 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3387 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3388 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3389 RD = Base;
3390 }
3391 Result = *Value;
3392 return true;
3393 }
3394 }
3395}
3396
Richard Smith180f4792011-11-10 06:34:14 +00003397bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003398 // Cannot constant-evaluate std::initializer_list inits.
3399 if (E->initializesStdInitializerList())
3400 return false;
3401
Richard Smith180f4792011-11-10 06:34:14 +00003402 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003403 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00003404 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3405
3406 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003407 const FieldDecl *Field = E->getInitializedFieldInUnion();
3408 Result = APValue(Field);
3409 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003410 return true;
Richard Smithec789162012-01-12 18:54:33 +00003411
3412 // If the initializer list for a union does not contain any elements, the
3413 // first element of the union is value-initialized.
3414 ImplicitValueInitExpr VIE(Field->getType());
3415 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3416
Richard Smith180f4792011-11-10 06:34:14 +00003417 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003418 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3419 return false;
Richard Smith83587db2012-02-15 02:18:13 +00003420 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003421 }
3422
3423 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3424 "initializer list for class with base classes");
3425 Result = APValue(APValue::UninitStruct(), 0,
3426 std::distance(RD->field_begin(), RD->field_end()));
3427 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003428 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003429 for (RecordDecl::field_iterator Field = RD->field_begin(),
3430 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3431 // Anonymous bit-fields are not considered members of the class for
3432 // purposes of aggregate initialization.
3433 if (Field->isUnnamedBitfield())
3434 continue;
3435
3436 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003437
Richard Smith745f5142012-01-27 01:14:48 +00003438 bool HaveInit = ElementNo < E->getNumInits();
3439
3440 // FIXME: Diagnostics here should point to the end of the initializer
3441 // list, not the start.
John McCall8d59dee2012-05-01 00:38:49 +00003442 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie581deb32012-06-06 20:45:41 +00003443 Subobject, *Field, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003444 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003445
3446 // Perform an implicit value-initialization for members beyond the end of
3447 // the initializer list.
3448 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3449
Richard Smith83587db2012-02-15 02:18:13 +00003450 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003451 Result.getStructField(Field->getFieldIndex()),
Richard Smith745f5142012-01-27 01:14:48 +00003452 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3453 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003454 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003455 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003456 }
3457 }
3458
Richard Smith745f5142012-01-27 01:14:48 +00003459 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003460}
3461
3462bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3463 const CXXConstructorDecl *FD = E->getConstructor();
John McCall1de9d7d2012-04-26 18:10:01 +00003464 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3465
Richard Smith51201882011-12-30 21:15:51 +00003466 bool ZeroInit = E->requiresZeroInitialization();
3467 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003468 // If we've already performed zero-initialization, we're already done.
3469 if (!Result.isUninit())
3470 return true;
3471
Richard Smith51201882011-12-30 21:15:51 +00003472 if (ZeroInit)
3473 return ZeroInitialization(E);
3474
Richard Smith61802452011-12-22 02:22:31 +00003475 const CXXRecordDecl *RD = FD->getParent();
3476 if (RD->isUnion())
3477 Result = APValue((FieldDecl*)0);
3478 else
3479 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3480 std::distance(RD->field_begin(), RD->field_end()));
3481 return true;
3482 }
3483
Richard Smith180f4792011-11-10 06:34:14 +00003484 const FunctionDecl *Definition = 0;
3485 FD->getBody(Definition);
3486
Richard Smithc1c5f272011-12-13 06:39:58 +00003487 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3488 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003489
Richard Smith610a60c2012-01-10 04:32:03 +00003490 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003491 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003492 if (const MaterializeTemporaryExpr *ME
3493 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3494 return Visit(ME->GetTemporaryExpr());
3495
Richard Smith51201882011-12-30 21:15:51 +00003496 if (ZeroInit && !ZeroInitialization(E))
3497 return false;
3498
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003499 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003500 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003501 cast<CXXConstructorDecl>(Definition), Info,
3502 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003503}
3504
3505static bool EvaluateRecord(const Expr *E, const LValue &This,
3506 APValue &Result, EvalInfo &Info) {
3507 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003508 "can't evaluate expression as a record rvalue");
3509 return RecordExprEvaluator(Info, This, Result).Visit(E);
3510}
3511
3512//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003513// Temporary Evaluation
3514//
3515// Temporaries are represented in the AST as rvalues, but generally behave like
3516// lvalues. The full-object of which the temporary is a subobject is implicitly
3517// materialized so that a reference can bind to it.
3518//===----------------------------------------------------------------------===//
3519namespace {
3520class TemporaryExprEvaluator
3521 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3522public:
3523 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3524 LValueExprEvaluatorBaseTy(Info, Result) {}
3525
3526 /// Visit an expression which constructs the value of this temporary.
3527 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003528 Result.set(E, Info.CurrentCall->Index);
3529 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003530 }
3531
3532 bool VisitCastExpr(const CastExpr *E) {
3533 switch (E->getCastKind()) {
3534 default:
3535 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3536
3537 case CK_ConstructorConversion:
3538 return VisitConstructExpr(E->getSubExpr());
3539 }
3540 }
3541 bool VisitInitListExpr(const InitListExpr *E) {
3542 return VisitConstructExpr(E);
3543 }
3544 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3545 return VisitConstructExpr(E);
3546 }
3547 bool VisitCallExpr(const CallExpr *E) {
3548 return VisitConstructExpr(E);
3549 }
3550};
3551} // end anonymous namespace
3552
3553/// Evaluate an expression of record type as a temporary.
3554static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003555 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003556 return TemporaryExprEvaluator(Info, Result).Visit(E);
3557}
3558
3559//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003560// Vector Evaluation
3561//===----------------------------------------------------------------------===//
3562
3563namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003564 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003565 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3566 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003567 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003568
Richard Smith07fc6572011-10-22 21:10:00 +00003569 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3570 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003571
Richard Smith07fc6572011-10-22 21:10:00 +00003572 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3573 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3574 // FIXME: remove this APValue copy.
3575 Result = APValue(V.data(), V.size());
3576 return true;
3577 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003578 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003579 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003580 Result = V;
3581 return true;
3582 }
Richard Smith51201882011-12-30 21:15:51 +00003583 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003584
Richard Smith07fc6572011-10-22 21:10:00 +00003585 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003586 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003587 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003588 bool VisitInitListExpr(const InitListExpr *E);
3589 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003590 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003591 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003592 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003593 };
3594} // end anonymous namespace
3595
3596static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003597 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003598 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003599}
3600
Richard Smith07fc6572011-10-22 21:10:00 +00003601bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3602 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003603 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003604
Richard Smithd62ca372011-12-06 22:44:34 +00003605 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003606 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003607
Eli Friedman46a52322011-03-25 00:43:55 +00003608 switch (E->getCastKind()) {
3609 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003610 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003611 if (SETy->isIntegerType()) {
3612 APSInt IntResult;
3613 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003614 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003615 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003616 } else if (SETy->isRealFloatingType()) {
3617 APFloat F(0.0);
3618 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003619 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003620 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003621 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003622 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003623 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003624
3625 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003626 SmallVector<APValue, 4> Elts(NElts, Val);
3627 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003628 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003629 case CK_BitCast: {
3630 // Evaluate the operand into an APInt we can extract from.
3631 llvm::APInt SValInt;
3632 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3633 return false;
3634 // Extract the elements
3635 QualType EltTy = VTy->getElementType();
3636 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3637 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3638 SmallVector<APValue, 4> Elts;
3639 if (EltTy->isRealFloatingType()) {
3640 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedmane6a24e82011-12-22 03:51:45 +00003641 unsigned FloatEltSize = EltSize;
3642 if (&Sem == &APFloat::x87DoubleExtended)
3643 FloatEltSize = 80;
3644 for (unsigned i = 0; i < NElts; i++) {
3645 llvm::APInt Elt;
3646 if (BigEndian)
3647 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3648 else
3649 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover9ec55f22013-01-22 09:46:51 +00003650 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedmane6a24e82011-12-22 03:51:45 +00003651 }
3652 } else if (EltTy->isIntegerType()) {
3653 for (unsigned i = 0; i < NElts; i++) {
3654 llvm::APInt Elt;
3655 if (BigEndian)
3656 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3657 else
3658 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3659 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3660 }
3661 } else {
3662 return Error(E);
3663 }
3664 return Success(Elts, E);
3665 }
Eli Friedman46a52322011-03-25 00:43:55 +00003666 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003667 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003668 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003669}
3670
Richard Smith07fc6572011-10-22 21:10:00 +00003671bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003672VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003673 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003674 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003675 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003676
Nate Begeman59b5da62009-01-18 03:20:47 +00003677 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003678 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003679
Eli Friedman3edd5a92012-01-03 23:24:20 +00003680 // The number of initializers can be less than the number of
3681 // vector elements. For OpenCL, this can be due to nested vector
3682 // initialization. For GCC compatibility, missing trailing elements
3683 // should be initialized with zeroes.
3684 unsigned CountInits = 0, CountElts = 0;
3685 while (CountElts < NumElements) {
3686 // Handle nested vector initialization.
3687 if (CountInits < NumInits
3688 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3689 APValue v;
3690 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3691 return Error(E);
3692 unsigned vlen = v.getVectorLength();
3693 for (unsigned j = 0; j < vlen; j++)
3694 Elements.push_back(v.getVectorElt(j));
3695 CountElts += vlen;
3696 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003697 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003698 if (CountInits < NumInits) {
3699 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003700 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003701 } else // trailing integer zero.
3702 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3703 Elements.push_back(APValue(sInt));
3704 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003705 } else {
3706 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003707 if (CountInits < NumInits) {
3708 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003709 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003710 } else // trailing float zero.
3711 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3712 Elements.push_back(APValue(f));
3713 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003714 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003715 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003716 }
Richard Smith07fc6572011-10-22 21:10:00 +00003717 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003718}
3719
Richard Smith07fc6572011-10-22 21:10:00 +00003720bool
Richard Smith51201882011-12-30 21:15:51 +00003721VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003722 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003723 QualType EltTy = VT->getElementType();
3724 APValue ZeroElement;
3725 if (EltTy->isIntegerType())
3726 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3727 else
3728 ZeroElement =
3729 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3730
Chris Lattner5f9e2722011-07-23 10:55:15 +00003731 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003732 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003733}
3734
Richard Smith07fc6572011-10-22 21:10:00 +00003735bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003736 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003737 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003738}
3739
Nate Begeman59b5da62009-01-18 03:20:47 +00003740//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003741// Array Evaluation
3742//===----------------------------------------------------------------------===//
3743
3744namespace {
3745 class ArrayExprEvaluator
3746 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003747 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003748 APValue &Result;
3749 public:
3750
Richard Smith180f4792011-11-10 06:34:14 +00003751 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3752 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003753
3754 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003755 assert((V.isArray() || V.isLValue()) &&
3756 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003757 Result = V;
3758 return true;
3759 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003760
Richard Smith51201882011-12-30 21:15:51 +00003761 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003762 const ConstantArrayType *CAT =
3763 Info.Ctx.getAsConstantArrayType(E->getType());
3764 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003765 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003766
3767 Result = APValue(APValue::UninitArray(), 0,
3768 CAT->getSize().getZExtValue());
3769 if (!Result.hasArrayFiller()) return true;
3770
Richard Smith51201882011-12-30 21:15:51 +00003771 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003772 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003773 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003774 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003775 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003776 }
3777
Richard Smithcc5d4f62011-11-07 09:22:26 +00003778 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003779 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003780 };
3781} // end anonymous namespace
3782
Richard Smith180f4792011-11-10 06:34:14 +00003783static bool EvaluateArray(const Expr *E, const LValue &This,
3784 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003785 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003786 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003787}
3788
3789bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3790 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3791 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003792 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003793
Richard Smith974c5f92011-12-22 01:07:19 +00003794 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3795 // an appropriately-typed string literal enclosed in braces.
Richard Smithfe587202012-04-15 02:50:59 +00003796 if (E->isStringLiteralInit()) {
Richard Smith974c5f92011-12-22 01:07:19 +00003797 LValue LV;
3798 if (!EvaluateLValue(E->getInit(0), LV, Info))
3799 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003800 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003801 LV.moveInto(Val);
3802 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003803 }
3804
Richard Smith745f5142012-01-27 01:14:48 +00003805 bool Success = true;
3806
Richard Smithde31aa72012-07-07 22:48:24 +00003807 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
3808 "zero-initialized array shouldn't have any initialized elts");
3809 APValue Filler;
3810 if (Result.isArray() && Result.hasArrayFiller())
3811 Filler = Result.getArrayFiller();
3812
Richard Smithcc5d4f62011-11-07 09:22:26 +00003813 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3814 CAT->getSize().getZExtValue());
Richard Smithde31aa72012-07-07 22:48:24 +00003815
3816 // If the array was previously zero-initialized, preserve the
3817 // zero-initialized values.
3818 if (!Filler.isUninit()) {
3819 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
3820 Result.getArrayInitializedElt(I) = Filler;
3821 if (Result.hasArrayFiller())
3822 Result.getArrayFiller() = Filler;
3823 }
3824
Richard Smith180f4792011-11-10 06:34:14 +00003825 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003826 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003827 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003828 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003829 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003830 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3831 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003832 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3833 CAT->getElementType(), 1)) {
3834 if (!Info.keepEvaluatingAfterFailure())
3835 return false;
3836 Success = false;
3837 }
Richard Smith180f4792011-11-10 06:34:14 +00003838 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003839
Richard Smith745f5142012-01-27 01:14:48 +00003840 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003841 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003842 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3843 // but sometimes does:
3844 // struct S { constexpr S() : p(&p) {} void *p; };
3845 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003846 return EvaluateInPlace(Result.getArrayFiller(), Info,
3847 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003848}
3849
Richard Smithe24f5fc2011-11-17 22:56:20 +00003850bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smithde31aa72012-07-07 22:48:24 +00003851 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3852 // but sometimes does:
3853 // struct S { constexpr S() : p(&p) {} void *p; };
3854 // S s[10];
3855 LValue Subobject = This;
3856
3857 APValue *Value = &Result;
3858 bool HadZeroInit = true;
Richard Smitha4334df2012-07-10 22:12:55 +00003859 QualType ElemTy = E->getType();
3860 while (const ConstantArrayType *CAT =
3861 Info.Ctx.getAsConstantArrayType(ElemTy)) {
Richard Smithde31aa72012-07-07 22:48:24 +00003862 Subobject.addArray(Info, E, CAT);
3863 HadZeroInit &= !Value->isUninit();
3864 if (!HadZeroInit)
3865 *Value = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3866 if (!Value->hasArrayFiller())
3867 return true;
Richard Smithde31aa72012-07-07 22:48:24 +00003868 Value = &Value->getArrayFiller();
Richard Smitha4334df2012-07-10 22:12:55 +00003869 ElemTy = CAT->getElementType();
Richard Smithde31aa72012-07-07 22:48:24 +00003870 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00003871
Richard Smitha4334df2012-07-10 22:12:55 +00003872 if (!ElemTy->isRecordType())
3873 return Error(E);
3874
Richard Smithe24f5fc2011-11-17 22:56:20 +00003875 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003876
Richard Smith51201882011-12-30 21:15:51 +00003877 bool ZeroInit = E->requiresZeroInitialization();
3878 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003879 if (HadZeroInit)
3880 return true;
3881
Richard Smith51201882011-12-30 21:15:51 +00003882 if (ZeroInit) {
Richard Smitha4334df2012-07-10 22:12:55 +00003883 ImplicitValueInitExpr VIE(ElemTy);
Richard Smithde31aa72012-07-07 22:48:24 +00003884 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003885 }
3886
Richard Smith61802452011-12-22 02:22:31 +00003887 const CXXRecordDecl *RD = FD->getParent();
3888 if (RD->isUnion())
Richard Smithde31aa72012-07-07 22:48:24 +00003889 *Value = APValue((FieldDecl*)0);
Richard Smith61802452011-12-22 02:22:31 +00003890 else
Richard Smithde31aa72012-07-07 22:48:24 +00003891 *Value =
Richard Smith61802452011-12-22 02:22:31 +00003892 APValue(APValue::UninitStruct(), RD->getNumBases(),
3893 std::distance(RD->field_begin(), RD->field_end()));
3894 return true;
3895 }
3896
Richard Smithe24f5fc2011-11-17 22:56:20 +00003897 const FunctionDecl *Definition = 0;
3898 FD->getBody(Definition);
3899
Richard Smithc1c5f272011-12-13 06:39:58 +00003900 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3901 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003902
Richard Smithec789162012-01-12 18:54:33 +00003903 if (ZeroInit && !HadZeroInit) {
Richard Smitha4334df2012-07-10 22:12:55 +00003904 ImplicitValueInitExpr VIE(ElemTy);
Richard Smithde31aa72012-07-07 22:48:24 +00003905 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003906 return false;
3907 }
3908
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003909 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003910 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003911 cast<CXXConstructorDecl>(Definition),
Richard Smithde31aa72012-07-07 22:48:24 +00003912 Info, *Value);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003913}
3914
Richard Smithcc5d4f62011-11-07 09:22:26 +00003915//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003916// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003917//
3918// As a GNU extension, we support casting pointers to sufficiently-wide integer
3919// types and back in constant folding. Integer values are thus represented
3920// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003921//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003922
3923namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003924class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003925 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003926 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003927public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003928 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003929 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003930
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003931 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003932 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003933 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003934 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003935 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003936 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003937 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003938 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003939 return true;
3940 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003941 bool Success(const llvm::APSInt &SI, const Expr *E) {
3942 return Success(SI, E, Result);
3943 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003944
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003945 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003946 assert(E->getType()->isIntegralOrEnumerationType() &&
3947 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003948 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003949 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003950 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003951 Result.getInt().setIsUnsigned(
3952 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003953 return true;
3954 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003955 bool Success(const llvm::APInt &I, const Expr *E) {
3956 return Success(I, E, Result);
3957 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00003958
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003959 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003960 assert(E->getType()->isIntegralOrEnumerationType() &&
3961 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003962 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003963 return true;
3964 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003965 bool Success(uint64_t Value, const Expr *E) {
3966 return Success(Value, E, Result);
3967 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00003968
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003969 bool Success(CharUnits Size, const Expr *E) {
3970 return Success(Size.getQuantity(), E);
3971 }
3972
Richard Smith1aa0be82012-03-03 22:46:17 +00003973 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003974 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003975 Result = V;
3976 return true;
3977 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003978 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003979 }
Mike Stump1eb44332009-09-09 15:08:12 +00003980
Richard Smith51201882011-12-30 21:15:51 +00003981 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003982
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003983 //===--------------------------------------------------------------------===//
3984 // Visitor Methods
3985 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003986
Chris Lattner4c4867e2008-07-12 00:38:25 +00003987 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003988 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003989 }
3990 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003991 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003992 }
Eli Friedman04309752009-11-24 05:28:59 +00003993
3994 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3995 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003996 if (CheckReferencedDecl(E, E->getDecl()))
3997 return true;
3998
3999 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004000 }
4001 bool VisitMemberExpr(const MemberExpr *E) {
4002 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004003 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004004 return true;
4005 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004006
4007 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004008 }
4009
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004010 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004011 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004012 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004013 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004014
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004015 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004016 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004017
Anders Carlsson3068d112008-11-16 19:01:22 +00004018 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004019 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004020 }
Mike Stump1eb44332009-09-09 15:08:12 +00004021
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004022 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4023 return Success(E->getValue(), E);
4024 }
4025
Richard Smithf10d9172011-10-11 21:43:33 +00004026 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004027 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004028 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004029 }
4030
Sebastian Redl64b45f72009-01-05 20:52:13 +00004031 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004032 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004033 }
4034
Francois Pichet6ad6f282010-12-07 00:08:36 +00004035 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4036 return Success(E->getValue(), E);
4037 }
4038
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004039 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4040 return Success(E->getValue(), E);
4041 }
4042
John Wiegley21ff2e52011-04-28 00:16:57 +00004043 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4044 return Success(E->getValue(), E);
4045 }
4046
John Wiegley55262202011-04-25 06:54:41 +00004047 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4048 return Success(E->getValue(), E);
4049 }
4050
Eli Friedman722c7172009-02-28 03:59:05 +00004051 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004052 bool VisitUnaryImag(const UnaryOperator *E);
4053
Sebastian Redl295995c2010-09-10 20:55:47 +00004054 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004055 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004056
Chris Lattnerfcee0012008-07-11 21:24:13 +00004057private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004058 CharUnits GetAlignOfExpr(const Expr *E);
4059 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004060 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004061 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004062 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004063};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004064} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004065
Richard Smithc49bd112011-10-28 17:51:58 +00004066/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4067/// produce either the integer value or a pointer.
4068///
4069/// GCC has a heinous extension which folds casts between pointer types and
4070/// pointer-sized integral types. We support this by allowing the evaluation of
4071/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4072/// Some simple arithmetic on such values is supported (they are treated much
4073/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004074static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004075 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004076 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004077 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004078}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004079
Richard Smithf48fdb02011-12-09 22:58:01 +00004080static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004081 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004082 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004083 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004084 if (!Val.isInt()) {
4085 // FIXME: It would be better to produce the diagnostic for casting
4086 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004087 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004088 return false;
4089 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004090 Result = Val.getInt();
4091 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004092}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004093
Richard Smithf48fdb02011-12-09 22:58:01 +00004094/// Check whether the given declaration can be directly converted to an integral
4095/// rvalue. If not, no diagnostic is produced; there are other things we can
4096/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004097bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004098 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004099 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004100 // Check for signedness/width mismatches between E type and ECD value.
4101 bool SameSign = (ECD->getInitVal().isSigned()
4102 == E->getType()->isSignedIntegerOrEnumerationType());
4103 bool SameWidth = (ECD->getInitVal().getBitWidth()
4104 == Info.Ctx.getIntWidth(E->getType()));
4105 if (SameSign && SameWidth)
4106 return Success(ECD->getInitVal(), E);
4107 else {
4108 // Get rid of mismatch (otherwise Success assertions will fail)
4109 // by computing a new value matching the type of E.
4110 llvm::APSInt Val = ECD->getInitVal();
4111 if (!SameSign)
4112 Val.setIsSigned(!ECD->getInitVal().isSigned());
4113 if (!SameWidth)
4114 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4115 return Success(Val, E);
4116 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004117 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004118 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004119}
4120
Chris Lattnera4d55d82008-10-06 06:40:35 +00004121/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4122/// as GCC.
4123static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4124 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004125 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004126 enum gcc_type_class {
4127 no_type_class = -1,
4128 void_type_class, integer_type_class, char_type_class,
4129 enumeral_type_class, boolean_type_class,
4130 pointer_type_class, reference_type_class, offset_type_class,
4131 real_type_class, complex_type_class,
4132 function_type_class, method_type_class,
4133 record_type_class, union_type_class,
4134 array_type_class, string_type_class,
4135 lang_type_class
4136 };
Mike Stump1eb44332009-09-09 15:08:12 +00004137
4138 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004139 // ideal, however it is what gcc does.
4140 if (E->getNumArgs() == 0)
4141 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004142
Chris Lattnera4d55d82008-10-06 06:40:35 +00004143 QualType ArgTy = E->getArg(0)->getType();
4144 if (ArgTy->isVoidType())
4145 return void_type_class;
4146 else if (ArgTy->isEnumeralType())
4147 return enumeral_type_class;
4148 else if (ArgTy->isBooleanType())
4149 return boolean_type_class;
4150 else if (ArgTy->isCharType())
4151 return string_type_class; // gcc doesn't appear to use char_type_class
4152 else if (ArgTy->isIntegerType())
4153 return integer_type_class;
4154 else if (ArgTy->isPointerType())
4155 return pointer_type_class;
4156 else if (ArgTy->isReferenceType())
4157 return reference_type_class;
4158 else if (ArgTy->isRealType())
4159 return real_type_class;
4160 else if (ArgTy->isComplexType())
4161 return complex_type_class;
4162 else if (ArgTy->isFunctionType())
4163 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004164 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004165 return record_type_class;
4166 else if (ArgTy->isUnionType())
4167 return union_type_class;
4168 else if (ArgTy->isArrayType())
4169 return array_type_class;
4170 else if (ArgTy->isUnionType())
4171 return union_type_class;
4172 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004173 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004174}
4175
Richard Smith80d4b552011-12-28 19:48:30 +00004176/// EvaluateBuiltinConstantPForLValue - Determine the result of
4177/// __builtin_constant_p when applied to the given lvalue.
4178///
4179/// An lvalue is only "constant" if it is a pointer or reference to the first
4180/// character of a string literal.
4181template<typename LValue>
4182static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004183 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004184 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4185}
4186
4187/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4188/// GCC as we can manage.
4189static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4190 QualType ArgType = Arg->getType();
4191
4192 // __builtin_constant_p always has one operand. The rules which gcc follows
4193 // are not precisely documented, but are as follows:
4194 //
4195 // - If the operand is of integral, floating, complex or enumeration type,
4196 // and can be folded to a known value of that type, it returns 1.
4197 // - If the operand and can be folded to a pointer to the first character
4198 // of a string literal (or such a pointer cast to an integral type), it
4199 // returns 1.
4200 //
4201 // Otherwise, it returns 0.
4202 //
4203 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4204 // its support for this does not currently work.
4205 if (ArgType->isIntegralOrEnumerationType()) {
4206 Expr::EvalResult Result;
4207 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4208 return false;
4209
4210 APValue &V = Result.Val;
4211 if (V.getKind() == APValue::Int)
4212 return true;
4213
4214 return EvaluateBuiltinConstantPForLValue(V);
4215 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4216 return Arg->isEvaluatable(Ctx);
4217 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4218 LValue LV;
4219 Expr::EvalStatus Status;
4220 EvalInfo Info(Ctx, Status);
4221 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4222 : EvaluatePointer(Arg, LV, Info)) &&
4223 !Status.HasSideEffects)
4224 return EvaluateBuiltinConstantPForLValue(LV);
4225 }
4226
4227 // Anything else isn't considered to be sufficiently constant.
4228 return false;
4229}
4230
John McCall42c8f872010-05-10 23:27:23 +00004231/// Retrieves the "underlying object type" of the given expression,
4232/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004233QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4234 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4235 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004236 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004237 } else if (const Expr *E = B.get<const Expr*>()) {
4238 if (isa<CompoundLiteralExpr>(E))
4239 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004240 }
4241
4242 return QualType();
4243}
4244
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004245bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004246 LValue Base;
Richard Smithc6794852012-05-23 04:13:20 +00004247
4248 {
4249 // The operand of __builtin_object_size is never evaluated for side-effects.
4250 // If there are any, but we can determine the pointed-to object anyway, then
4251 // ignore the side-effects.
4252 SpeculativeEvaluationRAII SpeculativeEval(Info);
4253 if (!EvaluatePointer(E->getArg(0), Base, Info))
4254 return false;
4255 }
John McCall42c8f872010-05-10 23:27:23 +00004256
4257 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004258 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004259
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004260 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004261 if (T.isNull() ||
4262 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004263 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004264 T->isVariablyModifiedType() ||
4265 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004266 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004267
4268 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4269 CharUnits Offset = Base.getLValueOffset();
4270
4271 if (!Offset.isNegative() && Offset <= Size)
4272 Size -= Offset;
4273 else
4274 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004275 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004276}
4277
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004278bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith2c39d712012-04-13 00:45:38 +00004279 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004280 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004281 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004282
4283 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004284 if (TryEvaluateBuiltinObjectSize(E))
4285 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004286
Richard Smith8ae4ec22012-08-07 04:16:51 +00004287 // If evaluating the argument has side-effects, we can't determine the size
4288 // of the object, and so we lower it to unknown now. CodeGen relies on us to
4289 // handle all cases where the expression has side-effects.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004290 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004291 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004292 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004293 return Success(0, E);
4294 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004295
Richard Smithc6794852012-05-23 04:13:20 +00004296 // Expression had no side effects, but we couldn't statically determine the
4297 // size of the referenced object.
Richard Smithf48fdb02011-12-09 22:58:01 +00004298 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004299 }
4300
Benjamin Kramerd1900572012-10-06 14:42:22 +00004301 case Builtin::BI__builtin_bswap16:
Richard Smith70d38f32012-09-28 20:20:52 +00004302 case Builtin::BI__builtin_bswap32:
4303 case Builtin::BI__builtin_bswap64: {
4304 APSInt Val;
4305 if (!EvaluateInteger(E->getArg(0), Val, Info))
4306 return false;
4307
4308 return Success(Val.byteSwap(), E);
4309 }
4310
Chris Lattner019f4e82008-10-06 05:28:25 +00004311 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004312 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004313
Richard Smith80d4b552011-12-28 19:48:30 +00004314 case Builtin::BI__builtin_constant_p:
4315 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004316
Chris Lattner21fb98e2009-09-23 06:06:36 +00004317 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004318 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004319 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004320 return Success(Operand, E);
4321 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004322
4323 case Builtin::BI__builtin_expect:
4324 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004325
Douglas Gregor5726d402010-09-10 06:27:15 +00004326 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004327 // A call to strlen is not a constant expression.
Richard Smith80ad52f2013-01-02 11:42:31 +00004328 if (Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004329 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004330 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4331 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004332 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004333 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004334 case Builtin::BI__builtin_strlen:
4335 // As an extension, we support strlen() and __builtin_strlen() as constant
4336 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004337 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004338 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4339 // The string literal may have embedded null characters. Find the first
4340 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004341 StringRef Str = S->getString();
4342 StringRef::size_type Pos = Str.find(0);
4343 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004344 Str = Str.substr(0, Pos);
4345
4346 return Success(Str.size(), E);
4347 }
4348
Richard Smithf48fdb02011-12-09 22:58:01 +00004349 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004350
Richard Smith2c39d712012-04-13 00:45:38 +00004351 case Builtin::BI__atomic_always_lock_free:
Richard Smithfafbf062012-04-11 17:55:32 +00004352 case Builtin::BI__atomic_is_lock_free:
4353 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedman454b57a2011-10-17 21:44:23 +00004354 APSInt SizeVal;
4355 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4356 return false;
4357
4358 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4359 // of two less than the maximum inline atomic width, we know it is
4360 // lock-free. If the size isn't a power of two, or greater than the
4361 // maximum alignment where we promote atomics, we know it is not lock-free
4362 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4363 // the answer can only be determined at runtime; for example, 16-byte
4364 // atomics have lock-free implementations on some, but not all,
4365 // x86-64 processors.
4366
4367 // Check power-of-two.
4368 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith2c39d712012-04-13 00:45:38 +00004369 if (Size.isPowerOfTwo()) {
4370 // Check against inlining width.
4371 unsigned InlineWidthBits =
4372 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4373 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4374 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4375 Size == CharUnits::One() ||
4376 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4377 Expr::NPC_NeverValueDependent))
4378 // OK, we will inline appropriately-aligned operations of this size,
4379 // and _Atomic(T) is appropriately-aligned.
4380 return Success(1, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004381
Richard Smith2c39d712012-04-13 00:45:38 +00004382 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4383 castAs<PointerType>()->getPointeeType();
4384 if (!PointeeType->isIncompleteType() &&
4385 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4386 // OK, we will inline operations on this object.
4387 return Success(1, E);
4388 }
4389 }
4390 }
Eli Friedman454b57a2011-10-17 21:44:23 +00004391
Richard Smith2c39d712012-04-13 00:45:38 +00004392 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4393 Success(0, E) : Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004394 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004395 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004396}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004397
Richard Smith625b8072011-10-31 01:37:14 +00004398static bool HasSameBase(const LValue &A, const LValue &B) {
4399 if (!A.getLValueBase())
4400 return !B.getLValueBase();
4401 if (!B.getLValueBase())
4402 return false;
4403
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004404 if (A.getLValueBase().getOpaqueValue() !=
4405 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004406 const Decl *ADecl = GetLValueBaseDecl(A);
4407 if (!ADecl)
4408 return false;
4409 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004410 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004411 return false;
4412 }
4413
4414 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004415 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004416}
4417
Richard Smith7b48a292012-02-01 05:53:12 +00004418/// Perform the given integer operation, which is known to need at most BitWidth
4419/// bits, and check for overflow in the original type (if that type was not an
4420/// unsigned type).
4421template<typename Operation>
4422static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4423 const APSInt &LHS, const APSInt &RHS,
4424 unsigned BitWidth, Operation Op) {
4425 if (LHS.isUnsigned())
4426 return Op(LHS, RHS);
4427
4428 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4429 APSInt Result = Value.trunc(LHS.getBitWidth());
Fariborz Jahanianad48a502013-01-24 22:11:45 +00004430 if (Result.extend(BitWidth) != Value) {
4431 if (Info.getIntOverflowCheckMode())
4432 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
4433 diag::warn_integer_constant_overflow)
4434 << Result.toString(10) << E->getType();
4435 else
4436 HandleOverflow(Info, E, Value, E->getType());
4437 }
Richard Smith7b48a292012-02-01 05:53:12 +00004438 return Result;
4439}
4440
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004441namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00004442
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004443/// \brief Data recursive integer evaluator of certain binary operators.
4444///
4445/// We use a data recursive algorithm for binary operators so that we are able
4446/// to handle extreme cases of chained binary operators without causing stack
4447/// overflow.
4448class DataRecursiveIntBinOpEvaluator {
4449 struct EvalResult {
4450 APValue Val;
4451 bool Failed;
4452
4453 EvalResult() : Failed(false) { }
4454
4455 void swap(EvalResult &RHS) {
4456 Val.swap(RHS.Val);
4457 Failed = RHS.Failed;
4458 RHS.Failed = false;
4459 }
4460 };
4461
4462 struct Job {
4463 const Expr *E;
4464 EvalResult LHSResult; // meaningful only for binary operator expression.
4465 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4466
4467 Job() : StoredInfo(0) { }
4468 void startSpeculativeEval(EvalInfo &Info) {
4469 OldEvalStatus = Info.EvalStatus;
4470 Info.EvalStatus.Diag = 0;
4471 StoredInfo = &Info;
4472 }
4473 ~Job() {
4474 if (StoredInfo) {
4475 StoredInfo->EvalStatus = OldEvalStatus;
4476 }
4477 }
4478 private:
4479 EvalInfo *StoredInfo; // non-null if status changed.
4480 Expr::EvalStatus OldEvalStatus;
4481 };
4482
4483 SmallVector<Job, 16> Queue;
4484
4485 IntExprEvaluator &IntEval;
4486 EvalInfo &Info;
4487 APValue &FinalResult;
4488
4489public:
4490 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4491 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4492
4493 /// \brief True if \param E is a binary operator that we are going to handle
4494 /// data recursively.
4495 /// We handle binary operators that are comma, logical, or that have operands
4496 /// with integral or enumeration type.
4497 static bool shouldEnqueue(const BinaryOperator *E) {
4498 return E->getOpcode() == BO_Comma ||
4499 E->isLogicalOp() ||
4500 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4501 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00004502 }
4503
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004504 bool Traverse(const BinaryOperator *E) {
4505 enqueue(E);
4506 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00004507 while (!Queue.empty())
4508 process(PrevResult);
4509
4510 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004511
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004512 FinalResult.swap(PrevResult.Val);
4513 return true;
4514 }
4515
4516private:
4517 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4518 return IntEval.Success(Value, E, Result);
4519 }
4520 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4521 return IntEval.Success(Value, E, Result);
4522 }
4523 bool Error(const Expr *E) {
4524 return IntEval.Error(E);
4525 }
4526 bool Error(const Expr *E, diag::kind D) {
4527 return IntEval.Error(E, D);
4528 }
4529
4530 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4531 return Info.CCEDiag(E, D);
4532 }
4533
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004534 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4535 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004536 bool &SuppressRHSDiags);
4537
4538 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4539 const BinaryOperator *E, APValue &Result);
4540
4541 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4542 Result.Failed = !Evaluate(Result.Val, Info, E);
4543 if (Result.Failed)
4544 Result.Val = APValue();
4545 }
4546
Richard Trieub7783052012-03-21 23:30:30 +00004547 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004548
4549 void enqueue(const Expr *E) {
4550 E = E->IgnoreParens();
4551 Queue.resize(Queue.size()+1);
4552 Queue.back().E = E;
4553 Queue.back().Kind = Job::AnyExprKind;
4554 }
4555};
4556
4557}
4558
4559bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004560 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004561 bool &SuppressRHSDiags) {
4562 if (E->getOpcode() == BO_Comma) {
4563 // Ignore LHS but note if we could not evaluate it.
4564 if (LHSResult.Failed)
4565 Info.EvalStatus.HasSideEffects = true;
4566 return true;
4567 }
4568
4569 if (E->isLogicalOp()) {
4570 bool lhsResult;
4571 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004572 // We were able to evaluate the LHS, see if we can get away with not
4573 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004574 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004575 Success(lhsResult, E, LHSResult.Val);
4576 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004577 }
4578 } else {
4579 // Since we weren't able to evaluate the left hand side, it
4580 // must have had side effects.
4581 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004582
4583 // We can't evaluate the LHS; however, sometimes the result
4584 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4585 // Don't ignore RHS and suppress diagnostics from this arm.
4586 SuppressRHSDiags = true;
4587 }
4588
4589 return true;
4590 }
4591
4592 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4593 E->getRHS()->getType()->isIntegralOrEnumerationType());
4594
4595 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004596 return false; // Ignore RHS;
4597
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004598 return true;
4599}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004600
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004601bool DataRecursiveIntBinOpEvaluator::
4602 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4603 const BinaryOperator *E, APValue &Result) {
4604 if (E->getOpcode() == BO_Comma) {
4605 if (RHSResult.Failed)
4606 return false;
4607 Result = RHSResult.Val;
4608 return true;
4609 }
4610
4611 if (E->isLogicalOp()) {
4612 bool lhsResult, rhsResult;
4613 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4614 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4615
4616 if (LHSIsOK) {
4617 if (RHSIsOK) {
4618 if (E->getOpcode() == BO_LOr)
4619 return Success(lhsResult || rhsResult, E, Result);
4620 else
4621 return Success(lhsResult && rhsResult, E, Result);
4622 }
4623 } else {
4624 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004625 // We can't evaluate the LHS; however, sometimes the result
4626 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4627 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004628 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004629 }
4630 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004631
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004632 return false;
4633 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004634
4635 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4636 E->getRHS()->getType()->isIntegralOrEnumerationType());
4637
4638 if (LHSResult.Failed || RHSResult.Failed)
4639 return false;
4640
4641 const APValue &LHSVal = LHSResult.Val;
4642 const APValue &RHSVal = RHSResult.Val;
4643
4644 // Handle cases like (unsigned long)&a + 4.
4645 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4646 Result = LHSVal;
4647 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4648 RHSVal.getInt().getZExtValue());
4649 if (E->getOpcode() == BO_Add)
4650 Result.getLValueOffset() += AdditionalOffset;
4651 else
4652 Result.getLValueOffset() -= AdditionalOffset;
4653 return true;
4654 }
4655
4656 // Handle cases like 4 + (unsigned long)&a
4657 if (E->getOpcode() == BO_Add &&
4658 RHSVal.isLValue() && LHSVal.isInt()) {
4659 Result = RHSVal;
4660 Result.getLValueOffset() += CharUnits::fromQuantity(
4661 LHSVal.getInt().getZExtValue());
4662 return true;
4663 }
4664
4665 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4666 // Handle (intptr_t)&&A - (intptr_t)&&B.
4667 if (!LHSVal.getLValueOffset().isZero() ||
4668 !RHSVal.getLValueOffset().isZero())
4669 return false;
4670 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4671 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4672 if (!LHSExpr || !RHSExpr)
4673 return false;
4674 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4675 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4676 if (!LHSAddrExpr || !RHSAddrExpr)
4677 return false;
4678 // Make sure both labels come from the same function.
4679 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4680 RHSAddrExpr->getLabel()->getDeclContext())
4681 return false;
4682 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4683 return true;
4684 }
4685
4686 // All the following cases expect both operands to be an integer
4687 if (!LHSVal.isInt() || !RHSVal.isInt())
4688 return Error(E);
4689
4690 const APSInt &LHS = LHSVal.getInt();
4691 APSInt RHS = RHSVal.getInt();
4692
4693 switch (E->getOpcode()) {
4694 default:
4695 return Error(E);
4696 case BO_Mul:
4697 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4698 LHS.getBitWidth() * 2,
4699 std::multiplies<APSInt>()), E,
4700 Result);
4701 case BO_Add:
4702 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4703 LHS.getBitWidth() + 1,
4704 std::plus<APSInt>()), E, Result);
4705 case BO_Sub:
4706 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4707 LHS.getBitWidth() + 1,
4708 std::minus<APSInt>()), E, Result);
4709 case BO_And: return Success(LHS & RHS, E, Result);
4710 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4711 case BO_Or: return Success(LHS | RHS, E, Result);
4712 case BO_Div:
4713 case BO_Rem:
4714 if (RHS == 0)
4715 return Error(E, diag::note_expr_divide_by_zero);
4716 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4717 // not actually undefined behavior in C++11 due to a language defect.
4718 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4719 LHS.isSigned() && LHS.isMinSignedValue())
4720 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4721 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4722 Result);
4723 case BO_Shl: {
David Tweed7a834212013-01-07 16:43:27 +00004724 if (Info.getLangOpts().OpenCL)
4725 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Goulya52d2782013-01-29 15:09:40 +00004726 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed7a834212013-01-07 16:43:27 +00004727 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
4728 RHS.isUnsigned());
4729 else if (RHS.isSigned() && RHS.isNegative()) {
4730 // During constant-folding, a negative shift is an opposite shift. Such
4731 // a shift is not a constant expression.
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004732 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4733 RHS = -RHS;
4734 goto shift_right;
4735 }
4736
4737 shift_left:
4738 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4739 // the shifted type.
4740 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4741 if (SA != RHS) {
4742 CCEDiag(E, diag::note_constexpr_large_shift)
4743 << RHS << E->getType() << LHS.getBitWidth();
4744 } else if (LHS.isSigned()) {
4745 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4746 // operand, and must not overflow the corresponding unsigned type.
4747 if (LHS.isNegative())
4748 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4749 else if (LHS.countLeadingZeros() < SA)
4750 CCEDiag(E, diag::note_constexpr_lshift_discards);
4751 }
4752
4753 return Success(LHS << SA, E, Result);
4754 }
4755 case BO_Shr: {
David Tweed7a834212013-01-07 16:43:27 +00004756 if (Info.getLangOpts().OpenCL)
4757 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Goulya52d2782013-01-29 15:09:40 +00004758 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed7a834212013-01-07 16:43:27 +00004759 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
4760 RHS.isUnsigned());
4761 else if (RHS.isSigned() && RHS.isNegative()) {
4762 // During constant-folding, a negative shift is an opposite shift. Such a
4763 // shift is not a constant expression.
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004764 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4765 RHS = -RHS;
4766 goto shift_left;
4767 }
4768
4769 shift_right:
4770 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4771 // shifted type.
4772 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4773 if (SA != RHS)
4774 CCEDiag(E, diag::note_constexpr_large_shift)
4775 << RHS << E->getType() << LHS.getBitWidth();
4776
4777 return Success(LHS >> SA, E, Result);
4778 }
4779
4780 case BO_LT: return Success(LHS < RHS, E, Result);
4781 case BO_GT: return Success(LHS > RHS, E, Result);
4782 case BO_LE: return Success(LHS <= RHS, E, Result);
4783 case BO_GE: return Success(LHS >= RHS, E, Result);
4784 case BO_EQ: return Success(LHS == RHS, E, Result);
4785 case BO_NE: return Success(LHS != RHS, E, Result);
4786 }
4787}
4788
Richard Trieub7783052012-03-21 23:30:30 +00004789void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004790 Job &job = Queue.back();
4791
4792 switch (job.Kind) {
4793 case Job::AnyExprKind: {
4794 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4795 if (shouldEnqueue(Bop)) {
4796 job.Kind = Job::BinOpKind;
4797 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00004798 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004799 }
4800 }
4801
4802 EvaluateExpr(job.E, Result);
4803 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004804 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004805 }
4806
4807 case Job::BinOpKind: {
4808 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004809 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004810 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004811 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004812 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004813 }
4814 if (SuppressRHSDiags)
4815 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004816 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004817 job.Kind = Job::BinOpVisitedLHSKind;
4818 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00004819 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004820 }
4821
4822 case Job::BinOpVisitedLHSKind: {
4823 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4824 EvalResult RHS;
4825 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00004826 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004827 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004828 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004829 }
4830 }
4831
4832 llvm_unreachable("Invalid Job::Kind!");
4833}
4834
4835bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4836 if (E->isAssignmentOp())
4837 return Error(E);
4838
4839 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4840 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004841
Anders Carlsson286f85e2008-11-16 07:17:21 +00004842 QualType LHSTy = E->getLHS()->getType();
4843 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004844
4845 if (LHSTy->isAnyComplexType()) {
4846 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004847 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004848
Richard Smith745f5142012-01-27 01:14:48 +00004849 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4850 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004851 return false;
4852
Richard Smith745f5142012-01-27 01:14:48 +00004853 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004854 return false;
4855
4856 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004857 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004858 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004859 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004860 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4861
John McCall2de56d12010-08-25 11:45:40 +00004862 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004863 return Success((CR_r == APFloat::cmpEqual &&
4864 CR_i == APFloat::cmpEqual), E);
4865 else {
John McCall2de56d12010-08-25 11:45:40 +00004866 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004867 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004868 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004869 CR_r == APFloat::cmpLessThan ||
4870 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004871 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004872 CR_i == APFloat::cmpLessThan ||
4873 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004874 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004875 } else {
John McCall2de56d12010-08-25 11:45:40 +00004876 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004877 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4878 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4879 else {
John McCall2de56d12010-08-25 11:45:40 +00004880 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004881 "Invalid compex comparison.");
4882 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4883 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4884 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004885 }
4886 }
Mike Stump1eb44332009-09-09 15:08:12 +00004887
Anders Carlsson286f85e2008-11-16 07:17:21 +00004888 if (LHSTy->isRealFloatingType() &&
4889 RHSTy->isRealFloatingType()) {
4890 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004891
Richard Smith745f5142012-01-27 01:14:48 +00004892 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4893 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004894 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004895
Richard Smith745f5142012-01-27 01:14:48 +00004896 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004897 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004898
Anders Carlsson286f85e2008-11-16 07:17:21 +00004899 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004900
Anders Carlsson286f85e2008-11-16 07:17:21 +00004901 switch (E->getOpcode()) {
4902 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004903 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004904 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004905 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004906 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004907 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004908 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004909 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004910 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004911 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004912 E);
John McCall2de56d12010-08-25 11:45:40 +00004913 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004914 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004915 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004916 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004917 || CR == APFloat::cmpLessThan
4918 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004919 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004920 }
Mike Stump1eb44332009-09-09 15:08:12 +00004921
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004922 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004923 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004924 LValue LHSValue, RHSValue;
4925
4926 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4927 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004928 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004929
Richard Smith745f5142012-01-27 01:14:48 +00004930 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004931 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004932
Richard Smith625b8072011-10-31 01:37:14 +00004933 // Reject differing bases from the normal codepath; we special-case
4934 // comparisons to null.
4935 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004936 if (E->getOpcode() == BO_Sub) {
4937 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004938 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4939 return false;
4940 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramer7b2f93c2012-10-03 14:15:39 +00004941 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedman65639282012-01-04 23:13:47 +00004942 if (!LHSExpr || !RHSExpr)
4943 return false;
4944 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4945 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4946 if (!LHSAddrExpr || !RHSAddrExpr)
4947 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004948 // Make sure both labels come from the same function.
4949 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4950 RHSAddrExpr->getLabel()->getDeclContext())
4951 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004952 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004953 return true;
4954 }
Richard Smith9e36b532011-10-31 05:11:32 +00004955 // Inequalities and subtractions between unrelated pointers have
4956 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004957 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004958 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004959 // A constant address may compare equal to the address of a symbol.
4960 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004961 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004962 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4963 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004964 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004965 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004966 // distinct addresses. In clang, the result of such a comparison is
4967 // unspecified, so it is not a constant expression. However, we do know
4968 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004969 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4970 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004971 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004972 // We can't tell whether weak symbols will end up pointing to the same
4973 // object.
4974 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004975 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004976 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004977 // (Note that clang defaults to -fmerge-all-constants, which can
4978 // lead to inconsistent results for comparisons involving the address
4979 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004980 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004981 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004982
Richard Smith15efc4d2012-02-01 08:10:20 +00004983 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4984 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4985
Richard Smithf15fda02012-02-02 01:16:57 +00004986 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4987 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4988
John McCall2de56d12010-08-25 11:45:40 +00004989 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004990 // C++11 [expr.add]p6:
4991 // Unless both pointers point to elements of the same array object, or
4992 // one past the last element of the array object, the behavior is
4993 // undefined.
4994 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4995 !AreElementsOfSameArray(getType(LHSValue.Base),
4996 LHSDesignator, RHSDesignator))
4997 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4998
Chris Lattner4992bdd2010-04-20 17:13:14 +00004999 QualType Type = E->getLHS()->getType();
5000 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00005001
Richard Smith180f4792011-11-10 06:34:14 +00005002 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00005003 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00005004 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00005005
Richard Smith15efc4d2012-02-01 08:10:20 +00005006 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5007 // and produce incorrect results when it overflows. Such behavior
5008 // appears to be non-conforming, but is common, so perhaps we should
5009 // assume the standard intended for such cases to be undefined behavior
5010 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00005011
Richard Smith15efc4d2012-02-01 08:10:20 +00005012 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5013 // overflow in the final conversion to ptrdiff_t.
5014 APSInt LHS(
5015 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5016 APSInt RHS(
5017 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5018 APSInt ElemSize(
5019 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5020 APSInt TrueResult = (LHS - RHS) / ElemSize;
5021 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5022
5023 if (Result.extend(65) != TrueResult)
5024 HandleOverflow(Info, E, TrueResult, E->getType());
5025 return Success(Result, E);
5026 }
Richard Smith82f28582012-01-31 06:41:30 +00005027
5028 // C++11 [expr.rel]p3:
5029 // Pointers to void (after pointer conversions) can be compared, with a
5030 // result defined as follows: If both pointers represent the same
5031 // address or are both the null pointer value, the result is true if the
5032 // operator is <= or >= and false otherwise; otherwise the result is
5033 // unspecified.
5034 // We interpret this as applying to pointers to *cv* void.
5035 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00005036 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00005037 CCEDiag(E, diag::note_constexpr_void_comparison);
5038
Richard Smithf15fda02012-02-02 01:16:57 +00005039 // C++11 [expr.rel]p2:
5040 // - If two pointers point to non-static data members of the same object,
5041 // or to subobjects or array elements fo such members, recursively, the
5042 // pointer to the later declared member compares greater provided the
5043 // two members have the same access control and provided their class is
5044 // not a union.
5045 // [...]
5046 // - Otherwise pointer comparisons are unspecified.
5047 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5048 E->isRelationalOp()) {
5049 bool WasArrayIndex;
5050 unsigned Mismatch =
5051 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5052 RHSDesignator, WasArrayIndex);
5053 // At the point where the designators diverge, the comparison has a
5054 // specified value if:
5055 // - we are comparing array indices
5056 // - we are comparing fields of a union, or fields with the same access
5057 // Otherwise, the result is unspecified and thus the comparison is not a
5058 // constant expression.
5059 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5060 Mismatch < RHSDesignator.Entries.size()) {
5061 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5062 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5063 if (!LF && !RF)
5064 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5065 else if (!LF)
5066 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5067 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5068 << RF->getParent() << RF;
5069 else if (!RF)
5070 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5071 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5072 << LF->getParent() << LF;
5073 else if (!LF->getParent()->isUnion() &&
5074 LF->getAccess() != RF->getAccess())
5075 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5076 << LF << LF->getAccess() << RF << RF->getAccess()
5077 << LF->getParent();
5078 }
5079 }
5080
Eli Friedmana3169882012-04-16 04:30:08 +00005081 // The comparison here must be unsigned, and performed with the same
5082 // width as the pointer.
Eli Friedmana3169882012-04-16 04:30:08 +00005083 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5084 uint64_t CompareLHS = LHSOffset.getQuantity();
5085 uint64_t CompareRHS = RHSOffset.getQuantity();
5086 assert(PtrSize <= 64 && "Unexpected pointer width");
5087 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5088 CompareLHS &= Mask;
5089 CompareRHS &= Mask;
5090
Eli Friedman28503762012-04-16 19:23:57 +00005091 // If there is a base and this is a relational operator, we can only
5092 // compare pointers within the object in question; otherwise, the result
5093 // depends on where the object is located in memory.
5094 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5095 QualType BaseTy = getType(LHSValue.Base);
5096 if (BaseTy->isIncompleteType())
5097 return Error(E);
5098 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5099 uint64_t OffsetLimit = Size.getQuantity();
5100 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5101 return Error(E);
5102 }
5103
Richard Smith625b8072011-10-31 01:37:14 +00005104 switch (E->getOpcode()) {
5105 default: llvm_unreachable("missing comparison operator");
Eli Friedmana3169882012-04-16 04:30:08 +00005106 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5107 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5108 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5109 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5110 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5111 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00005112 }
Anders Carlsson3068d112008-11-16 19:01:22 +00005113 }
5114 }
Richard Smithb02e4622012-02-01 01:42:44 +00005115
5116 if (LHSTy->isMemberPointerType()) {
5117 assert(E->isEqualityOp() && "unexpected member pointer operation");
5118 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5119
5120 MemberPtr LHSValue, RHSValue;
5121
5122 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5123 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5124 return false;
5125
5126 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5127 return false;
5128
5129 // C++11 [expr.eq]p2:
5130 // If both operands are null, they compare equal. Otherwise if only one is
5131 // null, they compare unequal.
5132 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5133 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5134 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5135 }
5136
5137 // Otherwise if either is a pointer to a virtual member function, the
5138 // result is unspecified.
5139 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5140 if (MD->isVirtual())
5141 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5142 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5143 if (MD->isVirtual())
5144 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5145
5146 // Otherwise they compare equal if and only if they would refer to the
5147 // same member of the same most derived object or the same subobject if
5148 // they were dereferenced with a hypothetical object of the associated
5149 // class type.
5150 bool Equal = LHSValue == RHSValue;
5151 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5152 }
5153
Richard Smith26f2cac2012-02-14 22:35:28 +00005154 if (LHSTy->isNullPtrType()) {
5155 assert(E->isComparisonOp() && "unexpected nullptr operation");
5156 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5157 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5158 // are compared, the result is true of the operator is <=, >= or ==, and
5159 // false otherwise.
5160 BinaryOperator::Opcode Opcode = E->getOpcode();
5161 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5162 }
5163
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005164 assert((!LHSTy->isIntegralOrEnumerationType() ||
5165 !RHSTy->isIntegralOrEnumerationType()) &&
5166 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5167 // We can't continue from here for non-integral types.
5168 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005169}
5170
Ken Dyck8b752f12010-01-27 17:10:57 +00005171CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005172 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5173 // result shall be the alignment of the referenced type."
5174 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5175 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005176
5177 // __alignof is defined to return the preferred alignment.
5178 return Info.Ctx.toCharUnitsFromBits(
5179 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005180}
5181
Ken Dyck8b752f12010-01-27 17:10:57 +00005182CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005183 E = E->IgnoreParens();
5184
5185 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005186 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005187 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005188 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5189 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005190
Chris Lattneraf707ab2009-01-24 21:53:27 +00005191 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005192 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5193 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005194
Chris Lattnere9feb472009-01-24 21:09:06 +00005195 return GetAlignOfType(E->getType());
5196}
5197
5198
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005199/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5200/// a result as the expression's type.
5201bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5202 const UnaryExprOrTypeTraitExpr *E) {
5203 switch(E->getKind()) {
5204 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005205 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005206 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005207 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005208 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005209 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005210
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005211 case UETT_VecStep: {
5212 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005213
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005214 if (Ty->isVectorType()) {
Ted Kremenek890f0f12012-08-23 20:46:57 +00005215 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005216
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005217 // The vec_step built-in functions that take a 3-component
5218 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5219 if (n == 3)
5220 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005221
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005222 return Success(n, E);
5223 } else
5224 return Success(1, E);
5225 }
5226
5227 case UETT_SizeOf: {
5228 QualType SrcTy = E->getTypeOfArgument();
5229 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5230 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005231 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5232 SrcTy = Ref->getPointeeType();
5233
Richard Smith180f4792011-11-10 06:34:14 +00005234 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005235 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005236 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005237 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005238 }
5239 }
5240
5241 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005242}
5243
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005244bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005245 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005246 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005247 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005248 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005249 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005250 for (unsigned i = 0; i != n; ++i) {
5251 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5252 switch (ON.getKind()) {
5253 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005254 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005255 APSInt IdxResult;
5256 if (!EvaluateInteger(Idx, IdxResult, Info))
5257 return false;
5258 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5259 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005260 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005261 CurrentType = AT->getElementType();
5262 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5263 Result += IdxResult.getSExtValue() * ElementSize;
5264 break;
5265 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005266
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005267 case OffsetOfExpr::OffsetOfNode::Field: {
5268 FieldDecl *MemberDecl = ON.getField();
5269 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005270 if (!RT)
5271 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005272 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005273 if (RD->isInvalidDecl()) return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005274 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005275 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005276 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005277 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005278 CurrentType = MemberDecl->getType().getNonReferenceType();
5279 break;
5280 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005281
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005282 case OffsetOfExpr::OffsetOfNode::Identifier:
5283 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005284
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005285 case OffsetOfExpr::OffsetOfNode::Base: {
5286 CXXBaseSpecifier *BaseSpec = ON.getBase();
5287 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005288 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005289
5290 // Find the layout of the class whose base we are looking into.
5291 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005292 if (!RT)
5293 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005294 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005295 if (RD->isInvalidDecl()) return false;
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005296 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5297
5298 // Find the base class itself.
5299 CurrentType = BaseSpec->getType();
5300 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5301 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005302 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005303
5304 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005305 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005306 break;
5307 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005308 }
5309 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005310 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005311}
5312
Chris Lattnerb542afe2008-07-11 19:10:17 +00005313bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005314 switch (E->getOpcode()) {
5315 default:
5316 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5317 // See C99 6.6p3.
5318 return Error(E);
5319 case UO_Extension:
5320 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5321 // If so, we could clear the diagnostic ID.
5322 return Visit(E->getSubExpr());
5323 case UO_Plus:
5324 // The result is just the value.
5325 return Visit(E->getSubExpr());
5326 case UO_Minus: {
5327 if (!Visit(E->getSubExpr()))
5328 return false;
5329 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005330 const APSInt &Value = Result.getInt();
5331 if (Value.isSigned() && Value.isMinSignedValue())
5332 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5333 E->getType());
5334 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005335 }
5336 case UO_Not: {
5337 if (!Visit(E->getSubExpr()))
5338 return false;
5339 if (!Result.isInt()) return Error(E);
5340 return Success(~Result.getInt(), E);
5341 }
5342 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005343 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005344 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005345 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005346 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005347 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005348 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005349}
Mike Stump1eb44332009-09-09 15:08:12 +00005350
Chris Lattner732b2232008-07-12 01:15:53 +00005351/// HandleCast - This is used to evaluate implicit or explicit casts where the
5352/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005353bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5354 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005355 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005356 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005357
Eli Friedman46a52322011-03-25 00:43:55 +00005358 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005359 case CK_BaseToDerived:
5360 case CK_DerivedToBase:
5361 case CK_UncheckedDerivedToBase:
5362 case CK_Dynamic:
5363 case CK_ToUnion:
5364 case CK_ArrayToPointerDecay:
5365 case CK_FunctionToPointerDecay:
5366 case CK_NullToPointer:
5367 case CK_NullToMemberPointer:
5368 case CK_BaseToDerivedMemberPointer:
5369 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005370 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005371 case CK_ConstructorConversion:
5372 case CK_IntegralToPointer:
5373 case CK_ToVoid:
5374 case CK_VectorSplat:
5375 case CK_IntegralToFloating:
5376 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005377 case CK_CPointerToObjCPointerCast:
5378 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005379 case CK_AnyPointerToBlockPointerCast:
5380 case CK_ObjCObjectLValueCast:
5381 case CK_FloatingRealToComplex:
5382 case CK_FloatingComplexToReal:
5383 case CK_FloatingComplexCast:
5384 case CK_FloatingComplexToIntegralComplex:
5385 case CK_IntegralRealToComplex:
5386 case CK_IntegralComplexCast:
5387 case CK_IntegralComplexToFloatingComplex:
Eli Friedmana6c66ce2012-08-31 00:14:07 +00005388 case CK_BuiltinFnToFnPtr:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005389 case CK_ZeroToOCLEvent:
Eli Friedman46a52322011-03-25 00:43:55 +00005390 llvm_unreachable("invalid cast kind for integral value");
5391
Eli Friedmane50c2972011-03-25 19:07:11 +00005392 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005393 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005394 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005395 case CK_ARCProduceObject:
5396 case CK_ARCConsumeObject:
5397 case CK_ARCReclaimReturnedObject:
5398 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005399 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005400 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005401
Richard Smith7d580a42012-01-17 21:17:26 +00005402 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005403 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005404 case CK_AtomicToNonAtomic:
5405 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005406 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005407 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005408
5409 case CK_MemberPointerToBoolean:
5410 case CK_PointerToBoolean:
5411 case CK_IntegralToBoolean:
5412 case CK_FloatingToBoolean:
5413 case CK_FloatingComplexToBoolean:
5414 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005415 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005416 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005417 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005418 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005419 }
5420
Eli Friedman46a52322011-03-25 00:43:55 +00005421 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005422 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005423 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005424
Eli Friedmanbe265702009-02-20 01:15:07 +00005425 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005426 // Allow casts of address-of-label differences if they are no-ops
5427 // or narrowing. (The narrowing case isn't actually guaranteed to
5428 // be constant-evaluatable except in some narrow cases which are hard
5429 // to detect here. We let it through on the assumption the user knows
5430 // what they are doing.)
5431 if (Result.isAddrLabelDiff())
5432 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005433 // Only allow casts of lvalues if they are lossless.
5434 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5435 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005436
Richard Smithf72fccf2012-01-30 22:27:01 +00005437 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5438 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005439 }
Mike Stump1eb44332009-09-09 15:08:12 +00005440
Eli Friedman46a52322011-03-25 00:43:55 +00005441 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005442 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5443
John McCallefdb83e2010-05-07 21:00:08 +00005444 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005445 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005446 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005447
Daniel Dunbardd211642009-02-19 22:24:01 +00005448 if (LV.getLValueBase()) {
5449 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005450 // FIXME: Allow a larger integer size than the pointer size, and allow
5451 // narrowing back down to pointer width in subsequent integral casts.
5452 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005453 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005454 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005455
Richard Smithb755a9d2011-11-16 07:18:12 +00005456 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005457 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005458 return true;
5459 }
5460
Ken Dycka7305832010-01-15 12:37:54 +00005461 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5462 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005463 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005464 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005465
Eli Friedman46a52322011-03-25 00:43:55 +00005466 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005467 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005468 if (!EvaluateComplex(SubExpr, C, Info))
5469 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005470 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005471 }
Eli Friedman2217c872009-02-22 11:46:18 +00005472
Eli Friedman46a52322011-03-25 00:43:55 +00005473 case CK_FloatingToIntegral: {
5474 APFloat F(0.0);
5475 if (!EvaluateFloat(SubExpr, F, Info))
5476 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005477
Richard Smithc1c5f272011-12-13 06:39:58 +00005478 APSInt Value;
5479 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5480 return false;
5481 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005482 }
5483 }
Mike Stump1eb44332009-09-09 15:08:12 +00005484
Eli Friedman46a52322011-03-25 00:43:55 +00005485 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005486}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005487
Eli Friedman722c7172009-02-28 03:59:05 +00005488bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5489 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005490 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005491 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5492 return false;
5493 if (!LV.isComplexInt())
5494 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005495 return Success(LV.getComplexIntReal(), E);
5496 }
5497
5498 return Visit(E->getSubExpr());
5499}
5500
Eli Friedman664a1042009-02-27 04:45:43 +00005501bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005502 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005503 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005504 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5505 return false;
5506 if (!LV.isComplexInt())
5507 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005508 return Success(LV.getComplexIntImag(), E);
5509 }
5510
Richard Smith8327fad2011-10-24 18:44:57 +00005511 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005512 return Success(0, E);
5513}
5514
Douglas Gregoree8aff02011-01-04 17:33:58 +00005515bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5516 return Success(E->getPackLength(), E);
5517}
5518
Sebastian Redl295995c2010-09-10 20:55:47 +00005519bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5520 return Success(E->getValue(), E);
5521}
5522
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005523//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005524// Float Evaluation
5525//===----------------------------------------------------------------------===//
5526
5527namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005528class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005529 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005530 APFloat &Result;
5531public:
5532 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005533 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005534
Richard Smith1aa0be82012-03-03 22:46:17 +00005535 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005536 Result = V.getFloat();
5537 return true;
5538 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005539
Richard Smith51201882011-12-30 21:15:51 +00005540 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005541 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5542 return true;
5543 }
5544
Chris Lattner019f4e82008-10-06 05:28:25 +00005545 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005546
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005547 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005548 bool VisitBinaryOperator(const BinaryOperator *E);
5549 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005550 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005551
John McCallabd3a852010-05-07 22:08:54 +00005552 bool VisitUnaryReal(const UnaryOperator *E);
5553 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005554
Richard Smith51201882011-12-30 21:15:51 +00005555 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005556};
5557} // end anonymous namespace
5558
5559static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005560 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005561 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005562}
5563
Jay Foad4ba2a172011-01-12 09:06:06 +00005564static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005565 QualType ResultTy,
5566 const Expr *Arg,
5567 bool SNaN,
5568 llvm::APFloat &Result) {
5569 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5570 if (!S) return false;
5571
5572 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5573
5574 llvm::APInt fill;
5575
5576 // Treat empty strings as if they were zero.
5577 if (S->getString().empty())
5578 fill = llvm::APInt(32, 0);
5579 else if (S->getString().getAsInteger(0, fill))
5580 return false;
5581
5582 if (SNaN)
5583 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5584 else
5585 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5586 return true;
5587}
5588
Chris Lattner019f4e82008-10-06 05:28:25 +00005589bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005590 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005591 default:
5592 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5593
Chris Lattner019f4e82008-10-06 05:28:25 +00005594 case Builtin::BI__builtin_huge_val:
5595 case Builtin::BI__builtin_huge_valf:
5596 case Builtin::BI__builtin_huge_vall:
5597 case Builtin::BI__builtin_inf:
5598 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005599 case Builtin::BI__builtin_infl: {
5600 const llvm::fltSemantics &Sem =
5601 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005602 Result = llvm::APFloat::getInf(Sem);
5603 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005604 }
Mike Stump1eb44332009-09-09 15:08:12 +00005605
John McCalldb7b72a2010-02-28 13:00:19 +00005606 case Builtin::BI__builtin_nans:
5607 case Builtin::BI__builtin_nansf:
5608 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005609 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5610 true, Result))
5611 return Error(E);
5612 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005613
Chris Lattner9e621712008-10-06 06:31:58 +00005614 case Builtin::BI__builtin_nan:
5615 case Builtin::BI__builtin_nanf:
5616 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005617 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005618 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005619 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5620 false, Result))
5621 return Error(E);
5622 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005623
5624 case Builtin::BI__builtin_fabs:
5625 case Builtin::BI__builtin_fabsf:
5626 case Builtin::BI__builtin_fabsl:
5627 if (!EvaluateFloat(E->getArg(0), Result, Info))
5628 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005629
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005630 if (Result.isNegative())
5631 Result.changeSign();
5632 return true;
5633
Mike Stump1eb44332009-09-09 15:08:12 +00005634 case Builtin::BI__builtin_copysign:
5635 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005636 case Builtin::BI__builtin_copysignl: {
5637 APFloat RHS(0.);
5638 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5639 !EvaluateFloat(E->getArg(1), RHS, Info))
5640 return false;
5641 Result.copySign(RHS);
5642 return true;
5643 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005644 }
5645}
5646
John McCallabd3a852010-05-07 22:08:54 +00005647bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005648 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5649 ComplexValue CV;
5650 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5651 return false;
5652 Result = CV.FloatReal;
5653 return true;
5654 }
5655
5656 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005657}
5658
5659bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005660 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5661 ComplexValue CV;
5662 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5663 return false;
5664 Result = CV.FloatImag;
5665 return true;
5666 }
5667
Richard Smith8327fad2011-10-24 18:44:57 +00005668 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005669 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5670 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005671 return true;
5672}
5673
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005674bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005675 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005676 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005677 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005678 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005679 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005680 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5681 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005682 Result.changeSign();
5683 return true;
5684 }
5685}
Chris Lattner019f4e82008-10-06 05:28:25 +00005686
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005687bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005688 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5689 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005690
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005691 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005692 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5693 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005694 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005695 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005696 return false;
5697
5698 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005699 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005700 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005701 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005702 break;
John McCall2de56d12010-08-25 11:45:40 +00005703 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005704 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005705 break;
John McCall2de56d12010-08-25 11:45:40 +00005706 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005707 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005708 break;
John McCall2de56d12010-08-25 11:45:40 +00005709 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005710 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005711 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005712 }
Richard Smith7b48a292012-02-01 05:53:12 +00005713
5714 if (Result.isInfinity() || Result.isNaN())
5715 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5716 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005717}
5718
5719bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5720 Result = E->getValue();
5721 return true;
5722}
5723
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005724bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5725 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005726
Eli Friedman2a523ee2011-03-25 00:54:52 +00005727 switch (E->getCastKind()) {
5728 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005729 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005730
5731 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005732 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005733 return EvaluateInteger(SubExpr, IntResult, Info) &&
5734 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5735 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005736 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005737
5738 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005739 if (!Visit(SubExpr))
5740 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005741 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5742 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005743 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005744
Eli Friedman2a523ee2011-03-25 00:54:52 +00005745 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005746 ComplexValue V;
5747 if (!EvaluateComplex(SubExpr, V, Info))
5748 return false;
5749 Result = V.getComplexFloatReal();
5750 return true;
5751 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005752 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005753}
5754
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005755//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005756// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005757//===----------------------------------------------------------------------===//
5758
5759namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005760class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005761 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005762 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005763
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005764public:
John McCallf4cf1a12010-05-07 17:22:02 +00005765 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005766 : ExprEvaluatorBaseTy(info), Result(Result) {}
5767
Richard Smith1aa0be82012-03-03 22:46:17 +00005768 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005769 Result.setFrom(V);
5770 return true;
5771 }
Mike Stump1eb44332009-09-09 15:08:12 +00005772
Eli Friedman7ead5c72012-01-10 04:58:17 +00005773 bool ZeroInitialization(const Expr *E);
5774
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005775 //===--------------------------------------------------------------------===//
5776 // Visitor Methods
5777 //===--------------------------------------------------------------------===//
5778
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005779 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005780 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005781 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005782 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005783 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005784};
5785} // end anonymous namespace
5786
John McCallf4cf1a12010-05-07 17:22:02 +00005787static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5788 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005789 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005790 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005791}
5792
Eli Friedman7ead5c72012-01-10 04:58:17 +00005793bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek890f0f12012-08-23 20:46:57 +00005794 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005795 if (ElemTy->isRealFloatingType()) {
5796 Result.makeComplexFloat();
5797 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5798 Result.FloatReal = Zero;
5799 Result.FloatImag = Zero;
5800 } else {
5801 Result.makeComplexInt();
5802 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5803 Result.IntReal = Zero;
5804 Result.IntImag = Zero;
5805 }
5806 return true;
5807}
5808
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005809bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5810 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005811
5812 if (SubExpr->getType()->isRealFloatingType()) {
5813 Result.makeComplexFloat();
5814 APFloat &Imag = Result.FloatImag;
5815 if (!EvaluateFloat(SubExpr, Imag, Info))
5816 return false;
5817
5818 Result.FloatReal = APFloat(Imag.getSemantics());
5819 return true;
5820 } else {
5821 assert(SubExpr->getType()->isIntegerType() &&
5822 "Unexpected imaginary literal.");
5823
5824 Result.makeComplexInt();
5825 APSInt &Imag = Result.IntImag;
5826 if (!EvaluateInteger(SubExpr, Imag, Info))
5827 return false;
5828
5829 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5830 return true;
5831 }
5832}
5833
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005834bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005835
John McCall8786da72010-12-14 17:51:41 +00005836 switch (E->getCastKind()) {
5837 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005838 case CK_BaseToDerived:
5839 case CK_DerivedToBase:
5840 case CK_UncheckedDerivedToBase:
5841 case CK_Dynamic:
5842 case CK_ToUnion:
5843 case CK_ArrayToPointerDecay:
5844 case CK_FunctionToPointerDecay:
5845 case CK_NullToPointer:
5846 case CK_NullToMemberPointer:
5847 case CK_BaseToDerivedMemberPointer:
5848 case CK_DerivedToBaseMemberPointer:
5849 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005850 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005851 case CK_ConstructorConversion:
5852 case CK_IntegralToPointer:
5853 case CK_PointerToIntegral:
5854 case CK_PointerToBoolean:
5855 case CK_ToVoid:
5856 case CK_VectorSplat:
5857 case CK_IntegralCast:
5858 case CK_IntegralToBoolean:
5859 case CK_IntegralToFloating:
5860 case CK_FloatingToIntegral:
5861 case CK_FloatingToBoolean:
5862 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005863 case CK_CPointerToObjCPointerCast:
5864 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005865 case CK_AnyPointerToBlockPointerCast:
5866 case CK_ObjCObjectLValueCast:
5867 case CK_FloatingComplexToReal:
5868 case CK_FloatingComplexToBoolean:
5869 case CK_IntegralComplexToReal:
5870 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005871 case CK_ARCProduceObject:
5872 case CK_ARCConsumeObject:
5873 case CK_ARCReclaimReturnedObject:
5874 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005875 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmana6c66ce2012-08-31 00:14:07 +00005876 case CK_BuiltinFnToFnPtr:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005877 case CK_ZeroToOCLEvent:
John McCall8786da72010-12-14 17:51:41 +00005878 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005879
John McCall8786da72010-12-14 17:51:41 +00005880 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005881 case CK_AtomicToNonAtomic:
5882 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005883 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005884 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005885
5886 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005887 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005888 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005889 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005890
5891 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005892 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005893 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005894 return false;
5895
John McCall8786da72010-12-14 17:51:41 +00005896 Result.makeComplexFloat();
5897 Result.FloatImag = APFloat(Real.getSemantics());
5898 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005899 }
5900
John McCall8786da72010-12-14 17:51:41 +00005901 case CK_FloatingComplexCast: {
5902 if (!Visit(E->getSubExpr()))
5903 return false;
5904
5905 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5906 QualType From
5907 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5908
Richard Smithc1c5f272011-12-13 06:39:58 +00005909 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5910 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005911 }
5912
5913 case CK_FloatingComplexToIntegralComplex: {
5914 if (!Visit(E->getSubExpr()))
5915 return false;
5916
5917 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5918 QualType From
5919 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5920 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005921 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5922 To, Result.IntReal) &&
5923 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5924 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005925 }
5926
5927 case CK_IntegralRealToComplex: {
5928 APSInt &Real = Result.IntReal;
5929 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5930 return false;
5931
5932 Result.makeComplexInt();
5933 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5934 return true;
5935 }
5936
5937 case CK_IntegralComplexCast: {
5938 if (!Visit(E->getSubExpr()))
5939 return false;
5940
5941 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5942 QualType From
5943 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5944
Richard Smithf72fccf2012-01-30 22:27:01 +00005945 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5946 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005947 return true;
5948 }
5949
5950 case CK_IntegralComplexToFloatingComplex: {
5951 if (!Visit(E->getSubExpr()))
5952 return false;
5953
Ted Kremenek890f0f12012-08-23 20:46:57 +00005954 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005955 QualType From
Ted Kremenek890f0f12012-08-23 20:46:57 +00005956 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005957 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005958 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5959 To, Result.FloatReal) &&
5960 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5961 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005962 }
5963 }
5964
5965 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005966}
5967
John McCallf4cf1a12010-05-07 17:22:02 +00005968bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005969 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005970 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5971
Richard Smith745f5142012-01-27 01:14:48 +00005972 bool LHSOK = Visit(E->getLHS());
5973 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005974 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005975
John McCallf4cf1a12010-05-07 17:22:02 +00005976 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005977 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005978 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005979
Daniel Dunbar3f279872009-01-29 01:32:56 +00005980 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5981 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005982 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005983 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005984 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005985 if (Result.isComplexFloat()) {
5986 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5987 APFloat::rmNearestTiesToEven);
5988 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5989 APFloat::rmNearestTiesToEven);
5990 } else {
5991 Result.getComplexIntReal() += RHS.getComplexIntReal();
5992 Result.getComplexIntImag() += RHS.getComplexIntImag();
5993 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005994 break;
John McCall2de56d12010-08-25 11:45:40 +00005995 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005996 if (Result.isComplexFloat()) {
5997 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5998 APFloat::rmNearestTiesToEven);
5999 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6000 APFloat::rmNearestTiesToEven);
6001 } else {
6002 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6003 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6004 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00006005 break;
John McCall2de56d12010-08-25 11:45:40 +00006006 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00006007 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00006008 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00006009 APFloat &LHS_r = LHS.getComplexFloatReal();
6010 APFloat &LHS_i = LHS.getComplexFloatImag();
6011 APFloat &RHS_r = RHS.getComplexFloatReal();
6012 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00006013
Daniel Dunbar3f279872009-01-29 01:32:56 +00006014 APFloat Tmp = LHS_r;
6015 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6016 Result.getComplexFloatReal() = Tmp;
6017 Tmp = LHS_i;
6018 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6019 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6020
6021 Tmp = LHS_r;
6022 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6023 Result.getComplexFloatImag() = Tmp;
6024 Tmp = LHS_i;
6025 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6026 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6027 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00006028 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00006029 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006030 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6031 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00006032 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006033 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6034 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6035 }
6036 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006037 case BO_Div:
6038 if (Result.isComplexFloat()) {
6039 ComplexValue LHS = Result;
6040 APFloat &LHS_r = LHS.getComplexFloatReal();
6041 APFloat &LHS_i = LHS.getComplexFloatImag();
6042 APFloat &RHS_r = RHS.getComplexFloatReal();
6043 APFloat &RHS_i = RHS.getComplexFloatImag();
6044 APFloat &Res_r = Result.getComplexFloatReal();
6045 APFloat &Res_i = Result.getComplexFloatImag();
6046
6047 APFloat Den = RHS_r;
6048 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6049 APFloat Tmp = RHS_i;
6050 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6051 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6052
6053 Res_r = LHS_r;
6054 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6055 Tmp = LHS_i;
6056 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6057 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6058 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6059
6060 Res_i = LHS_i;
6061 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6062 Tmp = LHS_r;
6063 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6064 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6065 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6066 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00006067 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6068 return Error(E, diag::note_expr_divide_by_zero);
6069
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006070 ComplexValue LHS = Result;
6071 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6072 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6073 Result.getComplexIntReal() =
6074 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6075 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6076 Result.getComplexIntImag() =
6077 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6078 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6079 }
6080 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006081 }
6082
John McCallf4cf1a12010-05-07 17:22:02 +00006083 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006084}
6085
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006086bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6087 // Get the operand value into 'Result'.
6088 if (!Visit(E->getSubExpr()))
6089 return false;
6090
6091 switch (E->getOpcode()) {
6092 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00006093 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006094 case UO_Extension:
6095 return true;
6096 case UO_Plus:
6097 // The result is always just the subexpr.
6098 return true;
6099 case UO_Minus:
6100 if (Result.isComplexFloat()) {
6101 Result.getComplexFloatReal().changeSign();
6102 Result.getComplexFloatImag().changeSign();
6103 }
6104 else {
6105 Result.getComplexIntReal() = -Result.getComplexIntReal();
6106 Result.getComplexIntImag() = -Result.getComplexIntImag();
6107 }
6108 return true;
6109 case UO_Not:
6110 if (Result.isComplexFloat())
6111 Result.getComplexFloatImag().changeSign();
6112 else
6113 Result.getComplexIntImag() = -Result.getComplexIntImag();
6114 return true;
6115 }
6116}
6117
Eli Friedman7ead5c72012-01-10 04:58:17 +00006118bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6119 if (E->getNumInits() == 2) {
6120 if (E->getType()->isComplexType()) {
6121 Result.makeComplexFloat();
6122 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6123 return false;
6124 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6125 return false;
6126 } else {
6127 Result.makeComplexInt();
6128 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6129 return false;
6130 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6131 return false;
6132 }
6133 return true;
6134 }
6135 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6136}
6137
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00006138//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00006139// Void expression evaluation, primarily for a cast to void on the LHS of a
6140// comma operator
6141//===----------------------------------------------------------------------===//
6142
6143namespace {
6144class VoidExprEvaluator
6145 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6146public:
6147 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6148
Richard Smith1aa0be82012-03-03 22:46:17 +00006149 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00006150
6151 bool VisitCastExpr(const CastExpr *E) {
6152 switch (E->getCastKind()) {
6153 default:
6154 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6155 case CK_ToVoid:
6156 VisitIgnoredValue(E->getSubExpr());
6157 return true;
6158 }
6159 }
6160};
6161} // end anonymous namespace
6162
6163static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6164 assert(E->isRValue() && E->getType()->isVoidType());
6165 return VoidExprEvaluator(Info).Visit(E);
6166}
6167
6168//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006169// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006170//===----------------------------------------------------------------------===//
6171
Richard Smith1aa0be82012-03-03 22:46:17 +00006172static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006173 // In C, function designators are not lvalues, but we evaluate them as if they
6174 // are.
6175 if (E->isGLValue() || E->getType()->isFunctionType()) {
6176 LValue LV;
6177 if (!EvaluateLValue(E, LV, Info))
6178 return false;
6179 LV.moveInto(Result);
6180 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006181 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006182 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006183 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006184 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006185 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006186 } else if (E->getType()->hasPointerRepresentation()) {
6187 LValue LV;
6188 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006189 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006190 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006191 } else if (E->getType()->isRealFloatingType()) {
6192 llvm::APFloat F(0.0);
6193 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006194 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006195 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006196 } else if (E->getType()->isAnyComplexType()) {
6197 ComplexValue C;
6198 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006199 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006200 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006201 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006202 MemberPtr P;
6203 if (!EvaluateMemberPointer(E, P, Info))
6204 return false;
6205 P.moveInto(Result);
6206 return true;
Richard Smith51201882011-12-30 21:15:51 +00006207 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006208 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006209 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006210 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006211 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006212 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006213 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006214 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006215 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006216 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6217 return false;
6218 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006219 } else if (E->getType()->isVoidType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00006220 if (!Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006221 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00006222 << E->getType();
Richard Smithaa9c3502011-12-07 00:43:50 +00006223 if (!EvaluateVoid(E, Info))
6224 return false;
Richard Smith80ad52f2013-01-02 11:42:31 +00006225 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006226 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006227 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006228 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006229 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006230 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006231 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006232
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006233 return true;
6234}
6235
Richard Smith83587db2012-02-15 02:18:13 +00006236/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6237/// cases, the in-place evaluation is essential, since later initializers for
6238/// an object can indirectly refer to subobjects which were initialized earlier.
6239static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6240 const Expr *E, CheckConstantExpressionKind CCEK,
6241 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006242 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006243 return false;
6244
6245 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006246 // Evaluate arrays and record types in-place, so that later initializers can
6247 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006248 if (E->getType()->isArrayType())
6249 return EvaluateArray(E, This, Result, Info);
6250 else if (E->getType()->isRecordType())
6251 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006252 }
6253
6254 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006255 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006256}
6257
Richard Smithf48fdb02011-12-09 22:58:01 +00006258/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6259/// lvalue-to-rvalue cast if it is an lvalue.
6260static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006261 if (!CheckLiteralType(Info, E))
6262 return false;
6263
Richard Smith1aa0be82012-03-03 22:46:17 +00006264 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006265 return false;
6266
6267 if (E->isGLValue()) {
6268 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006269 LV.setFrom(Info.Ctx, Result);
6270 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006271 return false;
6272 }
6273
Richard Smith1aa0be82012-03-03 22:46:17 +00006274 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006275 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006276}
Richard Smithc49bd112011-10-28 17:51:58 +00006277
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006278static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
6279 const ASTContext &Ctx, bool &IsConst) {
6280 // Fast-path evaluations of integer literals, since we sometimes see files
6281 // containing vast quantities of these.
6282 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
6283 Result.Val = APValue(APSInt(L->getValue(),
6284 L->getType()->isUnsignedIntegerType()));
6285 IsConst = true;
6286 return true;
6287 }
6288
6289 // FIXME: Evaluating values of large array and record types can cause
6290 // performance problems. Only do so in C++11 for now.
6291 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
6292 Exp->getType()->isRecordType()) &&
6293 !Ctx.getLangOpts().CPlusPlus11) {
6294 IsConst = false;
6295 return true;
6296 }
6297 return false;
6298}
6299
6300
Richard Smith51f47082011-10-29 00:50:52 +00006301/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006302/// any crazy technique (that has nothing to do with language standards) that
6303/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006304/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6305/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006306bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006307 bool IsConst;
6308 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
6309 return IsConst;
6310
Richard Smithf48fdb02011-12-09 22:58:01 +00006311 EvalInfo Info(Ctx, Result);
6312 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006313}
6314
Jay Foad4ba2a172011-01-12 09:06:06 +00006315bool Expr::EvaluateAsBooleanCondition(bool &Result,
6316 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006317 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006318 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006319 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006320}
6321
Richard Smith80d4b552011-12-28 19:48:30 +00006322bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6323 SideEffectsKind AllowSideEffects) const {
6324 if (!getType()->isIntegralOrEnumerationType())
6325 return false;
6326
Richard Smithc49bd112011-10-28 17:51:58 +00006327 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006328 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6329 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006330 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006331
Richard Smithc49bd112011-10-28 17:51:58 +00006332 Result = ExprResult.Val.getInt();
6333 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006334}
6335
Jay Foad4ba2a172011-01-12 09:06:06 +00006336bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006337 EvalInfo Info(Ctx, Result);
6338
John McCallefdb83e2010-05-07 21:00:08 +00006339 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006340 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6341 !CheckLValueConstantExpression(Info, getExprLoc(),
6342 Ctx.getLValueReferenceType(getType()), LV))
6343 return false;
6344
Richard Smith1aa0be82012-03-03 22:46:17 +00006345 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006346 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006347}
6348
Richard Smith099e7f62011-12-19 06:19:21 +00006349bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6350 const VarDecl *VD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006351 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006352 // FIXME: Evaluating initializers for large array and record types can cause
6353 // performance problems. Only do so in C++11 for now.
6354 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00006355 !Ctx.getLangOpts().CPlusPlus11)
Richard Smith2d6a5672012-01-14 04:30:29 +00006356 return false;
6357
Richard Smith099e7f62011-12-19 06:19:21 +00006358 Expr::EvalStatus EStatus;
6359 EStatus.Diag = &Notes;
6360
6361 EvalInfo InitInfo(Ctx, EStatus);
6362 InitInfo.setEvaluatingDecl(VD, Value);
6363
6364 LValue LVal;
6365 LVal.set(VD);
6366
Richard Smith51201882011-12-30 21:15:51 +00006367 // C++11 [basic.start.init]p2:
6368 // Variables with static storage duration or thread storage duration shall be
6369 // zero-initialized before any other initialization takes place.
6370 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006371 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006372 !VD->getType()->isReferenceType()) {
6373 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006374 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6375 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006376 return false;
6377 }
6378
Richard Smith83587db2012-02-15 02:18:13 +00006379 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6380 /*AllowNonLiteralTypes=*/true) ||
6381 EStatus.HasSideEffects)
6382 return false;
6383
6384 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6385 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006386}
6387
Richard Smith51f47082011-10-29 00:50:52 +00006388/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6389/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006390bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006391 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006392 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006393}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006394
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +00006395APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006396 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006397 EvalResult EvalResult;
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +00006398 EvalResult.Diag = Diag;
Richard Smith51f47082011-10-29 00:50:52 +00006399 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006400 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006401 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006402 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006403
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006404 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006405}
John McCalld905f5a2010-05-07 05:32:02 +00006406
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006407void Expr::EvaluateForOverflow(const ASTContext &Ctx,
6408 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
6409 bool IsConst;
6410 EvalResult EvalResult;
6411 EvalResult.Diag = Diags;
6412 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
6413 EvalInfo Info(Ctx, EvalResult, true);
6414 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
6415 }
6416}
6417
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006418 bool Expr::EvalResult::isGlobalLValue() const {
6419 assert(Val.isLValue());
6420 return IsGlobalLValue(Val.getLValueBase());
6421 }
6422
6423
John McCalld905f5a2010-05-07 05:32:02 +00006424/// isIntegerConstantExpr - this recursive routine will test if an expression is
6425/// an integer constant expression.
6426
6427/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6428/// comma, etc
John McCalld905f5a2010-05-07 05:32:02 +00006429
6430// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smithceb59d92012-12-28 13:25:52 +00006431// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
6432// and a (possibly null) SourceLocation indicating the location of the problem.
6433//
John McCalld905f5a2010-05-07 05:32:02 +00006434// Note that to reduce code duplication, this helper does no evaluation
6435// itself; the caller checks whether the expression is evaluatable, and
6436// in the rare cases where CheckICE actually cares about the evaluated
6437// value, it calls into Evalute.
John McCalld905f5a2010-05-07 05:32:02 +00006438
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006439namespace {
6440
Richard Smithceb59d92012-12-28 13:25:52 +00006441enum ICEKind {
6442 /// This expression is an ICE.
6443 IK_ICE,
6444 /// This expression is not an ICE, but if it isn't evaluated, it's
6445 /// a legal subexpression for an ICE. This return value is used to handle
6446 /// the comma operator in C99 mode, and non-constant subexpressions.
6447 IK_ICEIfUnevaluated,
6448 /// This expression is not an ICE, and is not a legal subexpression for one.
6449 IK_NotICE
6450};
6451
John McCalld905f5a2010-05-07 05:32:02 +00006452struct ICEDiag {
Richard Smithceb59d92012-12-28 13:25:52 +00006453 ICEKind Kind;
John McCalld905f5a2010-05-07 05:32:02 +00006454 SourceLocation Loc;
6455
Richard Smithceb59d92012-12-28 13:25:52 +00006456 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCalld905f5a2010-05-07 05:32:02 +00006457};
6458
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006459}
6460
Richard Smithceb59d92012-12-28 13:25:52 +00006461static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
6462
6463static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCalld905f5a2010-05-07 05:32:02 +00006464
6465static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6466 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006467 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smithceb59d92012-12-28 13:25:52 +00006468 !EVResult.Val.isInt())
6469 return ICEDiag(IK_NotICE, E->getLocStart());
6470
John McCalld905f5a2010-05-07 05:32:02 +00006471 return NoDiag();
6472}
6473
6474static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6475 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smithceb59d92012-12-28 13:25:52 +00006476 if (!E->getType()->isIntegralOrEnumerationType())
6477 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006478
6479 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006480#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006481#define STMT(Node, Base) case Expr::Node##Class:
6482#define EXPR(Node, Base)
6483#include "clang/AST/StmtNodes.inc"
6484 case Expr::PredefinedExprClass:
6485 case Expr::FloatingLiteralClass:
6486 case Expr::ImaginaryLiteralClass:
6487 case Expr::StringLiteralClass:
6488 case Expr::ArraySubscriptExprClass:
6489 case Expr::MemberExprClass:
6490 case Expr::CompoundAssignOperatorClass:
6491 case Expr::CompoundLiteralExprClass:
6492 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006493 case Expr::DesignatedInitExprClass:
6494 case Expr::ImplicitValueInitExprClass:
6495 case Expr::ParenListExprClass:
6496 case Expr::VAArgExprClass:
6497 case Expr::AddrLabelExprClass:
6498 case Expr::StmtExprClass:
6499 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006500 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006501 case Expr::CXXDynamicCastExprClass:
6502 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006503 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006504 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006505 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006506 case Expr::CXXThisExprClass:
6507 case Expr::CXXThrowExprClass:
6508 case Expr::CXXNewExprClass:
6509 case Expr::CXXDeleteExprClass:
6510 case Expr::CXXPseudoDestructorExprClass:
6511 case Expr::UnresolvedLookupExprClass:
6512 case Expr::DependentScopeDeclRefExprClass:
6513 case Expr::CXXConstructExprClass:
6514 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006515 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006516 case Expr::CXXTemporaryObjectExprClass:
6517 case Expr::CXXUnresolvedConstructExprClass:
6518 case Expr::CXXDependentScopeMemberExprClass:
6519 case Expr::UnresolvedMemberExprClass:
6520 case Expr::ObjCStringLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +00006521 case Expr::ObjCBoxedExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006522 case Expr::ObjCArrayLiteralClass:
6523 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006524 case Expr::ObjCEncodeExprClass:
6525 case Expr::ObjCMessageExprClass:
6526 case Expr::ObjCSelectorExprClass:
6527 case Expr::ObjCProtocolExprClass:
6528 case Expr::ObjCIvarRefExprClass:
6529 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006530 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006531 case Expr::ObjCIsaExprClass:
6532 case Expr::ShuffleVectorExprClass:
6533 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006534 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006535 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006536 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006537 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smith9a4db032012-09-12 00:56:43 +00006538 case Expr::FunctionParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006539 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006540 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006541 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006542 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006543 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006544 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006545 case Expr::LambdaExprClass:
Richard Smithceb59d92012-12-28 13:25:52 +00006546 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redlcea8d962011-09-24 17:48:14 +00006547
Douglas Gregoree8aff02011-01-04 17:33:58 +00006548 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006549 case Expr::GNUNullExprClass:
6550 // GCC considers the GNU __null value to be an integral constant expression.
6551 return NoDiag();
6552
John McCall91a57552011-07-15 05:09:51 +00006553 case Expr::SubstNonTypeTemplateParmExprClass:
6554 return
6555 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6556
John McCalld905f5a2010-05-07 05:32:02 +00006557 case Expr::ParenExprClass:
6558 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006559 case Expr::GenericSelectionExprClass:
6560 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006561 case Expr::IntegerLiteralClass:
6562 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006563 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006564 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006565 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006566 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006567 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006568 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006569 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006570 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006571 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006572 return NoDiag();
6573 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006574 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006575 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6576 // constant expressions, but they can never be ICEs because an ICE cannot
6577 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006578 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006579 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006580 return CheckEvalInICE(E, Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006581 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006582 }
Richard Smith359c89d2012-02-24 22:12:32 +00006583 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006584 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6585 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006586 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006587 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006588 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006589 // Parameter variables are never constants. Without this check,
6590 // getAnyInitializer() can find a default argument, which leads
6591 // to chaos.
6592 if (isa<ParmVarDecl>(D))
Richard Smithceb59d92012-12-28 13:25:52 +00006593 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006594
6595 // C++ 7.1.5.1p2
6596 // A variable of non-volatile const-qualified integral or enumeration
6597 // type initialized by an ICE can be used in ICEs.
6598 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006599 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smithceb59d92012-12-28 13:25:52 +00006600 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithdb1822c2011-11-08 01:31:09 +00006601
Richard Smith099e7f62011-12-19 06:19:21 +00006602 const VarDecl *VD;
6603 // Look for a declaration of this variable that has an initializer, and
6604 // check whether it is an ICE.
6605 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6606 return NoDiag();
6607 else
Richard Smithceb59d92012-12-28 13:25:52 +00006608 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006609 }
6610 }
Richard Smithceb59d92012-12-28 13:25:52 +00006611 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006612 }
John McCalld905f5a2010-05-07 05:32:02 +00006613 case Expr::UnaryOperatorClass: {
6614 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6615 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006616 case UO_PostInc:
6617 case UO_PostDec:
6618 case UO_PreInc:
6619 case UO_PreDec:
6620 case UO_AddrOf:
6621 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006622 // C99 6.6/3 allows increment and decrement within unevaluated
6623 // subexpressions of constant expressions, but they can never be ICEs
6624 // because an ICE cannot contain an lvalue operand.
Richard Smithceb59d92012-12-28 13:25:52 +00006625 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006626 case UO_Extension:
6627 case UO_LNot:
6628 case UO_Plus:
6629 case UO_Minus:
6630 case UO_Not:
6631 case UO_Real:
6632 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006633 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006634 }
Richard Smithceb59d92012-12-28 13:25:52 +00006635
John McCalld905f5a2010-05-07 05:32:02 +00006636 // OffsetOf falls through here.
6637 }
6638 case Expr::OffsetOfExprClass: {
Richard Smithceb59d92012-12-28 13:25:52 +00006639 // Note that per C99, offsetof must be an ICE. And AFAIK, using
6640 // EvaluateAsRValue matches the proposed gcc behavior for cases like
6641 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
6642 // compliance: we should warn earlier for offsetof expressions with
6643 // array subscripts that aren't ICEs, and if the array subscripts
6644 // are ICEs, the value of the offsetof must be an integer constant.
6645 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006646 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006647 case Expr::UnaryExprOrTypeTraitExprClass: {
6648 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6649 if ((Exp->getKind() == UETT_SizeOf) &&
6650 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smithceb59d92012-12-28 13:25:52 +00006651 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006652 return NoDiag();
6653 }
6654 case Expr::BinaryOperatorClass: {
6655 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6656 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006657 case BO_PtrMemD:
6658 case BO_PtrMemI:
6659 case BO_Assign:
6660 case BO_MulAssign:
6661 case BO_DivAssign:
6662 case BO_RemAssign:
6663 case BO_AddAssign:
6664 case BO_SubAssign:
6665 case BO_ShlAssign:
6666 case BO_ShrAssign:
6667 case BO_AndAssign:
6668 case BO_XorAssign:
6669 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006670 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6671 // constant expressions, but they can never be ICEs because an ICE cannot
6672 // contain an lvalue operand.
Richard Smithceb59d92012-12-28 13:25:52 +00006673 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006674
John McCall2de56d12010-08-25 11:45:40 +00006675 case BO_Mul:
6676 case BO_Div:
6677 case BO_Rem:
6678 case BO_Add:
6679 case BO_Sub:
6680 case BO_Shl:
6681 case BO_Shr:
6682 case BO_LT:
6683 case BO_GT:
6684 case BO_LE:
6685 case BO_GE:
6686 case BO_EQ:
6687 case BO_NE:
6688 case BO_And:
6689 case BO_Xor:
6690 case BO_Or:
6691 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006692 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6693 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006694 if (Exp->getOpcode() == BO_Div ||
6695 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006696 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006697 // we don't evaluate one.
Richard Smithceb59d92012-12-28 13:25:52 +00006698 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006699 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006700 if (REval == 0)
Richard Smithceb59d92012-12-28 13:25:52 +00006701 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006702 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006703 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006704 if (LEval.isMinSignedValue())
Richard Smithceb59d92012-12-28 13:25:52 +00006705 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006706 }
6707 }
6708 }
John McCall2de56d12010-08-25 11:45:40 +00006709 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006710 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006711 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6712 // if it isn't evaluated.
Richard Smithceb59d92012-12-28 13:25:52 +00006713 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
6714 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006715 } else {
6716 // In both C89 and C++, commas in ICEs are illegal.
Richard Smithceb59d92012-12-28 13:25:52 +00006717 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006718 }
6719 }
Richard Smithceb59d92012-12-28 13:25:52 +00006720 return Worst(LHSResult, RHSResult);
John McCalld905f5a2010-05-07 05:32:02 +00006721 }
John McCall2de56d12010-08-25 11:45:40 +00006722 case BO_LAnd:
6723 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006724 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6725 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006726 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCalld905f5a2010-05-07 05:32:02 +00006727 // Rare case where the RHS has a comma "side-effect"; we need
6728 // to actually check the condition to see whether the side
6729 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006730 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006731 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006732 return RHSResult;
6733 return NoDiag();
6734 }
6735
Richard Smithceb59d92012-12-28 13:25:52 +00006736 return Worst(LHSResult, RHSResult);
John McCalld905f5a2010-05-07 05:32:02 +00006737 }
6738 }
6739 }
6740 case Expr::ImplicitCastExprClass:
6741 case Expr::CStyleCastExprClass:
6742 case Expr::CXXFunctionalCastExprClass:
6743 case Expr::CXXStaticCastExprClass:
6744 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006745 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006746 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006747 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006748 if (isa<ExplicitCastExpr>(E)) {
6749 if (const FloatingLiteral *FL
6750 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6751 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6752 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6753 APSInt IgnoredVal(DestWidth, !DestSigned);
6754 bool Ignored;
6755 // If the value does not fit in the destination type, the behavior is
6756 // undefined, so we are not required to treat it as a constant
6757 // expression.
6758 if (FL->getValue().convertToInteger(IgnoredVal,
6759 llvm::APFloat::rmTowardZero,
6760 &Ignored) & APFloat::opInvalidOp)
Richard Smithceb59d92012-12-28 13:25:52 +00006761 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith2116b142011-12-18 02:33:09 +00006762 return NoDiag();
6763 }
6764 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006765 switch (cast<CastExpr>(E)->getCastKind()) {
6766 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006767 case CK_AtomicToNonAtomic:
6768 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006769 case CK_NoOp:
6770 case CK_IntegralToBoolean:
6771 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006772 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006773 default:
Richard Smithceb59d92012-12-28 13:25:52 +00006774 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedmaneea0e812011-09-29 21:49:34 +00006775 }
John McCalld905f5a2010-05-07 05:32:02 +00006776 }
John McCall56ca35d2011-02-17 10:25:35 +00006777 case Expr::BinaryConditionalOperatorClass: {
6778 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6779 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006780 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCall56ca35d2011-02-17 10:25:35 +00006781 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006782 if (FalseResult.Kind == IK_NotICE) return FalseResult;
6783 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
6784 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith9b403c52012-12-28 12:53:55 +00006785 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006786 return FalseResult;
6787 }
John McCalld905f5a2010-05-07 05:32:02 +00006788 case Expr::ConditionalOperatorClass: {
6789 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6790 // If the condition (ignoring parens) is a __builtin_constant_p call,
6791 // then only the true side is actually considered in an integer constant
6792 // expression, and it is fully evaluated. This is an important GNU
6793 // extension. See GCC PR38377 for discussion.
6794 if (const CallExpr *CallCE
6795 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006796 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6797 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006798 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006799 if (CondResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00006800 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006801
Richard Smithf48fdb02011-12-09 22:58:01 +00006802 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6803 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006804
Richard Smithceb59d92012-12-28 13:25:52 +00006805 if (TrueResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00006806 return TrueResult;
Richard Smithceb59d92012-12-28 13:25:52 +00006807 if (FalseResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00006808 return FalseResult;
Richard Smithceb59d92012-12-28 13:25:52 +00006809 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCalld905f5a2010-05-07 05:32:02 +00006810 return CondResult;
Richard Smithceb59d92012-12-28 13:25:52 +00006811 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCalld905f5a2010-05-07 05:32:02 +00006812 return NoDiag();
6813 // Rare case where the diagnostics depend on which side is evaluated
6814 // Note that if we get here, CondResult is 0, and at least one of
6815 // TrueResult and FalseResult is non-zero.
Richard Smithceb59d92012-12-28 13:25:52 +00006816 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCalld905f5a2010-05-07 05:32:02 +00006817 return FalseResult;
John McCalld905f5a2010-05-07 05:32:02 +00006818 return TrueResult;
6819 }
6820 case Expr::CXXDefaultArgExprClass:
6821 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6822 case Expr::ChooseExprClass: {
6823 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6824 }
6825 }
6826
David Blaikie30263482012-01-20 21:50:17 +00006827 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006828}
6829
Richard Smithf48fdb02011-12-09 22:58:01 +00006830/// Evaluate an expression as a C++11 integral constant expression.
6831static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6832 const Expr *E,
6833 llvm::APSInt *Value,
6834 SourceLocation *Loc) {
6835 if (!E->getType()->isIntegralOrEnumerationType()) {
6836 if (Loc) *Loc = E->getExprLoc();
6837 return false;
6838 }
6839
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006840 APValue Result;
6841 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006842 return false;
6843
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006844 assert(Result.isInt() && "pointer cast to int is not an ICE");
6845 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006846 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006847}
6848
Richard Smithdd1f29b2011-12-12 09:28:41 +00006849bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith80ad52f2013-01-02 11:42:31 +00006850 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf48fdb02011-12-09 22:58:01 +00006851 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6852
Richard Smithceb59d92012-12-28 13:25:52 +00006853 ICEDiag D = CheckICE(this, Ctx);
6854 if (D.Kind != IK_ICE) {
6855 if (Loc) *Loc = D.Loc;
John McCalld905f5a2010-05-07 05:32:02 +00006856 return false;
6857 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006858 return true;
6859}
6860
6861bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6862 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith80ad52f2013-01-02 11:42:31 +00006863 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf48fdb02011-12-09 22:58:01 +00006864 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6865
6866 if (!isIntegerConstantExpr(Ctx, Loc))
6867 return false;
6868 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006869 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006870 return true;
6871}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006872
Richard Smith70488e22012-02-14 21:38:30 +00006873bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smithceb59d92012-12-28 13:25:52 +00006874 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith70488e22012-02-14 21:38:30 +00006875}
6876
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006877bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6878 SourceLocation *Loc) const {
6879 // We support this checking in C++98 mode in order to diagnose compatibility
6880 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006881 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006882
Richard Smith70488e22012-02-14 21:38:30 +00006883 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006884 Expr::EvalStatus Status;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006885 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006886 Status.Diag = &Diags;
6887 EvalInfo Info(Ctx, Status);
6888
6889 APValue Scratch;
6890 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6891
6892 if (!Diags.empty()) {
6893 IsConstExpr = false;
6894 if (Loc) *Loc = Diags[0].first;
6895 } else if (!IsConstExpr) {
6896 // FIXME: This shouldn't happen.
6897 if (Loc) *Loc = getExprLoc();
6898 }
6899
6900 return IsConstExpr;
6901}
Richard Smith745f5142012-01-27 01:14:48 +00006902
6903bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006904 SmallVectorImpl<
Richard Smith745f5142012-01-27 01:14:48 +00006905 PartialDiagnosticAt> &Diags) {
6906 // FIXME: It would be useful to check constexpr function templates, but at the
6907 // moment the constant expression evaluator cannot cope with the non-rigorous
6908 // ASTs which we build for dependent expressions.
6909 if (FD->isDependentContext())
6910 return true;
6911
6912 Expr::EvalStatus Status;
6913 Status.Diag = &Diags;
6914
6915 EvalInfo Info(FD->getASTContext(), Status);
6916 Info.CheckingPotentialConstantExpression = true;
6917
6918 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6919 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6920
6921 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6922 // is a temporary being used as the 'this' pointer.
6923 LValue This;
6924 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006925 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006926
Richard Smith745f5142012-01-27 01:14:48 +00006927 ArrayRef<const Expr*> Args;
6928
6929 SourceLocation Loc = FD->getLocation();
6930
Richard Smith1aa0be82012-03-03 22:46:17 +00006931 APValue Scratch;
6932 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006933 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006934 else
Richard Smith745f5142012-01-27 01:14:48 +00006935 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6936 Args, FD->getBody(), Info, Scratch);
6937
6938 return Diags.empty();
6939}