blob: ed64153f853c30d9cd69dc50fe745e1831c4e53a [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith745f5142012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlssonc44eec62008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000038#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000039#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000040#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000041#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000042#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000047#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000048#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000049
Anders Carlssonc44eec62008-07-03 04:20:39 +000050using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000051using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000052using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000053
Richard Smith83587db2012-02-15 02:18:13 +000054static bool IsGlobalLValue(APValue::LValueBase B);
55
John McCallf4cf1a12010-05-07 17:22:02 +000056namespace {
Richard Smith180f4792011-11-10 06:34:14 +000057 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000058 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000059 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000060
Richard Smith83587db2012-02-15 02:18:13 +000061 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +000062 if (!B) return QualType();
63 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
64 return D->getType();
65 return B.get<const Expr*>()->getType();
66 }
67
Richard Smith180f4792011-11-10 06:34:14 +000068 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000069 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000070 static
Richard Smithf15fda02012-02-02 01:16:57 +000071 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000072 APValue::BaseOrMemberType Value;
73 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000074 return Value;
75 }
76
77 /// Get an LValue path entry, which is known to not be an array index, as a
78 /// field declaration.
Richard Smith83587db2012-02-15 02:18:13 +000079 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000080 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000081 }
82 /// Get an LValue path entry, which is known to not be an array index, as a
83 /// base class declaration.
Richard Smith83587db2012-02-15 02:18:13 +000084 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000085 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000086 }
87 /// Determine whether this LValue path entry for a base class names a virtual
88 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +000089 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000090 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +000091 }
92
Richard Smithb4e85ed2012-01-06 16:39:00 +000093 /// Find the path length and type of the most-derived subobject in the given
94 /// path, and find the size of the containing array, if any.
95 static
96 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
97 ArrayRef<APValue::LValuePathEntry> Path,
98 uint64_t &ArraySize, QualType &Type) {
99 unsigned MostDerivedLength = 0;
100 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000101 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000102 if (Type->isArrayType()) {
103 const ConstantArrayType *CAT =
104 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
105 Type = CAT->getElementType();
106 ArraySize = CAT->getSize().getZExtValue();
107 MostDerivedLength = I + 1;
Richard Smith86024012012-02-18 22:04:06 +0000108 } else if (Type->isAnyComplexType()) {
109 const ComplexType *CT = Type->castAs<ComplexType>();
110 Type = CT->getElementType();
111 ArraySize = 2;
112 MostDerivedLength = I + 1;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000113 } else if (const FieldDecl *FD = getAsField(Path[I])) {
114 Type = FD->getType();
115 ArraySize = 0;
116 MostDerivedLength = I + 1;
117 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000118 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000119 ArraySize = 0;
120 }
Richard Smith9a17a682011-11-07 05:07:52 +0000121 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000122 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000123 }
124
Richard Smithb4e85ed2012-01-06 16:39:00 +0000125 // The order of this enum is important for diagnostics.
126 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000127 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith86024012012-02-18 22:04:06 +0000128 CSK_This, CSK_Real, CSK_Imag
Richard Smithb4e85ed2012-01-06 16:39:00 +0000129 };
130
Richard Smith0a3bdb62011-11-04 02:25:55 +0000131 /// A path from a glvalue to a subobject of that glvalue.
132 struct SubobjectDesignator {
133 /// True if the subobject was named in a manner not supported by C++11. Such
134 /// lvalues can still be folded, but they are not core constant expressions
135 /// and we cannot perform lvalue-to-rvalue conversions on them.
136 bool Invalid : 1;
137
Richard Smithb4e85ed2012-01-06 16:39:00 +0000138 /// Is this a pointer one past the end of an object?
139 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000140
Richard Smithb4e85ed2012-01-06 16:39:00 +0000141 /// The length of the path to the most-derived object of which this is a
142 /// subobject.
143 unsigned MostDerivedPathLength : 30;
144
145 /// The size of the array of which the most-derived object is an element, or
146 /// 0 if the most-derived object is not an array element.
147 uint64_t MostDerivedArraySize;
148
149 /// The type of the most derived object referred to by this address.
150 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000151
Richard Smith9a17a682011-11-07 05:07:52 +0000152 typedef APValue::LValuePathEntry PathEntry;
153
Richard Smith0a3bdb62011-11-04 02:25:55 +0000154 /// The entries on the path from the glvalue to the designated subobject.
155 SmallVector<PathEntry, 8> Entries;
156
Richard Smithb4e85ed2012-01-06 16:39:00 +0000157 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000158
Richard Smithb4e85ed2012-01-06 16:39:00 +0000159 explicit SubobjectDesignator(QualType T)
160 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
161 MostDerivedArraySize(0), MostDerivedType(T) {}
162
163 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
164 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
165 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000166 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000167 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000168 ArrayRef<PathEntry> VEntries = V.getLValuePath();
169 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
170 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000171 MostDerivedPathLength =
172 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
173 V.getLValuePath(), MostDerivedArraySize,
174 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000175 }
176 }
177
Richard Smith0a3bdb62011-11-04 02:25:55 +0000178 void setInvalid() {
179 Invalid = true;
180 Entries.clear();
181 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000182
183 /// Determine whether this is a one-past-the-end pointer.
184 bool isOnePastTheEnd() const {
185 if (IsOnePastTheEnd)
186 return true;
187 if (MostDerivedArraySize &&
188 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
189 return true;
190 return false;
191 }
192
193 /// Check that this refers to a valid subobject.
194 bool isValidSubobject() const {
195 if (Invalid)
196 return false;
197 return !isOnePastTheEnd();
198 }
199 /// Check that this refers to a valid subobject, and if not, produce a
200 /// relevant diagnostic and set the designator as invalid.
201 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
202
203 /// Update this designator to refer to the first element within this array.
204 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000205 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000206 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000207 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000208
209 // This is a most-derived object.
210 MostDerivedType = CAT->getElementType();
211 MostDerivedArraySize = CAT->getSize().getZExtValue();
212 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000213 }
214 /// Update this designator to refer to the given base or member of this
215 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000216 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000217 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000218 APValue::BaseOrMemberType Value(D, Virtual);
219 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000220 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000221
222 // If this isn't a base class, it's a new most-derived object.
223 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
224 MostDerivedType = FD->getType();
225 MostDerivedArraySize = 0;
226 MostDerivedPathLength = Entries.size();
227 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000228 }
Richard Smith86024012012-02-18 22:04:06 +0000229 /// Update this designator to refer to the given complex component.
230 void addComplexUnchecked(QualType EltTy, bool Imag) {
231 PathEntry Entry;
232 Entry.ArrayIndex = Imag;
233 Entries.push_back(Entry);
234
235 // This is technically a most-derived object, though in practice this
236 // is unlikely to matter.
237 MostDerivedType = EltTy;
238 MostDerivedArraySize = 2;
239 MostDerivedPathLength = Entries.size();
240 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000241 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000242 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000243 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000244 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000245 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000246 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000247 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
248 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
249 setInvalid();
250 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000251 return;
252 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000253 // [expr.add]p4: For the purposes of these operators, a pointer to a
254 // nonarray object behaves the same as a pointer to the first element of
255 // an array of length one with the type of the object as its element type.
256 if (IsOnePastTheEnd && N == (uint64_t)-1)
257 IsOnePastTheEnd = false;
258 else if (!IsOnePastTheEnd && N == 1)
259 IsOnePastTheEnd = true;
260 else if (N != 0) {
261 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000262 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000263 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000264 }
265 };
266
Richard Smith47a1eed2011-10-29 20:57:55 +0000267 /// A core constant value. This can be the value of any constant expression,
268 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000269 ///
270 /// For an LValue, the base and offset are stored in the APValue subobject,
271 /// but the other information is stored in the SubobjectDesignator. For all
272 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000273 class CCValue : public APValue {
274 typedef llvm::APSInt APSInt;
275 typedef llvm::APFloat APFloat;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000276 /// If the value is a reference or pointer, this is a description of how the
277 /// subobject was specified.
278 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000279 public:
Richard Smith177dce72011-11-01 16:57:24 +0000280 struct GlobalValue {};
281
Richard Smith47a1eed2011-10-29 20:57:55 +0000282 CCValue() {}
283 explicit CCValue(const APSInt &I) : APValue(I) {}
284 explicit CCValue(const APFloat &F) : APValue(F) {}
285 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
286 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
287 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith83587db2012-02-15 02:18:13 +0000288 CCValue(const CCValue &V) : APValue(V), Designator(V.Designator) {}
289 CCValue(LValueBase B, const CharUnits &O, unsigned I,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000290 const SubobjectDesignator &D) :
Richard Smith83587db2012-02-15 02:18:13 +0000291 APValue(B, O, APValue::NoLValuePath(), I), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000292 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
Richard Smith83587db2012-02-15 02:18:13 +0000293 APValue(V), Designator(Ctx, V) {
294 }
Richard Smithe24f5fc2011-11-17 22:56:20 +0000295 CCValue(const ValueDecl *D, bool IsDerivedMember,
296 ArrayRef<const CXXRecordDecl*> Path) :
297 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000298 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
299 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000300
Richard Smith0a3bdb62011-11-04 02:25:55 +0000301 SubobjectDesignator &getLValueDesignator() {
302 assert(getKind() == LValue);
303 return Designator;
304 }
305 const SubobjectDesignator &getLValueDesignator() const {
306 return const_cast<CCValue*>(this)->getLValueDesignator();
307 }
Richard Smith83587db2012-02-15 02:18:13 +0000308 APValue toAPValue() const {
309 if (!isLValue())
310 return *this;
311
312 if (Designator.Invalid) {
313 // This is not a core constant expression. An appropriate diagnostic
314 // will have already been produced.
315 return APValue(getLValueBase(), getLValueOffset(),
316 APValue::NoLValuePath(), getLValueCallIndex());
317 }
318
319 return APValue(getLValueBase(), getLValueOffset(),
320 Designator.Entries, Designator.IsOnePastTheEnd,
321 getLValueCallIndex());
322 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000323 };
324
Richard Smithd0dccea2011-10-28 22:34:42 +0000325 /// A stack frame in the constexpr call stack.
326 struct CallStackFrame {
327 EvalInfo &Info;
328
329 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000330 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000331
Richard Smith08d6e032011-12-16 19:06:07 +0000332 /// CallLoc - The location of the call expression for this call.
333 SourceLocation CallLoc;
334
335 /// Callee - The function which was called.
336 const FunctionDecl *Callee;
337
Richard Smith83587db2012-02-15 02:18:13 +0000338 /// Index - The call index of this call.
339 unsigned Index;
340
Richard Smith180f4792011-11-10 06:34:14 +0000341 /// This - The binding for the this pointer in this call, if any.
342 const LValue *This;
343
Richard Smithd0dccea2011-10-28 22:34:42 +0000344 /// ParmBindings - Parameter bindings for this function call, indexed by
345 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000346 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000347
Richard Smithbd552ef2011-10-31 05:52:43 +0000348 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
349 typedef MapTy::const_iterator temp_iterator;
350 /// Temporaries - Temporary lvalues materialized within this stack frame.
351 MapTy Temporaries;
352
Richard Smith08d6e032011-12-16 19:06:07 +0000353 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
354 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000355 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000356 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000357 };
358
Richard Smithdd1f29b2011-12-12 09:28:41 +0000359 /// A partial diagnostic which we might know in advance that we are not going
360 /// to emit.
361 class OptionalDiagnostic {
362 PartialDiagnostic *Diag;
363
364 public:
365 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
366
367 template<typename T>
368 OptionalDiagnostic &operator<<(const T &v) {
369 if (Diag)
370 *Diag << v;
371 return *this;
372 }
Richard Smith789f9b62012-01-31 04:08:20 +0000373
374 OptionalDiagnostic &operator<<(const APSInt &I) {
375 if (Diag) {
376 llvm::SmallVector<char, 32> Buffer;
377 I.toString(Buffer);
378 *Diag << StringRef(Buffer.data(), Buffer.size());
379 }
380 return *this;
381 }
382
383 OptionalDiagnostic &operator<<(const APFloat &F) {
384 if (Diag) {
385 llvm::SmallVector<char, 32> Buffer;
386 F.toString(Buffer);
387 *Diag << StringRef(Buffer.data(), Buffer.size());
388 }
389 return *this;
390 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000391 };
392
Richard Smith83587db2012-02-15 02:18:13 +0000393 /// EvalInfo - This is a private struct used by the evaluator to capture
394 /// information about a subexpression as it is folded. It retains information
395 /// about the AST context, but also maintains information about the folded
396 /// expression.
397 ///
398 /// If an expression could be evaluated, it is still possible it is not a C
399 /// "integer constant expression" or constant expression. If not, this struct
400 /// captures information about how and why not.
401 ///
402 /// One bit of information passed *into* the request for constant folding
403 /// indicates whether the subexpression is "evaluated" or not according to C
404 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
405 /// evaluate the expression regardless of what the RHS is, but C only allows
406 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000407 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000408 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000409
410 /// EvalStatus - Contains information about the evaluation.
411 Expr::EvalStatus &EvalStatus;
412
413 /// CurrentCall - The top of the constexpr call stack.
414 CallStackFrame *CurrentCall;
415
Richard Smithbd552ef2011-10-31 05:52:43 +0000416 /// CallStackDepth - The number of calls in the call stack right now.
417 unsigned CallStackDepth;
418
Richard Smith83587db2012-02-15 02:18:13 +0000419 /// NextCallIndex - The next call index to assign.
420 unsigned NextCallIndex;
421
Richard Smithbd552ef2011-10-31 05:52:43 +0000422 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
423 /// OpaqueValues - Values used as the common expression in a
424 /// BinaryConditionalOperator.
425 MapTy OpaqueValues;
426
427 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000428 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000429 CallStackFrame BottomFrame;
430
Richard Smith180f4792011-11-10 06:34:14 +0000431 /// EvaluatingDecl - This is the declaration whose initializer is being
432 /// evaluated, if any.
433 const VarDecl *EvaluatingDecl;
434
435 /// EvaluatingDeclValue - This is the value being constructed for the
436 /// declaration whose initializer is being evaluated, if any.
437 APValue *EvaluatingDeclValue;
438
Richard Smithc1c5f272011-12-13 06:39:58 +0000439 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
440 /// notes attached to it will also be stored, otherwise they will not be.
441 bool HasActiveDiagnostic;
442
Richard Smith745f5142012-01-27 01:14:48 +0000443 /// CheckingPotentialConstantExpression - Are we checking whether the
444 /// expression is a potential constant expression? If so, some diagnostics
445 /// are suppressed.
446 bool CheckingPotentialConstantExpression;
447
Richard Smithbd552ef2011-10-31 05:52:43 +0000448
449 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000450 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000451 CallStackDepth(0), NextCallIndex(1),
452 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000453 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
454 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000455
Richard Smithbd552ef2011-10-31 05:52:43 +0000456 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
457 MapTy::const_iterator i = OpaqueValues.find(e);
458 if (i == OpaqueValues.end()) return 0;
459 return &i->second;
460 }
461
Richard Smith180f4792011-11-10 06:34:14 +0000462 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
463 EvaluatingDecl = VD;
464 EvaluatingDeclValue = &Value;
465 }
466
Richard Smithc18c4232011-11-21 19:36:32 +0000467 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
468
Richard Smithc1c5f272011-12-13 06:39:58 +0000469 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000470 // Don't perform any constexpr calls (other than the call we're checking)
471 // when checking a potential constant expression.
472 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
473 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000474 if (NextCallIndex == 0) {
475 // NextCallIndex has wrapped around.
476 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
477 return false;
478 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000479 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
480 return true;
481 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
482 << getLangOpts().ConstexprCallDepth;
483 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000484 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000485
Richard Smith83587db2012-02-15 02:18:13 +0000486 CallStackFrame *getCallFrame(unsigned CallIndex) {
487 assert(CallIndex && "no call index in getCallFrame");
488 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
489 // be null in this loop.
490 CallStackFrame *Frame = CurrentCall;
491 while (Frame->Index > CallIndex)
492 Frame = Frame->Caller;
493 return (Frame->Index == CallIndex) ? Frame : 0;
494 }
495
Richard Smithc1c5f272011-12-13 06:39:58 +0000496 private:
497 /// Add a diagnostic to the diagnostics list.
498 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
499 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
500 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
501 return EvalStatus.Diag->back().second;
502 }
503
Richard Smith08d6e032011-12-16 19:06:07 +0000504 /// Add notes containing a call stack to the current point of evaluation.
505 void addCallStack(unsigned Limit);
506
Richard Smithc1c5f272011-12-13 06:39:58 +0000507 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000508 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000509 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
510 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000511 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000512 // If we have a prior diagnostic, it will be noting that the expression
513 // isn't a constant expression. This diagnostic is more important.
514 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000515 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000516 unsigned CallStackNotes = CallStackDepth - 1;
517 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
518 if (Limit)
519 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000520 if (CheckingPotentialConstantExpression)
521 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000522
Richard Smithc1c5f272011-12-13 06:39:58 +0000523 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000524 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000525 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
526 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000527 if (!CheckingPotentialConstantExpression)
528 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000529 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000530 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000531 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000532 return OptionalDiagnostic();
533 }
534
535 /// Diagnose that the evaluation does not produce a C++11 core constant
536 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000537 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
538 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000539 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000540 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000541 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
542 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000543 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000544 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000545 return Diag(Loc, DiagId, ExtraNotes);
546 }
547
548 /// Add a note to a prior diagnostic.
549 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
550 if (!HasActiveDiagnostic)
551 return OptionalDiagnostic();
552 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000553 }
Richard Smith099e7f62011-12-19 06:19:21 +0000554
555 /// Add a stack of notes to a prior diagnostic.
556 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
557 if (HasActiveDiagnostic) {
558 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
559 Diags.begin(), Diags.end());
560 }
561 }
Richard Smith745f5142012-01-27 01:14:48 +0000562
563 /// Should we continue evaluation as much as possible after encountering a
564 /// construct which can't be folded?
565 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000566 return CheckingPotentialConstantExpression &&
567 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000568 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000569 };
Richard Smithf15fda02012-02-02 01:16:57 +0000570
571 /// Object used to treat all foldable expressions as constant expressions.
572 struct FoldConstant {
573 bool Enabled;
574
575 explicit FoldConstant(EvalInfo &Info)
576 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
577 !Info.EvalStatus.HasSideEffects) {
578 }
579 // Treat the value we've computed since this object was created as constant.
580 void Fold(EvalInfo &Info) {
581 if (Enabled && !Info.EvalStatus.Diag->empty() &&
582 !Info.EvalStatus.HasSideEffects)
583 Info.EvalStatus.Diag->clear();
584 }
585 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000586
587 /// RAII object used to suppress diagnostics and side-effects from a
588 /// speculative evaluation.
589 class SpeculativeEvaluationRAII {
590 EvalInfo &Info;
591 Expr::EvalStatus Old;
592
593 public:
594 SpeculativeEvaluationRAII(EvalInfo &Info,
595 llvm::SmallVectorImpl<PartialDiagnosticAt>
596 *NewDiag = 0)
597 : Info(Info), Old(Info.EvalStatus) {
598 Info.EvalStatus.Diag = NewDiag;
599 }
600 ~SpeculativeEvaluationRAII() {
601 Info.EvalStatus = Old;
602 }
603 };
Richard Smith08d6e032011-12-16 19:06:07 +0000604}
Richard Smithbd552ef2011-10-31 05:52:43 +0000605
Richard Smithb4e85ed2012-01-06 16:39:00 +0000606bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
607 CheckSubobjectKind CSK) {
608 if (Invalid)
609 return false;
610 if (isOnePastTheEnd()) {
611 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
612 << CSK;
613 setInvalid();
614 return false;
615 }
616 return true;
617}
618
619void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
620 const Expr *E, uint64_t N) {
621 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
622 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
623 << static_cast<int>(N) << /*array*/ 0
624 << static_cast<unsigned>(MostDerivedArraySize);
625 else
626 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
627 << static_cast<int>(N) << /*non-array*/ 1;
628 setInvalid();
629}
630
Richard Smith08d6e032011-12-16 19:06:07 +0000631CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
632 const FunctionDecl *Callee, const LValue *This,
633 const CCValue *Arguments)
634 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000635 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000636 Info.CurrentCall = this;
637 ++Info.CallStackDepth;
638}
639
640CallStackFrame::~CallStackFrame() {
641 assert(Info.CurrentCall == this && "calls retired out of order");
642 --Info.CallStackDepth;
643 Info.CurrentCall = Caller;
644}
645
646/// Produce a string describing the given constexpr call.
647static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
648 unsigned ArgIndex = 0;
649 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000650 !isa<CXXConstructorDecl>(Frame->Callee) &&
651 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000652
653 if (!IsMemberCall)
654 Out << *Frame->Callee << '(';
655
656 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
657 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000658 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000659 Out << ", ";
660
661 const ParmVarDecl *Param = *I;
662 const CCValue &Arg = Frame->Arguments[ArgIndex];
663 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
664 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
665 else {
Richard Smith83587db2012-02-15 02:18:13 +0000666 // Convert the CCValue to an APValue without checking for constantness.
Richard Smith08d6e032011-12-16 19:06:07 +0000667 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
668 Arg.getLValueDesignator().Entries,
Richard Smith83587db2012-02-15 02:18:13 +0000669 Arg.getLValueDesignator().IsOnePastTheEnd,
670 Arg.getLValueCallIndex());
Richard Smith08d6e032011-12-16 19:06:07 +0000671 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
672 }
673
674 if (ArgIndex == 0 && IsMemberCall)
675 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000676 }
677
Richard Smith08d6e032011-12-16 19:06:07 +0000678 Out << ')';
679}
680
681void EvalInfo::addCallStack(unsigned Limit) {
682 // Determine which calls to skip, if any.
683 unsigned ActiveCalls = CallStackDepth - 1;
684 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
685 if (Limit && Limit < ActiveCalls) {
686 SkipStart = Limit / 2 + Limit % 2;
687 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000688 }
689
Richard Smith08d6e032011-12-16 19:06:07 +0000690 // Walk the call stack and add the diagnostics.
691 unsigned CallIdx = 0;
692 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
693 Frame = Frame->Caller, ++CallIdx) {
694 // Skip this call?
695 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
696 if (CallIdx == SkipStart) {
697 // Note that we're skipping calls.
698 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
699 << unsigned(ActiveCalls - Limit);
700 }
701 continue;
702 }
703
704 llvm::SmallVector<char, 128> Buffer;
705 llvm::raw_svector_ostream Out(Buffer);
706 describeCall(Frame, Out);
707 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
708 }
709}
710
711namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000712 struct ComplexValue {
713 private:
714 bool IsInt;
715
716 public:
717 APSInt IntReal, IntImag;
718 APFloat FloatReal, FloatImag;
719
720 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
721
722 void makeComplexFloat() { IsInt = false; }
723 bool isComplexFloat() const { return !IsInt; }
724 APFloat &getComplexFloatReal() { return FloatReal; }
725 APFloat &getComplexFloatImag() { return FloatImag; }
726
727 void makeComplexInt() { IsInt = true; }
728 bool isComplexInt() const { return IsInt; }
729 APSInt &getComplexIntReal() { return IntReal; }
730 APSInt &getComplexIntImag() { return IntImag; }
731
Richard Smith47a1eed2011-10-29 20:57:55 +0000732 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000733 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000734 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000735 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000736 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000737 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000738 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000739 assert(v.isComplexFloat() || v.isComplexInt());
740 if (v.isComplexFloat()) {
741 makeComplexFloat();
742 FloatReal = v.getComplexFloatReal();
743 FloatImag = v.getComplexFloatImag();
744 } else {
745 makeComplexInt();
746 IntReal = v.getComplexIntReal();
747 IntImag = v.getComplexIntImag();
748 }
749 }
John McCallf4cf1a12010-05-07 17:22:02 +0000750 };
John McCallefdb83e2010-05-07 21:00:08 +0000751
752 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000753 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000754 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000755 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000756 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000757
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000758 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000759 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000760 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000761 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000762 SubobjectDesignator &getLValueDesignator() { return Designator; }
763 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000764
Richard Smith47a1eed2011-10-29 20:57:55 +0000765 void moveInto(CCValue &V) const {
Richard Smith83587db2012-02-15 02:18:13 +0000766 V = CCValue(Base, Offset, CallIndex, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000767 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000768 void setFrom(const CCValue &V) {
769 assert(V.isLValue());
770 Base = V.getLValueBase();
771 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000772 CallIndex = V.getLValueCallIndex();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000773 Designator = V.getLValueDesignator();
774 }
775
Richard Smith83587db2012-02-15 02:18:13 +0000776 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000777 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000778 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000779 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000780 Designator = SubobjectDesignator(getType(B));
781 }
782
783 // Check that this LValue is not based on a null pointer. If it is, produce
784 // a diagnostic and mark the designator as invalid.
785 bool checkNullPointer(EvalInfo &Info, const Expr *E,
786 CheckSubobjectKind CSK) {
787 if (Designator.Invalid)
788 return false;
789 if (!Base) {
790 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
791 << CSK;
792 Designator.setInvalid();
793 return false;
794 }
795 return true;
796 }
797
798 // Check this LValue refers to an object. If not, set the designator to be
799 // invalid and emit a diagnostic.
800 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
801 return checkNullPointer(Info, E, CSK) &&
802 Designator.checkSubobject(Info, E, CSK);
803 }
804
805 void addDecl(EvalInfo &Info, const Expr *E,
806 const Decl *D, bool Virtual = false) {
807 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
808 Designator.addDeclUnchecked(D, Virtual);
809 }
810 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
811 checkSubobject(Info, E, CSK_ArrayToPointer);
812 Designator.addArrayUnchecked(CAT);
813 }
Richard Smith86024012012-02-18 22:04:06 +0000814 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
815 checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real);
816 Designator.addComplexUnchecked(EltTy, Imag);
817 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000818 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
819 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
820 return;
821 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000822 }
John McCallefdb83e2010-05-07 21:00:08 +0000823 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000824
825 struct MemberPtr {
826 MemberPtr() {}
827 explicit MemberPtr(const ValueDecl *Decl) :
828 DeclAndIsDerivedMember(Decl, false), Path() {}
829
830 /// The member or (direct or indirect) field referred to by this member
831 /// pointer, or 0 if this is a null member pointer.
832 const ValueDecl *getDecl() const {
833 return DeclAndIsDerivedMember.getPointer();
834 }
835 /// Is this actually a member of some type derived from the relevant class?
836 bool isDerivedMember() const {
837 return DeclAndIsDerivedMember.getInt();
838 }
839 /// Get the class which the declaration actually lives in.
840 const CXXRecordDecl *getContainingRecord() const {
841 return cast<CXXRecordDecl>(
842 DeclAndIsDerivedMember.getPointer()->getDeclContext());
843 }
844
845 void moveInto(CCValue &V) const {
846 V = CCValue(getDecl(), isDerivedMember(), Path);
847 }
848 void setFrom(const CCValue &V) {
849 assert(V.isMemberPointer());
850 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
851 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
852 Path.clear();
853 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
854 Path.insert(Path.end(), P.begin(), P.end());
855 }
856
857 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
858 /// whether the member is a member of some class derived from the class type
859 /// of the member pointer.
860 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
861 /// Path - The path of base/derived classes from the member declaration's
862 /// class (exclusive) to the class type of the member pointer (inclusive).
863 SmallVector<const CXXRecordDecl*, 4> Path;
864
865 /// Perform a cast towards the class of the Decl (either up or down the
866 /// hierarchy).
867 bool castBack(const CXXRecordDecl *Class) {
868 assert(!Path.empty());
869 const CXXRecordDecl *Expected;
870 if (Path.size() >= 2)
871 Expected = Path[Path.size() - 2];
872 else
873 Expected = getContainingRecord();
874 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
875 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
876 // if B does not contain the original member and is not a base or
877 // derived class of the class containing the original member, the result
878 // of the cast is undefined.
879 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
880 // (D::*). We consider that to be a language defect.
881 return false;
882 }
883 Path.pop_back();
884 return true;
885 }
886 /// Perform a base-to-derived member pointer cast.
887 bool castToDerived(const CXXRecordDecl *Derived) {
888 if (!getDecl())
889 return true;
890 if (!isDerivedMember()) {
891 Path.push_back(Derived);
892 return true;
893 }
894 if (!castBack(Derived))
895 return false;
896 if (Path.empty())
897 DeclAndIsDerivedMember.setInt(false);
898 return true;
899 }
900 /// Perform a derived-to-base member pointer cast.
901 bool castToBase(const CXXRecordDecl *Base) {
902 if (!getDecl())
903 return true;
904 if (Path.empty())
905 DeclAndIsDerivedMember.setInt(true);
906 if (isDerivedMember()) {
907 Path.push_back(Base);
908 return true;
909 }
910 return castBack(Base);
911 }
912 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000913
Richard Smithb02e4622012-02-01 01:42:44 +0000914 /// Compare two member pointers, which are assumed to be of the same type.
915 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
916 if (!LHS.getDecl() || !RHS.getDecl())
917 return !LHS.getDecl() && !RHS.getDecl();
918 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
919 return false;
920 return LHS.Path == RHS.Path;
921 }
922
Richard Smithc1c5f272011-12-13 06:39:58 +0000923 /// Kinds of constant expression checking, for diagnostics.
924 enum CheckConstantExpressionKind {
925 CCEK_Constant, ///< A normal constant.
926 CCEK_ReturnValue, ///< A constexpr function return value.
927 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
928 };
John McCallf4cf1a12010-05-07 17:22:02 +0000929}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000930
Richard Smith47a1eed2011-10-29 20:57:55 +0000931static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000932static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
933 const LValue &This, const Expr *E,
934 CheckConstantExpressionKind CCEK = CCEK_Constant,
935 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000936static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
937static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000938static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
939 EvalInfo &Info);
940static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000941static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000942static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000943 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000944static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000945static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000946
947//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000948// Misc utilities
949//===----------------------------------------------------------------------===//
950
Richard Smith180f4792011-11-10 06:34:14 +0000951/// Should this call expression be treated as a string literal?
952static bool IsStringLiteralCall(const CallExpr *E) {
953 unsigned Builtin = E->isBuiltinCall();
954 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
955 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
956}
957
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000958static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000959 // C++11 [expr.const]p3 An address constant expression is a prvalue core
960 // constant expression of pointer type that evaluates to...
961
962 // ... a null pointer value, or a prvalue core constant expression of type
963 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000964 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000965
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000966 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
967 // ... the address of an object with static storage duration,
968 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
969 return VD->hasGlobalStorage();
970 // ... the address of a function,
971 return isa<FunctionDecl>(D);
972 }
973
974 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000975 switch (E->getStmtClass()) {
976 default:
977 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000978 case Expr::CompoundLiteralExprClass: {
979 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
980 return CLE->isFileScope() && CLE->isLValue();
981 }
Richard Smith180f4792011-11-10 06:34:14 +0000982 // A string literal has static storage duration.
983 case Expr::StringLiteralClass:
984 case Expr::PredefinedExprClass:
985 case Expr::ObjCStringLiteralClass:
986 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000987 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000988 return true;
989 case Expr::CallExprClass:
990 return IsStringLiteralCall(cast<CallExpr>(E));
991 // For GCC compatibility, &&label has static storage duration.
992 case Expr::AddrLabelExprClass:
993 return true;
994 // A Block literal expression may be used as the initialization value for
995 // Block variables at global or local static scope.
996 case Expr::BlockExprClass:
997 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000998 case Expr::ImplicitValueInitExprClass:
999 // FIXME:
1000 // We can never form an lvalue with an implicit value initialization as its
1001 // base through expression evaluation, so these only appear in one case: the
1002 // implicit variable declaration we invent when checking whether a constexpr
1003 // constructor can produce a constant expression. We must assume that such
1004 // an expression might be a global lvalue.
1005 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001006 }
John McCall42c8f872010-05-10 23:27:23 +00001007}
1008
Richard Smith83587db2012-02-15 02:18:13 +00001009static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1010 assert(Base && "no location for a null lvalue");
1011 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1012 if (VD)
1013 Info.Note(VD->getLocation(), diag::note_declared_at);
1014 else
1015 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
1016 diag::note_constexpr_temporary_here);
1017}
1018
Richard Smith9a17a682011-11-07 05:07:52 +00001019/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +00001020/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +00001021/// either LValue or CCValue. Return true if we can fold this expression,
1022/// whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00001023static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1024 QualType Type, const LValue &LVal) {
1025 bool IsReferenceType = Type->isReferenceType();
1026
Richard Smithc1c5f272011-12-13 06:39:58 +00001027 APValue::LValueBase Base = LVal.getLValueBase();
1028 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1029
Richard Smithb78ae972012-02-18 04:58:18 +00001030 // Check that the object is a global. Note that the fake 'this' object we
1031 // manufacture when checking potential constant expressions is conservatively
1032 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +00001033 if (!IsGlobalLValue(Base)) {
1034 if (Info.getLangOpts().CPlusPlus0x) {
1035 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001036 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1037 << IsReferenceType << !Designator.Entries.empty()
1038 << !!VD << VD;
1039 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001040 } else {
Richard Smith83587db2012-02-15 02:18:13 +00001041 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +00001042 }
Richard Smith61e61622012-01-12 06:08:57 +00001043 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +00001044 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001045 }
Richard Smith83587db2012-02-15 02:18:13 +00001046 assert((Info.CheckingPotentialConstantExpression ||
1047 LVal.getLValueCallIndex() == 0) &&
1048 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +00001049
1050 // Allow address constant expressions to be past-the-end pointers. This is
1051 // an extension: the standard requires them to point to an object.
1052 if (!IsReferenceType)
1053 return true;
1054
1055 // A reference constant expression must refer to an object.
1056 if (!Base) {
1057 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001058 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001059 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001060 }
1061
Richard Smithc1c5f272011-12-13 06:39:58 +00001062 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001063 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001064 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001065 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001066 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001067 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001068 }
1069
Richard Smith9a17a682011-11-07 05:07:52 +00001070 return true;
1071}
1072
Richard Smith51201882011-12-30 21:15:51 +00001073/// Check that this core constant expression is of literal type, and if not,
1074/// produce an appropriate diagnostic.
1075static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1076 if (!E->isRValue() || E->getType()->isLiteralType())
1077 return true;
1078
1079 // Prvalue constant expressions must be of literal types.
1080 if (Info.getLangOpts().CPlusPlus0x)
1081 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
1082 << E->getType();
1083 else
1084 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1085 return false;
1086}
1087
Richard Smith47a1eed2011-10-29 20:57:55 +00001088/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001089/// constant expression. If not, report an appropriate diagnostic. Does not
1090/// check that the expression is of literal type.
1091static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1092 QualType Type, const APValue &Value) {
1093 // Core issue 1454: For a literal constant expression of array or class type,
1094 // each subobject of its value shall have been initialized by a constant
1095 // expression.
1096 if (Value.isArray()) {
1097 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1098 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1099 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1100 Value.getArrayInitializedElt(I)))
1101 return false;
1102 }
1103 if (!Value.hasArrayFiller())
1104 return true;
1105 return CheckConstantExpression(Info, DiagLoc, EltTy,
1106 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001107 }
Richard Smith83587db2012-02-15 02:18:13 +00001108 if (Value.isUnion() && Value.getUnionField()) {
1109 return CheckConstantExpression(Info, DiagLoc,
1110 Value.getUnionField()->getType(),
1111 Value.getUnionValue());
1112 }
1113 if (Value.isStruct()) {
1114 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1115 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1116 unsigned BaseIndex = 0;
1117 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1118 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1119 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1120 Value.getStructBase(BaseIndex)))
1121 return false;
1122 }
1123 }
1124 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1125 I != E; ++I) {
1126 if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
1127 Value.getStructField((*I)->getFieldIndex())))
1128 return false;
1129 }
1130 }
1131
1132 if (Value.isLValue()) {
1133 CCValue Val(Info.Ctx, Value, CCValue::GlobalValue());
1134 LValue LVal;
1135 LVal.setFrom(Val);
1136 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1137 }
1138
1139 // Everything else is fine.
1140 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001141}
1142
Richard Smith9e36b532011-10-31 05:11:32 +00001143const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001144 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001145}
1146
1147static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001148 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001149}
1150
Richard Smith65ac5982011-11-01 21:06:14 +00001151static bool IsWeakLValue(const LValue &Value) {
1152 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001153 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001154}
1155
Richard Smithe24f5fc2011-11-17 22:56:20 +00001156static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001157 // A null base expression indicates a null pointer. These are always
1158 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001159 if (!Value.getLValueBase()) {
1160 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001161 return true;
1162 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001163
Richard Smithe24f5fc2011-11-17 22:56:20 +00001164 // We have a non-null base. These are generally known to be true, but if it's
1165 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001166 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001167 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001168 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001169}
1170
Richard Smith47a1eed2011-10-29 20:57:55 +00001171static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001172 switch (Val.getKind()) {
1173 case APValue::Uninitialized:
1174 return false;
1175 case APValue::Int:
1176 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001177 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001178 case APValue::Float:
1179 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001180 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001181 case APValue::ComplexInt:
1182 Result = Val.getComplexIntReal().getBoolValue() ||
1183 Val.getComplexIntImag().getBoolValue();
1184 return true;
1185 case APValue::ComplexFloat:
1186 Result = !Val.getComplexFloatReal().isZero() ||
1187 !Val.getComplexFloatImag().isZero();
1188 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001189 case APValue::LValue:
1190 return EvalPointerValueAsBool(Val, Result);
1191 case APValue::MemberPointer:
1192 Result = Val.getMemberPointerDecl();
1193 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001194 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001195 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001196 case APValue::Struct:
1197 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001198 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001199 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001200 }
1201
Richard Smithc49bd112011-10-28 17:51:58 +00001202 llvm_unreachable("unknown APValue kind");
1203}
1204
1205static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1206 EvalInfo &Info) {
1207 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001208 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001209 if (!Evaluate(Val, Info, E))
1210 return false;
1211 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001212}
1213
Richard Smithc1c5f272011-12-13 06:39:58 +00001214template<typename T>
1215static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1216 const T &SrcValue, QualType DestType) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001217 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001218 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001219 return false;
1220}
1221
1222static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1223 QualType SrcType, const APFloat &Value,
1224 QualType DestType, APSInt &Result) {
1225 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001226 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001227 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Richard Smithc1c5f272011-12-13 06:39:58 +00001229 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001230 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001231 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1232 & APFloat::opInvalidOp)
1233 return HandleOverflow(Info, E, Value, DestType);
1234 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001235}
1236
Richard Smithc1c5f272011-12-13 06:39:58 +00001237static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1238 QualType SrcType, QualType DestType,
1239 APFloat &Result) {
1240 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001241 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001242 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1243 APFloat::rmNearestTiesToEven, &ignored)
1244 & APFloat::opOverflow)
1245 return HandleOverflow(Info, E, Value, DestType);
1246 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001247}
1248
Richard Smithf72fccf2012-01-30 22:27:01 +00001249static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1250 QualType DestType, QualType SrcType,
1251 APSInt &Value) {
1252 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001253 APSInt Result = Value;
1254 // Figure out if this is a truncate, extend or noop cast.
1255 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001256 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001257 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001258 return Result;
1259}
1260
Richard Smithc1c5f272011-12-13 06:39:58 +00001261static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1262 QualType SrcType, const APSInt &Value,
1263 QualType DestType, APFloat &Result) {
1264 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1265 if (Result.convertFromAPInt(Value, Value.isSigned(),
1266 APFloat::rmNearestTiesToEven)
1267 & APFloat::opOverflow)
1268 return HandleOverflow(Info, E, Value, DestType);
1269 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001270}
1271
Eli Friedmane6a24e82011-12-22 03:51:45 +00001272static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1273 llvm::APInt &Res) {
1274 CCValue SVal;
1275 if (!Evaluate(SVal, Info, E))
1276 return false;
1277 if (SVal.isInt()) {
1278 Res = SVal.getInt();
1279 return true;
1280 }
1281 if (SVal.isFloat()) {
1282 Res = SVal.getFloat().bitcastToAPInt();
1283 return true;
1284 }
1285 if (SVal.isVector()) {
1286 QualType VecTy = E->getType();
1287 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1288 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1289 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1290 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1291 Res = llvm::APInt::getNullValue(VecSize);
1292 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1293 APValue &Elt = SVal.getVectorElt(i);
1294 llvm::APInt EltAsInt;
1295 if (Elt.isInt()) {
1296 EltAsInt = Elt.getInt();
1297 } else if (Elt.isFloat()) {
1298 EltAsInt = Elt.getFloat().bitcastToAPInt();
1299 } else {
1300 // Don't try to handle vectors of anything other than int or float
1301 // (not sure if it's possible to hit this case).
1302 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1303 return false;
1304 }
1305 unsigned BaseEltSize = EltAsInt.getBitWidth();
1306 if (BigEndian)
1307 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1308 else
1309 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1310 }
1311 return true;
1312 }
1313 // Give up if the input isn't an int, float, or vector. For example, we
1314 // reject "(v4i16)(intptr_t)&a".
1315 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1316 return false;
1317}
1318
Richard Smithb4e85ed2012-01-06 16:39:00 +00001319/// Cast an lvalue referring to a base subobject to a derived class, by
1320/// truncating the lvalue's path to the given length.
1321static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1322 const RecordDecl *TruncatedType,
1323 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001324 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001325
1326 // Check we actually point to a derived class object.
1327 if (TruncatedElements == D.Entries.size())
1328 return true;
1329 assert(TruncatedElements >= D.MostDerivedPathLength &&
1330 "not casting to a derived class");
1331 if (!Result.checkSubobject(Info, E, CSK_Derived))
1332 return false;
1333
1334 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001335 const RecordDecl *RD = TruncatedType;
1336 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001337 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1338 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001339 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001340 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001341 else
Richard Smith180f4792011-11-10 06:34:14 +00001342 Result.Offset -= Layout.getBaseClassOffset(Base);
1343 RD = Base;
1344 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001345 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001346 return true;
1347}
1348
Richard Smithb4e85ed2012-01-06 16:39:00 +00001349static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001350 const CXXRecordDecl *Derived,
1351 const CXXRecordDecl *Base,
1352 const ASTRecordLayout *RL = 0) {
1353 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1354 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001355 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001356}
1357
Richard Smithb4e85ed2012-01-06 16:39:00 +00001358static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001359 const CXXRecordDecl *DerivedDecl,
1360 const CXXBaseSpecifier *Base) {
1361 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1362
1363 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001364 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001365 return true;
1366 }
1367
Richard Smithb4e85ed2012-01-06 16:39:00 +00001368 SubobjectDesignator &D = Obj.Designator;
1369 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001370 return false;
1371
Richard Smithb4e85ed2012-01-06 16:39:00 +00001372 // Extract most-derived object and corresponding type.
1373 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1374 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1375 return false;
1376
1377 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001378 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1379 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001380 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001381 return true;
1382}
1383
1384/// Update LVal to refer to the given field, which must be a member of the type
1385/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001386static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001387 const FieldDecl *FD,
1388 const ASTRecordLayout *RL = 0) {
1389 if (!RL)
1390 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1391
1392 unsigned I = FD->getFieldIndex();
1393 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001394 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001395}
1396
Richard Smithd9b02e72012-01-25 22:15:11 +00001397/// Update LVal to refer to the given indirect field.
1398static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1399 LValue &LVal,
1400 const IndirectFieldDecl *IFD) {
1401 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1402 CE = IFD->chain_end(); C != CE; ++C)
1403 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1404}
1405
Richard Smith180f4792011-11-10 06:34:14 +00001406/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001407static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1408 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001409 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1410 // extension.
1411 if (Type->isVoidType() || Type->isFunctionType()) {
1412 Size = CharUnits::One();
1413 return true;
1414 }
1415
1416 if (!Type->isConstantSizeType()) {
1417 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001418 // FIXME: Better diagnostic.
1419 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001420 return false;
1421 }
1422
1423 Size = Info.Ctx.getTypeSizeInChars(Type);
1424 return true;
1425}
1426
1427/// Update a pointer value to model pointer arithmetic.
1428/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001429/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001430/// \param LVal - The pointer value to be updated.
1431/// \param EltTy - The pointee type represented by LVal.
1432/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001433static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1434 LValue &LVal, QualType EltTy,
1435 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001436 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001437 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001438 return false;
1439
1440 // Compute the new offset in the appropriate width.
1441 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001442 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001443 return true;
1444}
1445
Richard Smith86024012012-02-18 22:04:06 +00001446/// Update an lvalue to refer to a component of a complex number.
1447/// \param Info - Information about the ongoing evaluation.
1448/// \param LVal - The lvalue to be updated.
1449/// \param EltTy - The complex number's component type.
1450/// \param Imag - False for the real component, true for the imaginary.
1451static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1452 LValue &LVal, QualType EltTy,
1453 bool Imag) {
1454 if (Imag) {
1455 CharUnits SizeOfComponent;
1456 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1457 return false;
1458 LVal.Offset += SizeOfComponent;
1459 }
1460 LVal.addComplex(Info, E, EltTy, Imag);
1461 return true;
1462}
1463
Richard Smith03f96112011-10-24 17:54:18 +00001464/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001465static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1466 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001467 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001468 // If this is a parameter to an active constexpr function call, perform
1469 // argument substitution.
1470 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001471 // Assume arguments of a potential constant expression are unknown
1472 // constant expressions.
1473 if (Info.CheckingPotentialConstantExpression)
1474 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001475 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001476 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001477 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001478 }
Richard Smith177dce72011-11-01 16:57:24 +00001479 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1480 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001481 }
Richard Smith03f96112011-10-24 17:54:18 +00001482
Richard Smith099e7f62011-12-19 06:19:21 +00001483 // Dig out the initializer, and use the declaration which it's attached to.
1484 const Expr *Init = VD->getAnyInitializer(VD);
1485 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001486 // If we're checking a potential constant expression, the variable could be
1487 // initialized later.
1488 if (!Info.CheckingPotentialConstantExpression)
1489 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001490 return false;
1491 }
1492
Richard Smith180f4792011-11-10 06:34:14 +00001493 // If we're currently evaluating the initializer of this declaration, use that
1494 // in-flight value.
1495 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001496 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1497 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001498 return !Result.isUninit();
1499 }
1500
Richard Smith65ac5982011-11-01 21:06:14 +00001501 // Never evaluate the initializer of a weak variable. We can't be sure that
1502 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001503 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001504 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001505 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001506 }
Richard Smith65ac5982011-11-01 21:06:14 +00001507
Richard Smith099e7f62011-12-19 06:19:21 +00001508 // Check that we can fold the initializer. In C++, we will have already done
1509 // this in the cases where it matters for conformance.
1510 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1511 if (!VD->evaluateValue(Notes)) {
1512 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1513 Notes.size() + 1) << VD;
1514 Info.Note(VD->getLocation(), diag::note_declared_at);
1515 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001516 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001517 } else if (!VD->checkInitIsICE()) {
1518 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1519 Notes.size() + 1) << VD;
1520 Info.Note(VD->getLocation(), diag::note_declared_at);
1521 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001522 }
Richard Smith03f96112011-10-24 17:54:18 +00001523
Richard Smithb4e85ed2012-01-06 16:39:00 +00001524 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001525 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001526}
1527
Richard Smithc49bd112011-10-28 17:51:58 +00001528static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001529 Qualifiers Quals = T.getQualifiers();
1530 return Quals.hasConst() && !Quals.hasVolatile();
1531}
1532
Richard Smith59efe262011-11-11 04:05:33 +00001533/// Get the base index of the given base class within an APValue representing
1534/// the given derived class.
1535static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1536 const CXXRecordDecl *Base) {
1537 Base = Base->getCanonicalDecl();
1538 unsigned Index = 0;
1539 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1540 E = Derived->bases_end(); I != E; ++I, ++Index) {
1541 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1542 return Index;
1543 }
1544
1545 llvm_unreachable("base class missing from derived class's bases list");
1546}
1547
Richard Smithf3908f22012-02-17 03:35:37 +00001548/// Extract the value of a character from a string literal.
1549static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1550 uint64_t Index) {
1551 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1552 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1553 assert(S && "unexpected string literal expression kind");
1554
1555 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1556 Lit->getType()->getArrayElementTypeNoTypeQual()->isUnsignedIntegerType());
1557 if (Index < S->getLength())
1558 Value = S->getCodeUnit(Index);
1559 return Value;
1560}
1561
Richard Smithcc5d4f62011-11-07 09:22:26 +00001562/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001563static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1564 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001565 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001566 if (Sub.Invalid)
1567 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001568 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001569 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001570 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001571 (unsigned)diag::note_constexpr_read_past_end :
1572 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001573 return false;
1574 }
Richard Smithf64699e2011-11-11 08:28:03 +00001575 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001576 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001577 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1578 // This object might be initialized later.
1579 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001580
Richard Smithcc5d4f62011-11-07 09:22:26 +00001581 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001582 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001583 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001584 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001585 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001586 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001587 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001588 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001589 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001590 // Note, it should not be possible to form a pointer with a valid
1591 // designator which points more than one past the end of the array.
1592 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001593 (unsigned)diag::note_constexpr_read_past_end :
1594 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001595 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001596 }
Richard Smithf3908f22012-02-17 03:35:37 +00001597 // An array object is represented as either an Array APValue or as an
1598 // LValue which refers to a string literal.
1599 if (O->isLValue()) {
1600 assert(I == N - 1 && "extracting subobject of character?");
1601 assert(!O->hasLValuePath() || O->getLValuePath().empty());
1602 Obj = CCValue(ExtractStringLiteralCharacter(
1603 Info, O->getLValueBase().get<const Expr*>(), Index));
1604 return true;
1605 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001606 O = &O->getArrayInitializedElt(Index);
1607 else
1608 O = &O->getArrayFiller();
1609 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001610 } else if (ObjType->isAnyComplexType()) {
1611 // Next subobject is a complex number.
1612 uint64_t Index = Sub.Entries[I].ArrayIndex;
1613 if (Index > 1) {
1614 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
1615 (unsigned)diag::note_constexpr_read_past_end :
1616 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1617 return false;
1618 }
1619 assert(I == N - 1 && "extracting subobject of scalar?");
1620 if (O->isComplexInt()) {
1621 Obj = CCValue(Index ? O->getComplexIntImag()
1622 : O->getComplexIntReal());
1623 } else {
1624 assert(O->isComplexFloat());
1625 Obj = CCValue(Index ? O->getComplexFloatImag()
1626 : O->getComplexFloatReal());
1627 }
1628 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001629 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001630 if (Field->isMutable()) {
1631 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_mutable, 1)
1632 << Field;
1633 Info.Note(Field->getLocation(), diag::note_declared_at);
1634 return false;
1635 }
1636
Richard Smith180f4792011-11-10 06:34:14 +00001637 // Next subobject is a class, struct or union field.
1638 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1639 if (RD->isUnion()) {
1640 const FieldDecl *UnionField = O->getUnionField();
1641 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001642 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001643 Info.Diag(E->getExprLoc(),
1644 diag::note_constexpr_read_inactive_union_member)
1645 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001646 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001647 }
Richard Smith180f4792011-11-10 06:34:14 +00001648 O = &O->getUnionValue();
1649 } else
1650 O = &O->getStructField(Field->getFieldIndex());
1651 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001652
1653 if (ObjType.isVolatileQualified()) {
1654 if (Info.getLangOpts().CPlusPlus) {
1655 // FIXME: Include a description of the path to the volatile subobject.
1656 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1657 << 2 << Field;
1658 Info.Note(Field->getLocation(), diag::note_declared_at);
1659 } else {
1660 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1661 }
1662 return false;
1663 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001664 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001665 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001666 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1667 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1668 O = &O->getStructBase(getBaseIndex(Derived, Base));
1669 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001670 }
Richard Smith180f4792011-11-10 06:34:14 +00001671
Richard Smithf48fdb02011-12-09 22:58:01 +00001672 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001673 if (!Info.CheckingPotentialConstantExpression)
1674 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001675 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001676 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001677 }
1678
Richard Smithb4e85ed2012-01-06 16:39:00 +00001679 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001680 return true;
1681}
1682
Richard Smithf15fda02012-02-02 01:16:57 +00001683/// Find the position where two subobject designators diverge, or equivalently
1684/// the length of the common initial subsequence.
1685static unsigned FindDesignatorMismatch(QualType ObjType,
1686 const SubobjectDesignator &A,
1687 const SubobjectDesignator &B,
1688 bool &WasArrayIndex) {
1689 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1690 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001691 if (!ObjType.isNull() &&
1692 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001693 // Next subobject is an array element.
1694 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1695 WasArrayIndex = true;
1696 return I;
1697 }
Richard Smith86024012012-02-18 22:04:06 +00001698 if (ObjType->isAnyComplexType())
1699 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1700 else
1701 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001702 } else {
1703 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1704 WasArrayIndex = false;
1705 return I;
1706 }
1707 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1708 // Next subobject is a field.
1709 ObjType = FD->getType();
1710 else
1711 // Next subobject is a base class.
1712 ObjType = QualType();
1713 }
1714 }
1715 WasArrayIndex = false;
1716 return I;
1717}
1718
1719/// Determine whether the given subobject designators refer to elements of the
1720/// same array object.
1721static bool AreElementsOfSameArray(QualType ObjType,
1722 const SubobjectDesignator &A,
1723 const SubobjectDesignator &B) {
1724 if (A.Entries.size() != B.Entries.size())
1725 return false;
1726
1727 bool IsArray = A.MostDerivedArraySize != 0;
1728 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1729 // A is a subobject of the array element.
1730 return false;
1731
1732 // If A (and B) designates an array element, the last entry will be the array
1733 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1734 // of length 1' case, and the entire path must match.
1735 bool WasArrayIndex;
1736 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1737 return CommonLength >= A.Entries.size() - IsArray;
1738}
1739
Richard Smith180f4792011-11-10 06:34:14 +00001740/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1741/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1742/// for looking up the glvalue referred to by an entity of reference type.
1743///
1744/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001745/// \param Conv - The expression for which we are performing the conversion.
1746/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001747/// \param Type - The type we expect this conversion to produce, before
1748/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001749/// \param LVal - The glvalue on which we are attempting to perform this action.
1750/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001751static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1752 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001753 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001754 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1755 if (!Info.getLangOpts().CPlusPlus)
1756 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1757
Richard Smithb4e85ed2012-01-06 16:39:00 +00001758 if (LVal.Designator.Invalid)
1759 // A diagnostic will have already been produced.
1760 return false;
1761
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001762 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith7098cbd2011-12-21 05:04:46 +00001763 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001764
Richard Smithf48fdb02011-12-09 22:58:01 +00001765 if (!LVal.Base) {
1766 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001767 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1768 return false;
1769 }
1770
Richard Smith83587db2012-02-15 02:18:13 +00001771 CallStackFrame *Frame = 0;
1772 if (LVal.CallIndex) {
1773 Frame = Info.getCallFrame(LVal.CallIndex);
1774 if (!Frame) {
1775 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1776 NoteLValueLocation(Info, LVal.Base);
1777 return false;
1778 }
1779 }
1780
Richard Smith7098cbd2011-12-21 05:04:46 +00001781 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1782 // is not a constant expression (even if the object is non-volatile). We also
1783 // apply this rule to C++98, in order to conform to the expected 'volatile'
1784 // semantics.
1785 if (Type.isVolatileQualified()) {
1786 if (Info.getLangOpts().CPlusPlus)
1787 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1788 else
1789 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001790 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001791 }
Richard Smithc49bd112011-10-28 17:51:58 +00001792
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001793 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001794 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1795 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001796 // expressions are constant expressions too. Inside constexpr functions,
1797 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001798 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001799 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf15fda02012-02-02 01:16:57 +00001800 if (const VarDecl *VDef = VD->getDefinition())
1801 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001802 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001803 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001804 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001805 }
1806
Richard Smith7098cbd2011-12-21 05:04:46 +00001807 // DR1313: If the object is volatile-qualified but the glvalue was not,
1808 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001809 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001810 if (VT.isVolatileQualified()) {
1811 if (Info.getLangOpts().CPlusPlus) {
1812 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1813 Info.Note(VD->getLocation(), diag::note_declared_at);
1814 } else {
1815 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001816 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001817 return false;
1818 }
1819
1820 if (!isa<ParmVarDecl>(VD)) {
1821 if (VD->isConstexpr()) {
1822 // OK, we can read this variable.
1823 } else if (VT->isIntegralOrEnumerationType()) {
1824 if (!VT.isConstQualified()) {
1825 if (Info.getLangOpts().CPlusPlus) {
1826 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1827 Info.Note(VD->getLocation(), diag::note_declared_at);
1828 } else {
1829 Info.Diag(Loc);
1830 }
1831 return false;
1832 }
1833 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1834 // We support folding of const floating-point types, in order to make
1835 // static const data members of such types (supported as an extension)
1836 // more useful.
1837 if (Info.getLangOpts().CPlusPlus0x) {
1838 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1839 Info.Note(VD->getLocation(), diag::note_declared_at);
1840 } else {
1841 Info.CCEDiag(Loc);
1842 }
1843 } else {
1844 // FIXME: Allow folding of values of any literal type in all languages.
1845 if (Info.getLangOpts().CPlusPlus0x) {
1846 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1847 Info.Note(VD->getLocation(), diag::note_declared_at);
1848 } else {
1849 Info.Diag(Loc);
1850 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001851 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001852 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001853 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001854
Richard Smithf48fdb02011-12-09 22:58:01 +00001855 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001856 return false;
1857
Richard Smith47a1eed2011-10-29 20:57:55 +00001858 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001859 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001860
1861 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1862 // conversion. This happens when the declaration and the lvalue should be
1863 // considered synonymous, for instance when initializing an array of char
1864 // from a string literal. Continue as if the initializer lvalue was the
1865 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001866 assert(RVal.getLValueOffset().isZero() &&
1867 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001868 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001869
1870 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1871 Frame = Info.getCallFrame(CallIndex);
1872 if (!Frame) {
1873 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1874 NoteLValueLocation(Info, RVal.getLValueBase());
1875 return false;
1876 }
1877 } else {
1878 Frame = 0;
1879 }
Richard Smithc49bd112011-10-28 17:51:58 +00001880 }
1881
Richard Smith7098cbd2011-12-21 05:04:46 +00001882 // Volatile temporary objects cannot be read in constant expressions.
1883 if (Base->getType().isVolatileQualified()) {
1884 if (Info.getLangOpts().CPlusPlus) {
1885 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1886 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1887 } else {
1888 Info.Diag(Loc);
1889 }
1890 return false;
1891 }
1892
Richard Smithcc5d4f62011-11-07 09:22:26 +00001893 if (Frame) {
1894 // If this is a temporary expression with a nontrivial initializer, grab the
1895 // value from the relevant stack frame.
1896 RVal = Frame->Temporaries[Base];
1897 } else if (const CompoundLiteralExpr *CLE
1898 = dyn_cast<CompoundLiteralExpr>(Base)) {
1899 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1900 // initializer until now for such expressions. Such an expression can't be
1901 // an ICE in C, so this only matters for fold.
1902 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1903 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1904 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001905 } else if (isa<StringLiteral>(Base)) {
1906 // We represent a string literal array as an lvalue pointing at the
1907 // corresponding expression, rather than building an array of chars.
1908 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1909 RVal = CCValue(Info.Ctx,
1910 APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0),
1911 CCValue::GlobalValue());
Richard Smithf48fdb02011-12-09 22:58:01 +00001912 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001913 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001914 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001915 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001916
Richard Smithf48fdb02011-12-09 22:58:01 +00001917 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1918 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001919}
1920
Richard Smith59efe262011-11-11 04:05:33 +00001921/// Build an lvalue for the object argument of a member function call.
1922static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1923 LValue &This) {
1924 if (Object->getType()->isPointerType())
1925 return EvaluatePointer(Object, This, Info);
1926
1927 if (Object->isGLValue())
1928 return EvaluateLValue(Object, This, Info);
1929
Richard Smithe24f5fc2011-11-17 22:56:20 +00001930 if (Object->getType()->isLiteralType())
1931 return EvaluateTemporary(Object, This, Info);
1932
1933 return false;
1934}
1935
1936/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1937/// lvalue referring to the result.
1938///
1939/// \param Info - Information about the ongoing evaluation.
1940/// \param BO - The member pointer access operation.
1941/// \param LV - Filled in with a reference to the resulting object.
1942/// \param IncludeMember - Specifies whether the member itself is included in
1943/// the resulting LValue subobject designator. This is not possible when
1944/// creating a bound member function.
1945/// \return The field or method declaration to which the member pointer refers,
1946/// or 0 if evaluation fails.
1947static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1948 const BinaryOperator *BO,
1949 LValue &LV,
1950 bool IncludeMember = true) {
1951 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1952
Richard Smith745f5142012-01-27 01:14:48 +00001953 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1954 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001955 return 0;
1956
1957 MemberPtr MemPtr;
1958 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1959 return 0;
1960
1961 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1962 // member value, the behavior is undefined.
1963 if (!MemPtr.getDecl())
1964 return 0;
1965
Richard Smith745f5142012-01-27 01:14:48 +00001966 if (!EvalObjOK)
1967 return 0;
1968
Richard Smithe24f5fc2011-11-17 22:56:20 +00001969 if (MemPtr.isDerivedMember()) {
1970 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001971 // The end of the derived-to-base path for the base object must match the
1972 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001973 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001974 LV.Designator.Entries.size())
1975 return 0;
1976 unsigned PathLengthToMember =
1977 LV.Designator.Entries.size() - MemPtr.Path.size();
1978 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1979 const CXXRecordDecl *LVDecl = getAsBaseClass(
1980 LV.Designator.Entries[PathLengthToMember + I]);
1981 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1982 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1983 return 0;
1984 }
1985
1986 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001987 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1988 PathLengthToMember))
1989 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001990 } else if (!MemPtr.Path.empty()) {
1991 // Extend the LValue path with the member pointer's path.
1992 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1993 MemPtr.Path.size() + IncludeMember);
1994
1995 // Walk down to the appropriate base class.
1996 QualType LVType = BO->getLHS()->getType();
1997 if (const PointerType *PT = LVType->getAs<PointerType>())
1998 LVType = PT->getPointeeType();
1999 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2000 assert(RD && "member pointer access on non-class-type expression");
2001 // The first class in the path is that of the lvalue.
2002 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2003 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00002004 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002005 RD = Base;
2006 }
2007 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002008 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002009 }
2010
2011 // Add the member. Note that we cannot build bound member functions here.
2012 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002013 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
2014 HandleLValueMember(Info, BO, LV, FD);
2015 else if (const IndirectFieldDecl *IFD =
2016 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
2017 HandleLValueIndirectMember(Info, BO, LV, IFD);
2018 else
2019 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00002020 }
2021
2022 return MemPtr.getDecl();
2023}
2024
2025/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2026/// the provided lvalue, which currently refers to the base object.
2027static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2028 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002029 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002030 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002031 return false;
2032
Richard Smithb4e85ed2012-01-06 16:39:00 +00002033 QualType TargetQT = E->getType();
2034 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2035 TargetQT = PT->getPointeeType();
2036
2037 // Check this cast lands within the final derived-to-base subobject path.
2038 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
2039 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
2040 << D.MostDerivedType << TargetQT;
2041 return false;
2042 }
2043
Richard Smithe24f5fc2011-11-17 22:56:20 +00002044 // Check the type of the final cast. We don't need to check the path,
2045 // since a cast can only be formed if the path is unique.
2046 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002047 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2048 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002049 if (NewEntriesSize == D.MostDerivedPathLength)
2050 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2051 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002052 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002053 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
2054 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
2055 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002056 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002057 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002058
2059 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002060 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002061}
2062
Mike Stumpc4c90452009-10-27 22:09:17 +00002063namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002064enum EvalStmtResult {
2065 /// Evaluation failed.
2066 ESR_Failed,
2067 /// Hit a 'return' statement.
2068 ESR_Returned,
2069 /// Evaluation succeeded.
2070 ESR_Succeeded
2071};
2072}
2073
2074// Evaluate a statement.
Richard Smith83587db2012-02-15 02:18:13 +00002075static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002076 const Stmt *S) {
2077 switch (S->getStmtClass()) {
2078 default:
2079 return ESR_Failed;
2080
2081 case Stmt::NullStmtClass:
2082 case Stmt::DeclStmtClass:
2083 return ESR_Succeeded;
2084
Richard Smithc1c5f272011-12-13 06:39:58 +00002085 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002086 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002087 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002088 return ESR_Failed;
2089 return ESR_Returned;
2090 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002091
2092 case Stmt::CompoundStmtClass: {
2093 const CompoundStmt *CS = cast<CompoundStmt>(S);
2094 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2095 BE = CS->body_end(); BI != BE; ++BI) {
2096 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2097 if (ESR != ESR_Succeeded)
2098 return ESR;
2099 }
2100 return ESR_Succeeded;
2101 }
2102 }
2103}
2104
Richard Smith61802452011-12-22 02:22:31 +00002105/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2106/// default constructor. If so, we'll fold it whether or not it's marked as
2107/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2108/// so we need special handling.
2109static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002110 const CXXConstructorDecl *CD,
2111 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002112 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2113 return false;
2114
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002115 // Value-initialization does not call a trivial default constructor, so such a
2116 // call is a core constant expression whether or not the constructor is
2117 // constexpr.
2118 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002119 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002120 // FIXME: If DiagDecl is an implicitly-declared special member function,
2121 // we should be much more explicit about why it's not constexpr.
2122 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2123 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2124 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002125 } else {
2126 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2127 }
2128 }
2129 return true;
2130}
2131
Richard Smithc1c5f272011-12-13 06:39:58 +00002132/// CheckConstexprFunction - Check that a function can be called in a constant
2133/// expression.
2134static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2135 const FunctionDecl *Declaration,
2136 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002137 // Potential constant expressions can contain calls to declared, but not yet
2138 // defined, constexpr functions.
2139 if (Info.CheckingPotentialConstantExpression && !Definition &&
2140 Declaration->isConstexpr())
2141 return false;
2142
Richard Smithc1c5f272011-12-13 06:39:58 +00002143 // Can we evaluate this function call?
2144 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2145 return true;
2146
2147 if (Info.getLangOpts().CPlusPlus0x) {
2148 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002149 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2150 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002151 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2152 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2153 << DiagDecl;
2154 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2155 } else {
2156 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2157 }
2158 return false;
2159}
2160
Richard Smith180f4792011-11-10 06:34:14 +00002161namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00002162typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002163}
2164
2165/// EvaluateArgs - Evaluate the arguments to a function call.
2166static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2167 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002168 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002169 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002170 I != E; ++I) {
2171 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2172 // If we're checking for a potential constant expression, evaluate all
2173 // initializers even if some of them fail.
2174 if (!Info.keepEvaluatingAfterFailure())
2175 return false;
2176 Success = false;
2177 }
2178 }
2179 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002180}
2181
Richard Smithd0dccea2011-10-28 22:34:42 +00002182/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002183static bool HandleFunctionCall(SourceLocation CallLoc,
2184 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002185 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith83587db2012-02-15 02:18:13 +00002186 EvalInfo &Info, CCValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002187 ArgVector ArgValues(Args.size());
2188 if (!EvaluateArgs(Args, ArgValues, Info))
2189 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002190
Richard Smith745f5142012-01-27 01:14:48 +00002191 if (!Info.CheckCallLimit(CallLoc))
2192 return false;
2193
2194 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002195 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2196}
2197
Richard Smith180f4792011-11-10 06:34:14 +00002198/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002199static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002200 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002201 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002202 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002203 ArgVector ArgValues(Args.size());
2204 if (!EvaluateArgs(Args, ArgValues, Info))
2205 return false;
2206
Richard Smith745f5142012-01-27 01:14:48 +00002207 if (!Info.CheckCallLimit(CallLoc))
2208 return false;
2209
Richard Smith86c3ae42012-02-13 03:54:03 +00002210 const CXXRecordDecl *RD = Definition->getParent();
2211 if (RD->getNumVBases()) {
2212 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2213 return false;
2214 }
2215
Richard Smith745f5142012-01-27 01:14:48 +00002216 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002217
2218 // If it's a delegating constructor, just delegate.
2219 if (Definition->isDelegatingConstructor()) {
2220 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002221 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002222 }
2223
Richard Smith610a60c2012-01-10 04:32:03 +00002224 // For a trivial copy or move constructor, perform an APValue copy. This is
2225 // essential for unions, where the operations performed by the constructor
2226 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002227 if (Definition->isDefaulted() &&
2228 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
2229 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
2230 LValue RHS;
2231 RHS.setFrom(ArgValues[0]);
2232 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00002233 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2234 RHS, Value))
2235 return false;
2236 assert((Value.isStruct() || Value.isUnion()) &&
2237 "trivial copy/move from non-class type?");
2238 // Any CCValue of class type must already be a constant expression.
2239 Result = Value;
2240 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00002241 }
2242
2243 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002244 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002245 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2246 std::distance(RD->field_begin(), RD->field_end()));
2247
2248 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2249
Richard Smith745f5142012-01-27 01:14:48 +00002250 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002251 unsigned BasesSeen = 0;
2252#ifndef NDEBUG
2253 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2254#endif
2255 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2256 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002257 LValue Subobject = This;
2258 APValue *Value = &Result;
2259
2260 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002261 if ((*I)->isBaseInitializer()) {
2262 QualType BaseType((*I)->getBaseClass(), 0);
2263#ifndef NDEBUG
2264 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002265 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002266 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2267 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2268 "base class initializers not in expected order");
2269 ++BaseIt;
2270#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002271 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002272 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002273 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002274 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002275 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002276 if (RD->isUnion()) {
2277 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002278 Value = &Result.getUnionValue();
2279 } else {
2280 Value = &Result.getStructField(FD->getFieldIndex());
2281 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002282 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002283 // Walk the indirect field decl's chain to find the object to initialize,
2284 // and make sure we've initialized every step along it.
2285 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2286 CE = IFD->chain_end();
2287 C != CE; ++C) {
2288 FieldDecl *FD = cast<FieldDecl>(*C);
2289 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2290 // Switch the union field if it differs. This happens if we had
2291 // preceding zero-initialization, and we're now initializing a union
2292 // subobject other than the first.
2293 // FIXME: In this case, the values of the other subobjects are
2294 // specified, since zero-initialization sets all padding bits to zero.
2295 if (Value->isUninit() ||
2296 (Value->isUnion() && Value->getUnionField() != FD)) {
2297 if (CD->isUnion())
2298 *Value = APValue(FD);
2299 else
2300 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2301 std::distance(CD->field_begin(), CD->field_end()));
2302 }
Richard Smith745f5142012-01-27 01:14:48 +00002303 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002304 if (CD->isUnion())
2305 Value = &Value->getUnionValue();
2306 else
2307 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002308 }
Richard Smith180f4792011-11-10 06:34:14 +00002309 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002310 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002311 }
Richard Smith745f5142012-01-27 01:14:48 +00002312
Richard Smith83587db2012-02-15 02:18:13 +00002313 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2314 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002315 ? CCEK_Constant : CCEK_MemberInit)) {
2316 // If we're checking for a potential constant expression, evaluate all
2317 // initializers even if some of them fail.
2318 if (!Info.keepEvaluatingAfterFailure())
2319 return false;
2320 Success = false;
2321 }
Richard Smith180f4792011-11-10 06:34:14 +00002322 }
2323
Richard Smith745f5142012-01-27 01:14:48 +00002324 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002325}
2326
Richard Smithd0dccea2011-10-28 22:34:42 +00002327namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002328class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002329 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002330 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002331public:
2332
Richard Smith1e12c592011-10-16 21:26:27 +00002333 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002334
2335 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002336 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002337 return true;
2338 }
2339
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002340 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2341 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002342 return Visit(E->getResultExpr());
2343 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002344 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002345 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002346 return true;
2347 return false;
2348 }
John McCallf85e1932011-06-15 23:02:42 +00002349 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002350 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002351 return true;
2352 return false;
2353 }
2354 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002355 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002356 return true;
2357 return false;
2358 }
2359
Mike Stumpc4c90452009-10-27 22:09:17 +00002360 // We don't want to evaluate BlockExprs multiple times, as they generate
2361 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002362 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2363 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2364 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002365 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002366 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2367 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2368 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2369 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2370 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2371 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002372 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002373 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002374 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002375 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002376 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002377 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2378 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2379 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2380 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002381 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002382 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2383 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2384 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2385 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2386 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002387 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002388 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002389 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002390 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002391 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002392
2393 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002394 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002395 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2396 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002397 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002398 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002399 return false;
2400 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002401
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002402 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002403};
2404
John McCall56ca35d2011-02-17 10:25:35 +00002405class OpaqueValueEvaluation {
2406 EvalInfo &info;
2407 OpaqueValueExpr *opaqueValue;
2408
2409public:
2410 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2411 Expr *value)
2412 : info(info), opaqueValue(opaqueValue) {
2413
2414 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002415 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002416 this->opaqueValue = 0;
2417 return;
2418 }
John McCall56ca35d2011-02-17 10:25:35 +00002419 }
2420
2421 bool hasError() const { return opaqueValue == 0; }
2422
2423 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002424 // FIXME: For a recursive constexpr call, an outer stack frame might have
2425 // been using this opaque value too, and will now have to re-evaluate the
2426 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002427 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2428 }
2429};
2430
Mike Stumpc4c90452009-10-27 22:09:17 +00002431} // end anonymous namespace
2432
Eli Friedman4efaa272008-11-12 09:44:48 +00002433//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002434// Generic Evaluation
2435//===----------------------------------------------------------------------===//
2436namespace {
2437
Richard Smithf48fdb02011-12-09 22:58:01 +00002438// FIXME: RetTy is always bool. Remove it.
2439template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002440class ExprEvaluatorBase
2441 : public ConstStmtVisitor<Derived, RetTy> {
2442private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002443 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002444 return static_cast<Derived*>(this)->Success(V, E);
2445 }
Richard Smith51201882011-12-30 21:15:51 +00002446 RetTy DerivedZeroInitialization(const Expr *E) {
2447 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002448 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002449
Richard Smith74e1ad92012-02-16 02:46:34 +00002450 // Check whether a conditional operator with a non-constant condition is a
2451 // potential constant expression. If neither arm is a potential constant
2452 // expression, then the conditional operator is not either.
2453 template<typename ConditionalOperator>
2454 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2455 assert(Info.CheckingPotentialConstantExpression);
2456
2457 // Speculatively evaluate both arms.
2458 {
2459 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2460 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2461
2462 StmtVisitorTy::Visit(E->getFalseExpr());
2463 if (Diag.empty())
2464 return;
2465
2466 Diag.clear();
2467 StmtVisitorTy::Visit(E->getTrueExpr());
2468 if (Diag.empty())
2469 return;
2470 }
2471
2472 Error(E, diag::note_constexpr_conditional_never_const);
2473 }
2474
2475
2476 template<typename ConditionalOperator>
2477 bool HandleConditionalOperator(const ConditionalOperator *E) {
2478 bool BoolResult;
2479 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2480 if (Info.CheckingPotentialConstantExpression)
2481 CheckPotentialConstantConditional(E);
2482 return false;
2483 }
2484
2485 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2486 return StmtVisitorTy::Visit(EvalExpr);
2487 }
2488
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002489protected:
2490 EvalInfo &Info;
2491 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2492 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2493
Richard Smithdd1f29b2011-12-12 09:28:41 +00002494 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002495 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002496 }
2497
2498 /// Report an evaluation error. This should only be called when an error is
2499 /// first discovered. When propagating an error, just return false.
2500 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002501 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002502 return false;
2503 }
2504 bool Error(const Expr *E) {
2505 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2506 }
2507
Richard Smith51201882011-12-30 21:15:51 +00002508 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002509
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002510public:
2511 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2512
2513 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002514 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002515 }
2516 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002517 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002518 }
2519
2520 RetTy VisitParenExpr(const ParenExpr *E)
2521 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2522 RetTy VisitUnaryExtension(const UnaryOperator *E)
2523 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2524 RetTy VisitUnaryPlus(const UnaryOperator *E)
2525 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2526 RetTy VisitChooseExpr(const ChooseExpr *E)
2527 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2528 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2529 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002530 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2531 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002532 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2533 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002534 // We cannot create any objects for which cleanups are required, so there is
2535 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2536 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2537 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002538
Richard Smithc216a012011-12-12 12:46:16 +00002539 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2540 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2541 return static_cast<Derived*>(this)->VisitCastExpr(E);
2542 }
2543 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2544 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2545 return static_cast<Derived*>(this)->VisitCastExpr(E);
2546 }
2547
Richard Smithe24f5fc2011-11-17 22:56:20 +00002548 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2549 switch (E->getOpcode()) {
2550 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002551 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002552
2553 case BO_Comma:
2554 VisitIgnoredValue(E->getLHS());
2555 return StmtVisitorTy::Visit(E->getRHS());
2556
2557 case BO_PtrMemD:
2558 case BO_PtrMemI: {
2559 LValue Obj;
2560 if (!HandleMemberPointerAccess(Info, E, Obj))
2561 return false;
2562 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002563 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002564 return false;
2565 return DerivedSuccess(Result, E);
2566 }
2567 }
2568 }
2569
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002570 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002571 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002572 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2573 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002574 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002575
Richard Smith74e1ad92012-02-16 02:46:34 +00002576 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002577 }
2578
2579 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002580 bool IsBcpCall = false;
2581 // If the condition (ignoring parens) is a __builtin_constant_p call,
2582 // the result is a constant expression if it can be folded without
2583 // side-effects. This is an important GNU extension. See GCC PR38377
2584 // for discussion.
2585 if (const CallExpr *CallCE =
2586 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2587 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2588 IsBcpCall = true;
2589
2590 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2591 // constant expression; we can't check whether it's potentially foldable.
2592 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2593 return false;
2594
2595 FoldConstant Fold(Info);
2596
Richard Smith74e1ad92012-02-16 02:46:34 +00002597 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002598 return false;
2599
2600 if (IsBcpCall)
2601 Fold.Fold(Info);
2602
2603 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002604 }
2605
2606 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002607 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002608 if (!Value) {
2609 const Expr *Source = E->getSourceExpr();
2610 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002611 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002612 if (Source == E) { // sanity checking.
2613 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002614 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002615 }
2616 return StmtVisitorTy::Visit(Source);
2617 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002618 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002619 }
Richard Smithf10d9172011-10-11 21:43:33 +00002620
Richard Smithd0dccea2011-10-28 22:34:42 +00002621 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002622 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002623 QualType CalleeType = Callee->getType();
2624
Richard Smithd0dccea2011-10-28 22:34:42 +00002625 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002626 LValue *This = 0, ThisVal;
2627 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002628 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002629
Richard Smith59efe262011-11-11 04:05:33 +00002630 // Extract function decl and 'this' pointer from the callee.
2631 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002632 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002633 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2634 // Explicit bound member calls, such as x.f() or p->g();
2635 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002636 return false;
2637 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002638 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002639 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002640 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2641 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002642 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2643 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002644 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002645 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002646 return Error(Callee);
2647
2648 FD = dyn_cast<FunctionDecl>(Member);
2649 if (!FD)
2650 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002651 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002652 LValue Call;
2653 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002654 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002655
Richard Smithb4e85ed2012-01-06 16:39:00 +00002656 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002657 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002658 FD = dyn_cast_or_null<FunctionDecl>(
2659 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002660 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002661 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002662
2663 // Overloaded operator calls to member functions are represented as normal
2664 // calls with '*this' as the first argument.
2665 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2666 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002667 // FIXME: When selecting an implicit conversion for an overloaded
2668 // operator delete, we sometimes try to evaluate calls to conversion
2669 // operators without a 'this' parameter!
2670 if (Args.empty())
2671 return Error(E);
2672
Richard Smith59efe262011-11-11 04:05:33 +00002673 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2674 return false;
2675 This = &ThisVal;
2676 Args = Args.slice(1);
2677 }
2678
2679 // Don't call function pointers which have been cast to some other type.
2680 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002681 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002682 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002683 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002684
Richard Smithb04035a2012-02-01 02:39:43 +00002685 if (This && !This->checkSubobject(Info, E, CSK_This))
2686 return false;
2687
Richard Smith86c3ae42012-02-13 03:54:03 +00002688 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2689 // calls to such functions in constant expressions.
2690 if (This && !HasQualifier &&
2691 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2692 return Error(E, diag::note_constexpr_virtual_call);
2693
Richard Smithc1c5f272011-12-13 06:39:58 +00002694 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002695 Stmt *Body = FD->getBody(Definition);
Richard Smith83587db2012-02-15 02:18:13 +00002696 CCValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002697
Richard Smithc1c5f272011-12-13 06:39:58 +00002698 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002699 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2700 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002701 return false;
2702
Richard Smith83587db2012-02-15 02:18:13 +00002703 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002704 }
2705
Richard Smithc49bd112011-10-28 17:51:58 +00002706 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2707 return StmtVisitorTy::Visit(E->getInitializer());
2708 }
Richard Smithf10d9172011-10-11 21:43:33 +00002709 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002710 if (E->getNumInits() == 0)
2711 return DerivedZeroInitialization(E);
2712 if (E->getNumInits() == 1)
2713 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002714 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002715 }
2716 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002717 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002718 }
2719 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002720 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002721 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002722 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002723 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002724 }
Richard Smithf10d9172011-10-11 21:43:33 +00002725
Richard Smith180f4792011-11-10 06:34:14 +00002726 /// A member expression where the object is a prvalue is itself a prvalue.
2727 RetTy VisitMemberExpr(const MemberExpr *E) {
2728 assert(!E->isArrow() && "missing call to bound member function?");
2729
2730 CCValue Val;
2731 if (!Evaluate(Val, Info, E->getBase()))
2732 return false;
2733
2734 QualType BaseTy = E->getBase()->getType();
2735
2736 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002737 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002738 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2739 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2740 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2741
Richard Smithb4e85ed2012-01-06 16:39:00 +00002742 SubobjectDesignator Designator(BaseTy);
2743 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002744
Richard Smithf48fdb02011-12-09 22:58:01 +00002745 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002746 DerivedSuccess(Val, E);
2747 }
2748
Richard Smithc49bd112011-10-28 17:51:58 +00002749 RetTy VisitCastExpr(const CastExpr *E) {
2750 switch (E->getCastKind()) {
2751 default:
2752 break;
2753
David Chisnall7a7ee302012-01-16 17:27:18 +00002754 case CK_AtomicToNonAtomic:
2755 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002756 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002757 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002758 return StmtVisitorTy::Visit(E->getSubExpr());
2759
2760 case CK_LValueToRValue: {
2761 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002762 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2763 return false;
2764 CCValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002765 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2766 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2767 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002768 return false;
2769 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002770 }
2771 }
2772
Richard Smithf48fdb02011-12-09 22:58:01 +00002773 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002774 }
2775
Richard Smith8327fad2011-10-24 18:44:57 +00002776 /// Visit a value which is evaluated, but whose value is ignored.
2777 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002778 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002779 if (!Evaluate(Scratch, Info, E))
2780 Info.EvalStatus.HasSideEffects = true;
2781 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002782};
2783
2784}
2785
2786//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002787// Common base class for lvalue and temporary evaluation.
2788//===----------------------------------------------------------------------===//
2789namespace {
2790template<class Derived>
2791class LValueExprEvaluatorBase
2792 : public ExprEvaluatorBase<Derived, bool> {
2793protected:
2794 LValue &Result;
2795 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2796 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2797
2798 bool Success(APValue::LValueBase B) {
2799 Result.set(B);
2800 return true;
2801 }
2802
2803public:
2804 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2805 ExprEvaluatorBaseTy(Info), Result(Result) {}
2806
2807 bool Success(const CCValue &V, const Expr *E) {
2808 Result.setFrom(V);
2809 return true;
2810 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002811
Richard Smithe24f5fc2011-11-17 22:56:20 +00002812 bool VisitMemberExpr(const MemberExpr *E) {
2813 // Handle non-static data members.
2814 QualType BaseTy;
2815 if (E->isArrow()) {
2816 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2817 return false;
2818 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002819 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002820 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002821 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2822 return false;
2823 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002824 } else {
2825 if (!this->Visit(E->getBase()))
2826 return false;
2827 BaseTy = E->getBase()->getType();
2828 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002829
Richard Smithd9b02e72012-01-25 22:15:11 +00002830 const ValueDecl *MD = E->getMemberDecl();
2831 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2832 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2833 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2834 (void)BaseTy;
2835 HandleLValueMember(this->Info, E, Result, FD);
2836 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2837 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2838 } else
2839 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002840
Richard Smithd9b02e72012-01-25 22:15:11 +00002841 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002842 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002843 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002844 RefValue))
2845 return false;
2846 return Success(RefValue, E);
2847 }
2848 return true;
2849 }
2850
2851 bool VisitBinaryOperator(const BinaryOperator *E) {
2852 switch (E->getOpcode()) {
2853 default:
2854 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2855
2856 case BO_PtrMemD:
2857 case BO_PtrMemI:
2858 return HandleMemberPointerAccess(this->Info, E, Result);
2859 }
2860 }
2861
2862 bool VisitCastExpr(const CastExpr *E) {
2863 switch (E->getCastKind()) {
2864 default:
2865 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2866
2867 case CK_DerivedToBase:
2868 case CK_UncheckedDerivedToBase: {
2869 if (!this->Visit(E->getSubExpr()))
2870 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002871
2872 // Now figure out the necessary offset to add to the base LV to get from
2873 // the derived class to the base class.
2874 QualType Type = E->getSubExpr()->getType();
2875
2876 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2877 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002878 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002879 *PathI))
2880 return false;
2881 Type = (*PathI)->getType();
2882 }
2883
2884 return true;
2885 }
2886 }
2887 }
2888};
2889}
2890
2891//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002892// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002893//
2894// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2895// function designators (in C), decl references to void objects (in C), and
2896// temporaries (if building with -Wno-address-of-temporary).
2897//
2898// LValue evaluation produces values comprising a base expression of one of the
2899// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002900// - Declarations
2901// * VarDecl
2902// * FunctionDecl
2903// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002904// * CompoundLiteralExpr in C
2905// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002906// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002907// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002908// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002909// * ObjCEncodeExpr
2910// * AddrLabelExpr
2911// * BlockExpr
2912// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002913// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002914// * Any Expr, with a CallIndex indicating the function in which the temporary
2915// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002916// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002917//===----------------------------------------------------------------------===//
2918namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002919class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002920 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002921public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002922 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2923 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002924
Richard Smithc49bd112011-10-28 17:51:58 +00002925 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2926
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002927 bool VisitDeclRefExpr(const DeclRefExpr *E);
2928 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002929 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002930 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2931 bool VisitMemberExpr(const MemberExpr *E);
2932 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2933 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002934 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002935 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2936 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002937 bool VisitUnaryReal(const UnaryOperator *E);
2938 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002939
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002940 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002941 switch (E->getCastKind()) {
2942 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002943 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002944
Eli Friedmandb924222011-10-11 00:13:24 +00002945 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002946 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002947 if (!Visit(E->getSubExpr()))
2948 return false;
2949 Result.Designator.setInvalid();
2950 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002951
Richard Smithe24f5fc2011-11-17 22:56:20 +00002952 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002953 if (!Visit(E->getSubExpr()))
2954 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002955 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002956 }
2957 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002958};
2959} // end anonymous namespace
2960
Richard Smithc49bd112011-10-28 17:51:58 +00002961/// Evaluate an expression as an lvalue. This can be legitimately called on
2962/// expressions which are not glvalues, in a few cases:
2963/// * function designators in C,
2964/// * "extern void" objects,
2965/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002966static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002967 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2968 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2969 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002970 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002971}
2972
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002973bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002974 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2975 return Success(FD);
2976 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002977 return VisitVarDecl(E, VD);
2978 return Error(E);
2979}
Richard Smith436c8892011-10-24 23:14:33 +00002980
Richard Smithc49bd112011-10-28 17:51:58 +00002981bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002982 if (!VD->getType()->isReferenceType()) {
2983 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002984 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002985 return true;
2986 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002987 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002988 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002989
Richard Smith47a1eed2011-10-29 20:57:55 +00002990 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002991 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2992 return false;
2993 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002994}
2995
Richard Smithbd552ef2011-10-31 05:52:43 +00002996bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2997 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002998 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002999 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00003000 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
3001
Richard Smith83587db2012-02-15 02:18:13 +00003002 Result.set(E, Info.CurrentCall->Index);
3003 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3004 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003005 }
3006
3007 // Materialization of an lvalue temporary occurs when we need to force a copy
3008 // (for instance, if it's a bitfield).
3009 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
3010 if (!Visit(E->GetTemporaryExpr()))
3011 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003012 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003013 Info.CurrentCall->Temporaries[E]))
3014 return false;
Richard Smith83587db2012-02-15 02:18:13 +00003015 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003016 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00003017}
3018
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003019bool
3020LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003021 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3022 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3023 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00003024 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003025}
3026
Richard Smith47d21452011-12-27 12:18:28 +00003027bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
3028 if (E->isTypeOperand())
3029 return Success(E);
3030 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
3031 if (RD && RD->isPolymorphic()) {
3032 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
3033 << E->getExprOperand()->getType()
3034 << E->getExprOperand()->getSourceRange();
3035 return false;
3036 }
3037 return Success(E);
3038}
3039
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003040bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003041 // Handle static data members.
3042 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3043 VisitIgnoredValue(E->getBase());
3044 return VisitVarDecl(E, VD);
3045 }
3046
Richard Smithd0dccea2011-10-28 22:34:42 +00003047 // Handle static member functions.
3048 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3049 if (MD->isStatic()) {
3050 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003051 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00003052 }
3053 }
3054
Richard Smith180f4792011-11-10 06:34:14 +00003055 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00003056 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003057}
3058
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003059bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003060 // FIXME: Deal with vectors as array subscript bases.
3061 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003062 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003063
Anders Carlsson3068d112008-11-16 19:01:22 +00003064 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003065 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003066
Anders Carlsson3068d112008-11-16 19:01:22 +00003067 APSInt Index;
3068 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003069 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003070 int64_t IndexValue
3071 = Index.isSigned() ? Index.getSExtValue()
3072 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003073
Richard Smithb4e85ed2012-01-06 16:39:00 +00003074 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003075}
Eli Friedman4efaa272008-11-12 09:44:48 +00003076
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003077bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003078 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003079}
3080
Richard Smith86024012012-02-18 22:04:06 +00003081bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3082 if (!Visit(E->getSubExpr()))
3083 return false;
3084 // __real is a no-op on scalar lvalues.
3085 if (E->getSubExpr()->getType()->isAnyComplexType())
3086 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3087 return true;
3088}
3089
3090bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3091 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3092 "lvalue __imag__ on scalar?");
3093 if (!Visit(E->getSubExpr()))
3094 return false;
3095 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3096 return true;
3097}
3098
Eli Friedman4efaa272008-11-12 09:44:48 +00003099//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003100// Pointer Evaluation
3101//===----------------------------------------------------------------------===//
3102
Anders Carlssonc754aa62008-07-08 05:13:58 +00003103namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003104class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003105 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003106 LValue &Result;
3107
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003108 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003109 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003110 return true;
3111 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003112public:
Mike Stump1eb44332009-09-09 15:08:12 +00003113
John McCallefdb83e2010-05-07 21:00:08 +00003114 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003115 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003116
Richard Smith47a1eed2011-10-29 20:57:55 +00003117 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003118 Result.setFrom(V);
3119 return true;
3120 }
Richard Smith51201882011-12-30 21:15:51 +00003121 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003122 return Success((Expr*)0);
3123 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003124
John McCallefdb83e2010-05-07 21:00:08 +00003125 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003126 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003127 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003128 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003129 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003130 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003131 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003132 bool VisitCallExpr(const CallExpr *E);
3133 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003134 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003135 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003136 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003137 }
Richard Smith180f4792011-11-10 06:34:14 +00003138 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3139 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003140 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003141 Result = *Info.CurrentCall->This;
3142 return true;
3143 }
John McCall56ca35d2011-02-17 10:25:35 +00003144
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003145 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003146};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003147} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003148
John McCallefdb83e2010-05-07 21:00:08 +00003149static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003150 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003151 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003152}
3153
John McCallefdb83e2010-05-07 21:00:08 +00003154bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003155 if (E->getOpcode() != BO_Add &&
3156 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003157 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003158
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003159 const Expr *PExp = E->getLHS();
3160 const Expr *IExp = E->getRHS();
3161 if (IExp->getType()->isPointerType())
3162 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003163
Richard Smith745f5142012-01-27 01:14:48 +00003164 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3165 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003166 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003167
John McCallefdb83e2010-05-07 21:00:08 +00003168 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003169 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003170 return false;
3171 int64_t AdditionalOffset
3172 = Offset.isSigned() ? Offset.getSExtValue()
3173 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003174 if (E->getOpcode() == BO_Sub)
3175 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003176
Richard Smith180f4792011-11-10 06:34:14 +00003177 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003178 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3179 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003180}
Eli Friedman4efaa272008-11-12 09:44:48 +00003181
John McCallefdb83e2010-05-07 21:00:08 +00003182bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3183 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003184}
Mike Stump1eb44332009-09-09 15:08:12 +00003185
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003186bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3187 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003188
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003189 switch (E->getCastKind()) {
3190 default:
3191 break;
3192
John McCall2de56d12010-08-25 11:45:40 +00003193 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003194 case CK_CPointerToObjCPointerCast:
3195 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003196 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003197 if (!Visit(SubExpr))
3198 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003199 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3200 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3201 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003202 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003203 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003204 if (SubExpr->getType()->isVoidPointerType())
3205 CCEDiag(E, diag::note_constexpr_invalid_cast)
3206 << 3 << SubExpr->getType();
3207 else
3208 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3209 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003210 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003211
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003212 case CK_DerivedToBase:
3213 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003214 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003215 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003216 if (!Result.Base && Result.Offset.isZero())
3217 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003218
Richard Smith180f4792011-11-10 06:34:14 +00003219 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003220 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003221 QualType Type =
3222 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003223
Richard Smith180f4792011-11-10 06:34:14 +00003224 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003225 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003226 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3227 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003228 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003229 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003230 }
3231
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003232 return true;
3233 }
3234
Richard Smithe24f5fc2011-11-17 22:56:20 +00003235 case CK_BaseToDerived:
3236 if (!Visit(E->getSubExpr()))
3237 return false;
3238 if (!Result.Base && Result.Offset.isZero())
3239 return true;
3240 return HandleBaseToDerivedCast(Info, E, Result);
3241
Richard Smith47a1eed2011-10-29 20:57:55 +00003242 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003243 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003244
John McCall2de56d12010-08-25 11:45:40 +00003245 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003246 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3247
Richard Smith47a1eed2011-10-29 20:57:55 +00003248 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003249 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003250 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003251
John McCallefdb83e2010-05-07 21:00:08 +00003252 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003253 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3254 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003255 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003256 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003257 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003258 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003259 return true;
3260 } else {
3261 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00003262 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00003263 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003264 }
3265 }
John McCall2de56d12010-08-25 11:45:40 +00003266 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003267 if (SubExpr->isGLValue()) {
3268 if (!EvaluateLValue(SubExpr, Result, Info))
3269 return false;
3270 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003271 Result.set(SubExpr, Info.CurrentCall->Index);
3272 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3273 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003274 return false;
3275 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003276 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003277 if (const ConstantArrayType *CAT
3278 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3279 Result.addArray(Info, E, CAT);
3280 else
3281 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003282 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003283
John McCall2de56d12010-08-25 11:45:40 +00003284 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003285 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003286 }
3287
Richard Smithc49bd112011-10-28 17:51:58 +00003288 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003289}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003290
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003291bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003292 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003293 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003294
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003295 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003296}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003297
3298//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003299// Member Pointer Evaluation
3300//===----------------------------------------------------------------------===//
3301
3302namespace {
3303class MemberPointerExprEvaluator
3304 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3305 MemberPtr &Result;
3306
3307 bool Success(const ValueDecl *D) {
3308 Result = MemberPtr(D);
3309 return true;
3310 }
3311public:
3312
3313 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3314 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3315
3316 bool Success(const CCValue &V, const Expr *E) {
3317 Result.setFrom(V);
3318 return true;
3319 }
Richard Smith51201882011-12-30 21:15:51 +00003320 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003321 return Success((const ValueDecl*)0);
3322 }
3323
3324 bool VisitCastExpr(const CastExpr *E);
3325 bool VisitUnaryAddrOf(const UnaryOperator *E);
3326};
3327} // end anonymous namespace
3328
3329static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3330 EvalInfo &Info) {
3331 assert(E->isRValue() && E->getType()->isMemberPointerType());
3332 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3333}
3334
3335bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3336 switch (E->getCastKind()) {
3337 default:
3338 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3339
3340 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003341 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003342
3343 case CK_BaseToDerivedMemberPointer: {
3344 if (!Visit(E->getSubExpr()))
3345 return false;
3346 if (E->path_empty())
3347 return true;
3348 // Base-to-derived member pointer casts store the path in derived-to-base
3349 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3350 // the wrong end of the derived->base arc, so stagger the path by one class.
3351 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3352 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3353 PathI != PathE; ++PathI) {
3354 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3355 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3356 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003357 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003358 }
3359 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3360 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003361 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003362 return true;
3363 }
3364
3365 case CK_DerivedToBaseMemberPointer:
3366 if (!Visit(E->getSubExpr()))
3367 return false;
3368 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3369 PathE = E->path_end(); PathI != PathE; ++PathI) {
3370 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3371 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3372 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003373 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003374 }
3375 return true;
3376 }
3377}
3378
3379bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3380 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3381 // member can be formed.
3382 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3383}
3384
3385//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003386// Record Evaluation
3387//===----------------------------------------------------------------------===//
3388
3389namespace {
3390 class RecordExprEvaluator
3391 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3392 const LValue &This;
3393 APValue &Result;
3394 public:
3395
3396 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3397 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3398
3399 bool Success(const CCValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003400 Result = V;
3401 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003402 }
Richard Smith51201882011-12-30 21:15:51 +00003403 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003404
Richard Smith59efe262011-11-11 04:05:33 +00003405 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003406 bool VisitInitListExpr(const InitListExpr *E);
3407 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3408 };
3409}
3410
Richard Smith51201882011-12-30 21:15:51 +00003411/// Perform zero-initialization on an object of non-union class type.
3412/// C++11 [dcl.init]p5:
3413/// To zero-initialize an object or reference of type T means:
3414/// [...]
3415/// -- if T is a (possibly cv-qualified) non-union class type,
3416/// each non-static data member and each base-class subobject is
3417/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003418static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3419 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003420 const LValue &This, APValue &Result) {
3421 assert(!RD->isUnion() && "Expected non-union class type");
3422 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3423 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3424 std::distance(RD->field_begin(), RD->field_end()));
3425
3426 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3427
3428 if (CD) {
3429 unsigned Index = 0;
3430 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003431 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003432 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3433 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003434 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3435 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003436 Result.getStructBase(Index)))
3437 return false;
3438 }
3439 }
3440
Richard Smithb4e85ed2012-01-06 16:39:00 +00003441 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3442 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003443 // -- if T is a reference type, no initialization is performed.
3444 if ((*I)->getType()->isReferenceType())
3445 continue;
3446
3447 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003448 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003449
3450 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003451 if (!EvaluateInPlace(
Richard Smith51201882011-12-30 21:15:51 +00003452 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3453 return false;
3454 }
3455
3456 return true;
3457}
3458
3459bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3460 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3461 if (RD->isUnion()) {
3462 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3463 // object's first non-static named data member is zero-initialized
3464 RecordDecl::field_iterator I = RD->field_begin();
3465 if (I == RD->field_end()) {
3466 Result = APValue((const FieldDecl*)0);
3467 return true;
3468 }
3469
3470 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003471 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003472 Result = APValue(*I);
3473 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003474 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003475 }
3476
Richard Smithce582fe2012-02-17 00:44:16 +00003477 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
3478 Info.Diag(E->getExprLoc(), diag::note_constexpr_virtual_base) << RD;
3479 return false;
3480 }
3481
Richard Smithb4e85ed2012-01-06 16:39:00 +00003482 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003483}
3484
Richard Smith59efe262011-11-11 04:05:33 +00003485bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3486 switch (E->getCastKind()) {
3487 default:
3488 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3489
3490 case CK_ConstructorConversion:
3491 return Visit(E->getSubExpr());
3492
3493 case CK_DerivedToBase:
3494 case CK_UncheckedDerivedToBase: {
3495 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003496 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003497 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003498 if (!DerivedObject.isStruct())
3499 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003500
3501 // Derived-to-base rvalue conversion: just slice off the derived part.
3502 APValue *Value = &DerivedObject;
3503 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3504 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3505 PathE = E->path_end(); PathI != PathE; ++PathI) {
3506 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3507 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3508 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3509 RD = Base;
3510 }
3511 Result = *Value;
3512 return true;
3513 }
3514 }
3515}
3516
Richard Smith180f4792011-11-10 06:34:14 +00003517bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003518 // Cannot constant-evaluate std::initializer_list inits.
3519 if (E->initializesStdInitializerList())
3520 return false;
3521
Richard Smith180f4792011-11-10 06:34:14 +00003522 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3523 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3524
3525 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003526 const FieldDecl *Field = E->getInitializedFieldInUnion();
3527 Result = APValue(Field);
3528 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003529 return true;
Richard Smithec789162012-01-12 18:54:33 +00003530
3531 // If the initializer list for a union does not contain any elements, the
3532 // first element of the union is value-initialized.
3533 ImplicitValueInitExpr VIE(Field->getType());
3534 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3535
Richard Smith180f4792011-11-10 06:34:14 +00003536 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003537 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith83587db2012-02-15 02:18:13 +00003538 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003539 }
3540
3541 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3542 "initializer list for class with base classes");
3543 Result = APValue(APValue::UninitStruct(), 0,
3544 std::distance(RD->field_begin(), RD->field_end()));
3545 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003546 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003547 for (RecordDecl::field_iterator Field = RD->field_begin(),
3548 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3549 // Anonymous bit-fields are not considered members of the class for
3550 // purposes of aggregate initialization.
3551 if (Field->isUnnamedBitfield())
3552 continue;
3553
3554 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003555
Richard Smith745f5142012-01-27 01:14:48 +00003556 bool HaveInit = ElementNo < E->getNumInits();
3557
3558 // FIXME: Diagnostics here should point to the end of the initializer
3559 // list, not the start.
3560 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3561 *Field, &Layout);
3562
3563 // Perform an implicit value-initialization for members beyond the end of
3564 // the initializer list.
3565 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3566
Richard Smith83587db2012-02-15 02:18:13 +00003567 if (!EvaluateInPlace(
Richard Smith745f5142012-01-27 01:14:48 +00003568 Result.getStructField((*Field)->getFieldIndex()),
3569 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3570 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003571 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003572 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003573 }
3574 }
3575
Richard Smith745f5142012-01-27 01:14:48 +00003576 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003577}
3578
3579bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3580 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003581 bool ZeroInit = E->requiresZeroInitialization();
3582 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003583 // If we've already performed zero-initialization, we're already done.
3584 if (!Result.isUninit())
3585 return true;
3586
Richard Smith51201882011-12-30 21:15:51 +00003587 if (ZeroInit)
3588 return ZeroInitialization(E);
3589
Richard Smith61802452011-12-22 02:22:31 +00003590 const CXXRecordDecl *RD = FD->getParent();
3591 if (RD->isUnion())
3592 Result = APValue((FieldDecl*)0);
3593 else
3594 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3595 std::distance(RD->field_begin(), RD->field_end()));
3596 return true;
3597 }
3598
Richard Smith180f4792011-11-10 06:34:14 +00003599 const FunctionDecl *Definition = 0;
3600 FD->getBody(Definition);
3601
Richard Smithc1c5f272011-12-13 06:39:58 +00003602 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3603 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003604
Richard Smith610a60c2012-01-10 04:32:03 +00003605 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003606 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003607 if (const MaterializeTemporaryExpr *ME
3608 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3609 return Visit(ME->GetTemporaryExpr());
3610
Richard Smith51201882011-12-30 21:15:51 +00003611 if (ZeroInit && !ZeroInitialization(E))
3612 return false;
3613
Richard Smith180f4792011-11-10 06:34:14 +00003614 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003615 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003616 cast<CXXConstructorDecl>(Definition), Info,
3617 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003618}
3619
3620static bool EvaluateRecord(const Expr *E, const LValue &This,
3621 APValue &Result, EvalInfo &Info) {
3622 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003623 "can't evaluate expression as a record rvalue");
3624 return RecordExprEvaluator(Info, This, Result).Visit(E);
3625}
3626
3627//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003628// Temporary Evaluation
3629//
3630// Temporaries are represented in the AST as rvalues, but generally behave like
3631// lvalues. The full-object of which the temporary is a subobject is implicitly
3632// materialized so that a reference can bind to it.
3633//===----------------------------------------------------------------------===//
3634namespace {
3635class TemporaryExprEvaluator
3636 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3637public:
3638 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3639 LValueExprEvaluatorBaseTy(Info, Result) {}
3640
3641 /// Visit an expression which constructs the value of this temporary.
3642 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003643 Result.set(E, Info.CurrentCall->Index);
3644 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003645 }
3646
3647 bool VisitCastExpr(const CastExpr *E) {
3648 switch (E->getCastKind()) {
3649 default:
3650 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3651
3652 case CK_ConstructorConversion:
3653 return VisitConstructExpr(E->getSubExpr());
3654 }
3655 }
3656 bool VisitInitListExpr(const InitListExpr *E) {
3657 return VisitConstructExpr(E);
3658 }
3659 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3660 return VisitConstructExpr(E);
3661 }
3662 bool VisitCallExpr(const CallExpr *E) {
3663 return VisitConstructExpr(E);
3664 }
3665};
3666} // end anonymous namespace
3667
3668/// Evaluate an expression of record type as a temporary.
3669static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003670 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003671 return TemporaryExprEvaluator(Info, Result).Visit(E);
3672}
3673
3674//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003675// Vector Evaluation
3676//===----------------------------------------------------------------------===//
3677
3678namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003679 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003680 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3681 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003682 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003683
Richard Smith07fc6572011-10-22 21:10:00 +00003684 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3685 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003686
Richard Smith07fc6572011-10-22 21:10:00 +00003687 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3688 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3689 // FIXME: remove this APValue copy.
3690 Result = APValue(V.data(), V.size());
3691 return true;
3692 }
Richard Smith69c2c502011-11-04 05:33:44 +00003693 bool Success(const CCValue &V, const Expr *E) {
3694 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003695 Result = V;
3696 return true;
3697 }
Richard Smith51201882011-12-30 21:15:51 +00003698 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003699
Richard Smith07fc6572011-10-22 21:10:00 +00003700 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003701 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003702 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003703 bool VisitInitListExpr(const InitListExpr *E);
3704 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003705 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003706 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003707 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003708 };
3709} // end anonymous namespace
3710
3711static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003712 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003713 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003714}
3715
Richard Smith07fc6572011-10-22 21:10:00 +00003716bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3717 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003718 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003719
Richard Smithd62ca372011-12-06 22:44:34 +00003720 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003721 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003722
Eli Friedman46a52322011-03-25 00:43:55 +00003723 switch (E->getCastKind()) {
3724 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003725 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003726 if (SETy->isIntegerType()) {
3727 APSInt IntResult;
3728 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003729 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003730 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003731 } else if (SETy->isRealFloatingType()) {
3732 APFloat F(0.0);
3733 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003734 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003735 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003736 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003737 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003738 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003739
3740 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003741 SmallVector<APValue, 4> Elts(NElts, Val);
3742 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003743 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003744 case CK_BitCast: {
3745 // Evaluate the operand into an APInt we can extract from.
3746 llvm::APInt SValInt;
3747 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3748 return false;
3749 // Extract the elements
3750 QualType EltTy = VTy->getElementType();
3751 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3752 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3753 SmallVector<APValue, 4> Elts;
3754 if (EltTy->isRealFloatingType()) {
3755 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3756 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3757 unsigned FloatEltSize = EltSize;
3758 if (&Sem == &APFloat::x87DoubleExtended)
3759 FloatEltSize = 80;
3760 for (unsigned i = 0; i < NElts; i++) {
3761 llvm::APInt Elt;
3762 if (BigEndian)
3763 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3764 else
3765 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3766 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3767 }
3768 } else if (EltTy->isIntegerType()) {
3769 for (unsigned i = 0; i < NElts; i++) {
3770 llvm::APInt Elt;
3771 if (BigEndian)
3772 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3773 else
3774 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3775 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3776 }
3777 } else {
3778 return Error(E);
3779 }
3780 return Success(Elts, E);
3781 }
Eli Friedman46a52322011-03-25 00:43:55 +00003782 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003783 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003784 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003785}
3786
Richard Smith07fc6572011-10-22 21:10:00 +00003787bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003788VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003789 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003790 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003791 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003792
Nate Begeman59b5da62009-01-18 03:20:47 +00003793 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003794 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003795
Eli Friedman3edd5a92012-01-03 23:24:20 +00003796 // The number of initializers can be less than the number of
3797 // vector elements. For OpenCL, this can be due to nested vector
3798 // initialization. For GCC compatibility, missing trailing elements
3799 // should be initialized with zeroes.
3800 unsigned CountInits = 0, CountElts = 0;
3801 while (CountElts < NumElements) {
3802 // Handle nested vector initialization.
3803 if (CountInits < NumInits
3804 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3805 APValue v;
3806 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3807 return Error(E);
3808 unsigned vlen = v.getVectorLength();
3809 for (unsigned j = 0; j < vlen; j++)
3810 Elements.push_back(v.getVectorElt(j));
3811 CountElts += vlen;
3812 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003813 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003814 if (CountInits < NumInits) {
3815 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3816 return Error(E);
3817 } else // trailing integer zero.
3818 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3819 Elements.push_back(APValue(sInt));
3820 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003821 } else {
3822 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003823 if (CountInits < NumInits) {
3824 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3825 return Error(E);
3826 } else // trailing float zero.
3827 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3828 Elements.push_back(APValue(f));
3829 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003830 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003831 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003832 }
Richard Smith07fc6572011-10-22 21:10:00 +00003833 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003834}
3835
Richard Smith07fc6572011-10-22 21:10:00 +00003836bool
Richard Smith51201882011-12-30 21:15:51 +00003837VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003838 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003839 QualType EltTy = VT->getElementType();
3840 APValue ZeroElement;
3841 if (EltTy->isIntegerType())
3842 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3843 else
3844 ZeroElement =
3845 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3846
Chris Lattner5f9e2722011-07-23 10:55:15 +00003847 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003848 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003849}
3850
Richard Smith07fc6572011-10-22 21:10:00 +00003851bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003852 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003853 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003854}
3855
Nate Begeman59b5da62009-01-18 03:20:47 +00003856//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003857// Array Evaluation
3858//===----------------------------------------------------------------------===//
3859
3860namespace {
3861 class ArrayExprEvaluator
3862 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003863 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003864 APValue &Result;
3865 public:
3866
Richard Smith180f4792011-11-10 06:34:14 +00003867 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3868 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003869
3870 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003871 assert((V.isArray() || V.isLValue()) &&
3872 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003873 Result = V;
3874 return true;
3875 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003876
Richard Smith51201882011-12-30 21:15:51 +00003877 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003878 const ConstantArrayType *CAT =
3879 Info.Ctx.getAsConstantArrayType(E->getType());
3880 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003881 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003882
3883 Result = APValue(APValue::UninitArray(), 0,
3884 CAT->getSize().getZExtValue());
3885 if (!Result.hasArrayFiller()) return true;
3886
Richard Smith51201882011-12-30 21:15:51 +00003887 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003888 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003889 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003890 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003891 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003892 }
3893
Richard Smithcc5d4f62011-11-07 09:22:26 +00003894 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003895 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003896 };
3897} // end anonymous namespace
3898
Richard Smith180f4792011-11-10 06:34:14 +00003899static bool EvaluateArray(const Expr *E, const LValue &This,
3900 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003901 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003902 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003903}
3904
3905bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3906 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3907 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003908 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003909
Richard Smith974c5f92011-12-22 01:07:19 +00003910 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3911 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003912 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003913 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3914 LValue LV;
3915 if (!EvaluateLValue(E->getInit(0), LV, Info))
3916 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00003917 CCValue Val;
3918 LV.moveInto(Val);
3919 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003920 }
3921
Richard Smith745f5142012-01-27 01:14:48 +00003922 bool Success = true;
3923
Richard Smithcc5d4f62011-11-07 09:22:26 +00003924 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3925 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003926 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003927 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003928 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003929 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003930 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003931 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3932 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003933 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3934 CAT->getElementType(), 1)) {
3935 if (!Info.keepEvaluatingAfterFailure())
3936 return false;
3937 Success = false;
3938 }
Richard Smith180f4792011-11-10 06:34:14 +00003939 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003940
Richard Smith745f5142012-01-27 01:14:48 +00003941 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003942 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003943 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3944 // but sometimes does:
3945 // struct S { constexpr S() : p(&p) {} void *p; };
3946 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003947 return EvaluateInPlace(Result.getArrayFiller(), Info,
3948 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003949}
3950
Richard Smithe24f5fc2011-11-17 22:56:20 +00003951bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3952 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3953 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003954 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003955
Richard Smithec789162012-01-12 18:54:33 +00003956 bool HadZeroInit = !Result.isUninit();
3957 if (!HadZeroInit)
3958 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003959 if (!Result.hasArrayFiller())
3960 return true;
3961
3962 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003963
Richard Smith51201882011-12-30 21:15:51 +00003964 bool ZeroInit = E->requiresZeroInitialization();
3965 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003966 if (HadZeroInit)
3967 return true;
3968
Richard Smith51201882011-12-30 21:15:51 +00003969 if (ZeroInit) {
3970 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003971 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003972 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003973 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003974 }
3975
Richard Smith61802452011-12-22 02:22:31 +00003976 const CXXRecordDecl *RD = FD->getParent();
3977 if (RD->isUnion())
3978 Result.getArrayFiller() = APValue((FieldDecl*)0);
3979 else
3980 Result.getArrayFiller() =
3981 APValue(APValue::UninitStruct(), RD->getNumBases(),
3982 std::distance(RD->field_begin(), RD->field_end()));
3983 return true;
3984 }
3985
Richard Smithe24f5fc2011-11-17 22:56:20 +00003986 const FunctionDecl *Definition = 0;
3987 FD->getBody(Definition);
3988
Richard Smithc1c5f272011-12-13 06:39:58 +00003989 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3990 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003991
3992 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3993 // but sometimes does:
3994 // struct S { constexpr S() : p(&p) {} void *p; };
3995 // S s[10];
3996 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003997 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003998
Richard Smithec789162012-01-12 18:54:33 +00003999 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00004000 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00004001 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00004002 return false;
4003 }
4004
Richard Smithe24f5fc2011-11-17 22:56:20 +00004005 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00004006 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00004007 cast<CXXConstructorDecl>(Definition),
4008 Info, Result.getArrayFiller());
4009}
4010
Richard Smithcc5d4f62011-11-07 09:22:26 +00004011//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004012// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00004013//
4014// As a GNU extension, we support casting pointers to sufficiently-wide integer
4015// types and back in constant folding. Integer values are thus represented
4016// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004017//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004018
4019namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004020class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004021 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00004022 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00004023public:
Richard Smith47a1eed2011-10-29 20:57:55 +00004024 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004025 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004026
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004027 bool Success(const llvm::APSInt &SI, const Expr *E) {
4028 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004029 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004030 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004031 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004032 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004033 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00004034 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004035 return true;
4036 }
4037
Daniel Dunbar131eb432009-02-19 09:06:44 +00004038 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004039 assert(E->getType()->isIntegralOrEnumerationType() &&
4040 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004041 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004042 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00004043 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00004044 Result.getInt().setIsUnsigned(
4045 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00004046 return true;
4047 }
4048
4049 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004050 assert(E->getType()->isIntegralOrEnumerationType() &&
4051 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00004052 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00004053 return true;
4054 }
4055
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004056 bool Success(CharUnits Size, const Expr *E) {
4057 return Success(Size.getQuantity(), E);
4058 }
4059
Richard Smith47a1eed2011-10-29 20:57:55 +00004060 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00004061 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00004062 Result = V;
4063 return true;
4064 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004065 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00004066 }
Mike Stump1eb44332009-09-09 15:08:12 +00004067
Richard Smith51201882011-12-30 21:15:51 +00004068 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00004069
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004070 //===--------------------------------------------------------------------===//
4071 // Visitor Methods
4072 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004073
Chris Lattner4c4867e2008-07-12 00:38:25 +00004074 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004075 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004076 }
4077 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004078 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004079 }
Eli Friedman04309752009-11-24 05:28:59 +00004080
4081 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4082 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004083 if (CheckReferencedDecl(E, E->getDecl()))
4084 return true;
4085
4086 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004087 }
4088 bool VisitMemberExpr(const MemberExpr *E) {
4089 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004090 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004091 return true;
4092 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004093
4094 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004095 }
4096
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004097 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004098 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004099 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004100 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004101
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004102 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004103 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004104
Anders Carlsson3068d112008-11-16 19:01:22 +00004105 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004106 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004107 }
Mike Stump1eb44332009-09-09 15:08:12 +00004108
Richard Smithf10d9172011-10-11 21:43:33 +00004109 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004110 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004111 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004112 }
4113
Sebastian Redl64b45f72009-01-05 20:52:13 +00004114 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004115 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004116 }
4117
Francois Pichet6ad6f282010-12-07 00:08:36 +00004118 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4119 return Success(E->getValue(), E);
4120 }
4121
John Wiegley21ff2e52011-04-28 00:16:57 +00004122 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4123 return Success(E->getValue(), E);
4124 }
4125
John Wiegley55262202011-04-25 06:54:41 +00004126 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4127 return Success(E->getValue(), E);
4128 }
4129
Eli Friedman722c7172009-02-28 03:59:05 +00004130 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004131 bool VisitUnaryImag(const UnaryOperator *E);
4132
Sebastian Redl295995c2010-09-10 20:55:47 +00004133 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004134 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004135
Chris Lattnerfcee0012008-07-11 21:24:13 +00004136private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004137 CharUnits GetAlignOfExpr(const Expr *E);
4138 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004139 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004140 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004141 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004142};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004143} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004144
Richard Smithc49bd112011-10-28 17:51:58 +00004145/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4146/// produce either the integer value or a pointer.
4147///
4148/// GCC has a heinous extension which folds casts between pointer types and
4149/// pointer-sized integral types. We support this by allowing the evaluation of
4150/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4151/// Some simple arithmetic on such values is supported (they are treated much
4152/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00004153static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004154 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004155 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004156 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004157}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004158
Richard Smithf48fdb02011-12-09 22:58:01 +00004159static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004160 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004161 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004162 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004163 if (!Val.isInt()) {
4164 // FIXME: It would be better to produce the diagnostic for casting
4165 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00004166 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004167 return false;
4168 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004169 Result = Val.getInt();
4170 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004171}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004172
Richard Smithf48fdb02011-12-09 22:58:01 +00004173/// Check whether the given declaration can be directly converted to an integral
4174/// rvalue. If not, no diagnostic is produced; there are other things we can
4175/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004176bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004177 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004178 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004179 // Check for signedness/width mismatches between E type and ECD value.
4180 bool SameSign = (ECD->getInitVal().isSigned()
4181 == E->getType()->isSignedIntegerOrEnumerationType());
4182 bool SameWidth = (ECD->getInitVal().getBitWidth()
4183 == Info.Ctx.getIntWidth(E->getType()));
4184 if (SameSign && SameWidth)
4185 return Success(ECD->getInitVal(), E);
4186 else {
4187 // Get rid of mismatch (otherwise Success assertions will fail)
4188 // by computing a new value matching the type of E.
4189 llvm::APSInt Val = ECD->getInitVal();
4190 if (!SameSign)
4191 Val.setIsSigned(!ECD->getInitVal().isSigned());
4192 if (!SameWidth)
4193 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4194 return Success(Val, E);
4195 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004196 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004197 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004198}
4199
Chris Lattnera4d55d82008-10-06 06:40:35 +00004200/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4201/// as GCC.
4202static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4203 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004204 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004205 enum gcc_type_class {
4206 no_type_class = -1,
4207 void_type_class, integer_type_class, char_type_class,
4208 enumeral_type_class, boolean_type_class,
4209 pointer_type_class, reference_type_class, offset_type_class,
4210 real_type_class, complex_type_class,
4211 function_type_class, method_type_class,
4212 record_type_class, union_type_class,
4213 array_type_class, string_type_class,
4214 lang_type_class
4215 };
Mike Stump1eb44332009-09-09 15:08:12 +00004216
4217 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004218 // ideal, however it is what gcc does.
4219 if (E->getNumArgs() == 0)
4220 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004221
Chris Lattnera4d55d82008-10-06 06:40:35 +00004222 QualType ArgTy = E->getArg(0)->getType();
4223 if (ArgTy->isVoidType())
4224 return void_type_class;
4225 else if (ArgTy->isEnumeralType())
4226 return enumeral_type_class;
4227 else if (ArgTy->isBooleanType())
4228 return boolean_type_class;
4229 else if (ArgTy->isCharType())
4230 return string_type_class; // gcc doesn't appear to use char_type_class
4231 else if (ArgTy->isIntegerType())
4232 return integer_type_class;
4233 else if (ArgTy->isPointerType())
4234 return pointer_type_class;
4235 else if (ArgTy->isReferenceType())
4236 return reference_type_class;
4237 else if (ArgTy->isRealType())
4238 return real_type_class;
4239 else if (ArgTy->isComplexType())
4240 return complex_type_class;
4241 else if (ArgTy->isFunctionType())
4242 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004243 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004244 return record_type_class;
4245 else if (ArgTy->isUnionType())
4246 return union_type_class;
4247 else if (ArgTy->isArrayType())
4248 return array_type_class;
4249 else if (ArgTy->isUnionType())
4250 return union_type_class;
4251 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004252 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004253}
4254
Richard Smith80d4b552011-12-28 19:48:30 +00004255/// EvaluateBuiltinConstantPForLValue - Determine the result of
4256/// __builtin_constant_p when applied to the given lvalue.
4257///
4258/// An lvalue is only "constant" if it is a pointer or reference to the first
4259/// character of a string literal.
4260template<typename LValue>
4261static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4262 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
4263 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4264}
4265
4266/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4267/// GCC as we can manage.
4268static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4269 QualType ArgType = Arg->getType();
4270
4271 // __builtin_constant_p always has one operand. The rules which gcc follows
4272 // are not precisely documented, but are as follows:
4273 //
4274 // - If the operand is of integral, floating, complex or enumeration type,
4275 // and can be folded to a known value of that type, it returns 1.
4276 // - If the operand and can be folded to a pointer to the first character
4277 // of a string literal (or such a pointer cast to an integral type), it
4278 // returns 1.
4279 //
4280 // Otherwise, it returns 0.
4281 //
4282 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4283 // its support for this does not currently work.
4284 if (ArgType->isIntegralOrEnumerationType()) {
4285 Expr::EvalResult Result;
4286 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4287 return false;
4288
4289 APValue &V = Result.Val;
4290 if (V.getKind() == APValue::Int)
4291 return true;
4292
4293 return EvaluateBuiltinConstantPForLValue(V);
4294 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4295 return Arg->isEvaluatable(Ctx);
4296 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4297 LValue LV;
4298 Expr::EvalStatus Status;
4299 EvalInfo Info(Ctx, Status);
4300 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4301 : EvaluatePointer(Arg, LV, Info)) &&
4302 !Status.HasSideEffects)
4303 return EvaluateBuiltinConstantPForLValue(LV);
4304 }
4305
4306 // Anything else isn't considered to be sufficiently constant.
4307 return false;
4308}
4309
John McCall42c8f872010-05-10 23:27:23 +00004310/// Retrieves the "underlying object type" of the given expression,
4311/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004312QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4313 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4314 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004315 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004316 } else if (const Expr *E = B.get<const Expr*>()) {
4317 if (isa<CompoundLiteralExpr>(E))
4318 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004319 }
4320
4321 return QualType();
4322}
4323
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004324bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004325 // TODO: Perhaps we should let LLVM lower this?
4326 LValue Base;
4327 if (!EvaluatePointer(E->getArg(0), Base, Info))
4328 return false;
4329
4330 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004331 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004332
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004333 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004334 if (T.isNull() ||
4335 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004336 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004337 T->isVariablyModifiedType() ||
4338 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004339 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004340
4341 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4342 CharUnits Offset = Base.getLValueOffset();
4343
4344 if (!Offset.isNegative() && Offset <= Size)
4345 Size -= Offset;
4346 else
4347 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004348 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004349}
4350
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004351bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004352 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004353 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004354 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004355
4356 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004357 if (TryEvaluateBuiltinObjectSize(E))
4358 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004359
Eric Christopherb2aaf512010-01-19 22:58:35 +00004360 // If evaluating the argument has side-effects we can't determine
4361 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004362 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004363 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004364 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004365 return Success(0, E);
4366 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004367
Richard Smithf48fdb02011-12-09 22:58:01 +00004368 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004369 }
4370
Chris Lattner019f4e82008-10-06 05:28:25 +00004371 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004372 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004373
Richard Smith80d4b552011-12-28 19:48:30 +00004374 case Builtin::BI__builtin_constant_p:
4375 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004376
Chris Lattner21fb98e2009-09-23 06:06:36 +00004377 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004378 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004379 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004380 return Success(Operand, E);
4381 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004382
4383 case Builtin::BI__builtin_expect:
4384 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004385
Douglas Gregor5726d402010-09-10 06:27:15 +00004386 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004387 // A call to strlen is not a constant expression.
4388 if (Info.getLangOpts().CPlusPlus0x)
4389 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4390 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4391 else
4392 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4393 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004394 case Builtin::BI__builtin_strlen:
4395 // As an extension, we support strlen() and __builtin_strlen() as constant
4396 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004397 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004398 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4399 // The string literal may have embedded null characters. Find the first
4400 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004401 StringRef Str = S->getString();
4402 StringRef::size_type Pos = Str.find(0);
4403 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004404 Str = Str.substr(0, Pos);
4405
4406 return Success(Str.size(), E);
4407 }
4408
Richard Smithf48fdb02011-12-09 22:58:01 +00004409 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004410
4411 case Builtin::BI__atomic_is_lock_free: {
4412 APSInt SizeVal;
4413 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4414 return false;
4415
4416 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4417 // of two less than the maximum inline atomic width, we know it is
4418 // lock-free. If the size isn't a power of two, or greater than the
4419 // maximum alignment where we promote atomics, we know it is not lock-free
4420 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4421 // the answer can only be determined at runtime; for example, 16-byte
4422 // atomics have lock-free implementations on some, but not all,
4423 // x86-64 processors.
4424
4425 // Check power-of-two.
4426 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4427 if (!Size.isPowerOfTwo())
4428#if 0
4429 // FIXME: Suppress this folding until the ABI for the promotion width
4430 // settles.
4431 return Success(0, E);
4432#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004433 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004434#endif
4435
4436#if 0
4437 // Check against promotion width.
4438 // FIXME: Suppress this folding until the ABI for the promotion width
4439 // settles.
4440 unsigned PromoteWidthBits =
4441 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4442 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4443 return Success(0, E);
4444#endif
4445
4446 // Check against inlining width.
4447 unsigned InlineWidthBits =
4448 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4449 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4450 return Success(1, E);
4451
Richard Smithf48fdb02011-12-09 22:58:01 +00004452 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004453 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004454 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004455}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004456
Richard Smith625b8072011-10-31 01:37:14 +00004457static bool HasSameBase(const LValue &A, const LValue &B) {
4458 if (!A.getLValueBase())
4459 return !B.getLValueBase();
4460 if (!B.getLValueBase())
4461 return false;
4462
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004463 if (A.getLValueBase().getOpaqueValue() !=
4464 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004465 const Decl *ADecl = GetLValueBaseDecl(A);
4466 if (!ADecl)
4467 return false;
4468 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004469 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004470 return false;
4471 }
4472
4473 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004474 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004475}
4476
Richard Smith7b48a292012-02-01 05:53:12 +00004477/// Perform the given integer operation, which is known to need at most BitWidth
4478/// bits, and check for overflow in the original type (if that type was not an
4479/// unsigned type).
4480template<typename Operation>
4481static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4482 const APSInt &LHS, const APSInt &RHS,
4483 unsigned BitWidth, Operation Op) {
4484 if (LHS.isUnsigned())
4485 return Op(LHS, RHS);
4486
4487 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4488 APSInt Result = Value.trunc(LHS.getBitWidth());
4489 if (Result.extend(BitWidth) != Value)
4490 HandleOverflow(Info, E, Value, E->getType());
4491 return Result;
4492}
4493
Chris Lattnerb542afe2008-07-11 19:10:17 +00004494bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004495 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004496 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004497
John McCall2de56d12010-08-25 11:45:40 +00004498 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004499 VisitIgnoredValue(E->getLHS());
4500 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004501 }
4502
4503 if (E->isLogicalOp()) {
4504 // These need to be handled specially because the operands aren't
Richard Smith74e1ad92012-02-16 02:46:34 +00004505 // necessarily integral nor evaluated.
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004506 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004507
Richard Smithc49bd112011-10-28 17:51:58 +00004508 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004509 // We were able to evaluate the LHS, see if we can get away with not
4510 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004511 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004512 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004513
Richard Smithc49bd112011-10-28 17:51:58 +00004514 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004515 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004516 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004517 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004518 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004519 }
4520 } else {
Richard Smith74e1ad92012-02-16 02:46:34 +00004521 // Since we weren't able to evaluate the left hand side, it
4522 // must have had side effects.
4523 Info.EvalStatus.HasSideEffects = true;
4524
4525 // Suppress diagnostics from this arm.
4526 SpeculativeEvaluationRAII Speculative(Info);
Richard Smithc49bd112011-10-28 17:51:58 +00004527 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004528 // We can't evaluate the LHS; however, sometimes the result
4529 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smith74e1ad92012-02-16 02:46:34 +00004530 if (rhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar131eb432009-02-19 09:06:44 +00004531 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004532 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004533 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004534
Eli Friedmana6afa762008-11-13 06:09:17 +00004535 return false;
4536 }
4537
Anders Carlsson286f85e2008-11-16 07:17:21 +00004538 QualType LHSTy = E->getLHS()->getType();
4539 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004540
4541 if (LHSTy->isAnyComplexType()) {
4542 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004543 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004544
Richard Smith745f5142012-01-27 01:14:48 +00004545 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4546 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004547 return false;
4548
Richard Smith745f5142012-01-27 01:14:48 +00004549 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004550 return false;
4551
4552 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004553 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004554 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004555 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004556 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4557
John McCall2de56d12010-08-25 11:45:40 +00004558 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004559 return Success((CR_r == APFloat::cmpEqual &&
4560 CR_i == APFloat::cmpEqual), E);
4561 else {
John McCall2de56d12010-08-25 11:45:40 +00004562 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004563 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004564 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004565 CR_r == APFloat::cmpLessThan ||
4566 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004567 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004568 CR_i == APFloat::cmpLessThan ||
4569 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004570 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004571 } else {
John McCall2de56d12010-08-25 11:45:40 +00004572 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004573 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4574 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4575 else {
John McCall2de56d12010-08-25 11:45:40 +00004576 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004577 "Invalid compex comparison.");
4578 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4579 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4580 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004581 }
4582 }
Mike Stump1eb44332009-09-09 15:08:12 +00004583
Anders Carlsson286f85e2008-11-16 07:17:21 +00004584 if (LHSTy->isRealFloatingType() &&
4585 RHSTy->isRealFloatingType()) {
4586 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004587
Richard Smith745f5142012-01-27 01:14:48 +00004588 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4589 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004590 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004591
Richard Smith745f5142012-01-27 01:14:48 +00004592 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004593 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004594
Anders Carlsson286f85e2008-11-16 07:17:21 +00004595 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004596
Anders Carlsson286f85e2008-11-16 07:17:21 +00004597 switch (E->getOpcode()) {
4598 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004599 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004600 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004601 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004602 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004603 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004604 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004605 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004606 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004607 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004608 E);
John McCall2de56d12010-08-25 11:45:40 +00004609 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004610 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004611 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004612 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004613 || CR == APFloat::cmpLessThan
4614 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004615 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004616 }
Mike Stump1eb44332009-09-09 15:08:12 +00004617
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004618 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004619 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004620 LValue LHSValue, RHSValue;
4621
4622 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4623 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004624 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004625
Richard Smith745f5142012-01-27 01:14:48 +00004626 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004627 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004628
Richard Smith625b8072011-10-31 01:37:14 +00004629 // Reject differing bases from the normal codepath; we special-case
4630 // comparisons to null.
4631 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004632 if (E->getOpcode() == BO_Sub) {
4633 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004634 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4635 return false;
4636 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4637 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4638 if (!LHSExpr || !RHSExpr)
4639 return false;
4640 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4641 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4642 if (!LHSAddrExpr || !RHSAddrExpr)
4643 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004644 // Make sure both labels come from the same function.
4645 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4646 RHSAddrExpr->getLabel()->getDeclContext())
4647 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004648 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4649 return true;
4650 }
Richard Smith9e36b532011-10-31 05:11:32 +00004651 // Inequalities and subtractions between unrelated pointers have
4652 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004653 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004654 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004655 // A constant address may compare equal to the address of a symbol.
4656 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004657 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004658 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4659 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004660 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004661 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004662 // distinct addresses. In clang, the result of such a comparison is
4663 // unspecified, so it is not a constant expression. However, we do know
4664 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004665 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4666 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004667 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004668 // We can't tell whether weak symbols will end up pointing to the same
4669 // object.
4670 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004671 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004672 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004673 // (Note that clang defaults to -fmerge-all-constants, which can
4674 // lead to inconsistent results for comparisons involving the address
4675 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004676 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004677 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004678
Richard Smith15efc4d2012-02-01 08:10:20 +00004679 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4680 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4681
Richard Smithf15fda02012-02-02 01:16:57 +00004682 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4683 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4684
John McCall2de56d12010-08-25 11:45:40 +00004685 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004686 // C++11 [expr.add]p6:
4687 // Unless both pointers point to elements of the same array object, or
4688 // one past the last element of the array object, the behavior is
4689 // undefined.
4690 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4691 !AreElementsOfSameArray(getType(LHSValue.Base),
4692 LHSDesignator, RHSDesignator))
4693 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4694
Chris Lattner4992bdd2010-04-20 17:13:14 +00004695 QualType Type = E->getLHS()->getType();
4696 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004697
Richard Smith180f4792011-11-10 06:34:14 +00004698 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004699 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004700 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004701
Richard Smith15efc4d2012-02-01 08:10:20 +00004702 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4703 // and produce incorrect results when it overflows. Such behavior
4704 // appears to be non-conforming, but is common, so perhaps we should
4705 // assume the standard intended for such cases to be undefined behavior
4706 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004707
Richard Smith15efc4d2012-02-01 08:10:20 +00004708 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4709 // overflow in the final conversion to ptrdiff_t.
4710 APSInt LHS(
4711 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4712 APSInt RHS(
4713 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4714 APSInt ElemSize(
4715 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4716 APSInt TrueResult = (LHS - RHS) / ElemSize;
4717 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4718
4719 if (Result.extend(65) != TrueResult)
4720 HandleOverflow(Info, E, TrueResult, E->getType());
4721 return Success(Result, E);
4722 }
Richard Smith82f28582012-01-31 06:41:30 +00004723
4724 // C++11 [expr.rel]p3:
4725 // Pointers to void (after pointer conversions) can be compared, with a
4726 // result defined as follows: If both pointers represent the same
4727 // address or are both the null pointer value, the result is true if the
4728 // operator is <= or >= and false otherwise; otherwise the result is
4729 // unspecified.
4730 // We interpret this as applying to pointers to *cv* void.
4731 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004732 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004733 CCEDiag(E, diag::note_constexpr_void_comparison);
4734
Richard Smithf15fda02012-02-02 01:16:57 +00004735 // C++11 [expr.rel]p2:
4736 // - If two pointers point to non-static data members of the same object,
4737 // or to subobjects or array elements fo such members, recursively, the
4738 // pointer to the later declared member compares greater provided the
4739 // two members have the same access control and provided their class is
4740 // not a union.
4741 // [...]
4742 // - Otherwise pointer comparisons are unspecified.
4743 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4744 E->isRelationalOp()) {
4745 bool WasArrayIndex;
4746 unsigned Mismatch =
4747 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4748 RHSDesignator, WasArrayIndex);
4749 // At the point where the designators diverge, the comparison has a
4750 // specified value if:
4751 // - we are comparing array indices
4752 // - we are comparing fields of a union, or fields with the same access
4753 // Otherwise, the result is unspecified and thus the comparison is not a
4754 // constant expression.
4755 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4756 Mismatch < RHSDesignator.Entries.size()) {
4757 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4758 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4759 if (!LF && !RF)
4760 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4761 else if (!LF)
4762 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4763 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4764 << RF->getParent() << RF;
4765 else if (!RF)
4766 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4767 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4768 << LF->getParent() << LF;
4769 else if (!LF->getParent()->isUnion() &&
4770 LF->getAccess() != RF->getAccess())
4771 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4772 << LF << LF->getAccess() << RF << RF->getAccess()
4773 << LF->getParent();
4774 }
4775 }
4776
Richard Smith625b8072011-10-31 01:37:14 +00004777 switch (E->getOpcode()) {
4778 default: llvm_unreachable("missing comparison operator");
4779 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4780 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4781 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4782 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4783 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4784 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004785 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004786 }
4787 }
Richard Smithb02e4622012-02-01 01:42:44 +00004788
4789 if (LHSTy->isMemberPointerType()) {
4790 assert(E->isEqualityOp() && "unexpected member pointer operation");
4791 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4792
4793 MemberPtr LHSValue, RHSValue;
4794
4795 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4796 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4797 return false;
4798
4799 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4800 return false;
4801
4802 // C++11 [expr.eq]p2:
4803 // If both operands are null, they compare equal. Otherwise if only one is
4804 // null, they compare unequal.
4805 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4806 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4807 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4808 }
4809
4810 // Otherwise if either is a pointer to a virtual member function, the
4811 // result is unspecified.
4812 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4813 if (MD->isVirtual())
4814 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4815 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4816 if (MD->isVirtual())
4817 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4818
4819 // Otherwise they compare equal if and only if they would refer to the
4820 // same member of the same most derived object or the same subobject if
4821 // they were dereferenced with a hypothetical object of the associated
4822 // class type.
4823 bool Equal = LHSValue == RHSValue;
4824 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4825 }
4826
Richard Smith26f2cac2012-02-14 22:35:28 +00004827 if (LHSTy->isNullPtrType()) {
4828 assert(E->isComparisonOp() && "unexpected nullptr operation");
4829 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
4830 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
4831 // are compared, the result is true of the operator is <=, >= or ==, and
4832 // false otherwise.
4833 BinaryOperator::Opcode Opcode = E->getOpcode();
4834 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
4835 }
4836
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004837 if (!LHSTy->isIntegralOrEnumerationType() ||
4838 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004839 // We can't continue from here for non-integral types.
4840 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004841 }
4842
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004843 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004844 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004845
4846 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4847 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004848 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004849
Richard Smith745f5142012-01-27 01:14:48 +00004850 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004851 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004852
Richard Smith47a1eed2011-10-29 20:57:55 +00004853 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004854
4855 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004856 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004857 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4858 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004859 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004860 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004861 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004862 LHSVal.getLValueOffset() -= AdditionalOffset;
4863 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004864 return true;
4865 }
4866
4867 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004868 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004869 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004870 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4871 LHSVal.getInt().getZExtValue());
4872 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004873 return true;
4874 }
4875
Eli Friedman65639282012-01-04 23:13:47 +00004876 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4877 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004878 if (!LHSVal.getLValueOffset().isZero() ||
4879 !RHSVal.getLValueOffset().isZero())
4880 return false;
4881 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4882 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4883 if (!LHSExpr || !RHSExpr)
4884 return false;
4885 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4886 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4887 if (!LHSAddrExpr || !RHSAddrExpr)
4888 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004889 // Make sure both labels come from the same function.
4890 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4891 RHSAddrExpr->getLabel()->getDeclContext())
4892 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004893 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4894 return true;
4895 }
4896
Eli Friedman42edd0d2009-03-24 01:14:50 +00004897 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004898 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004899 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004900
Richard Smithc49bd112011-10-28 17:51:58 +00004901 APSInt &LHS = LHSVal.getInt();
4902 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004903
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004904 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004905 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004906 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004907 case BO_Mul:
4908 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4909 LHS.getBitWidth() * 2,
4910 std::multiplies<APSInt>()), E);
4911 case BO_Add:
4912 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4913 LHS.getBitWidth() + 1,
4914 std::plus<APSInt>()), E);
4915 case BO_Sub:
4916 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4917 LHS.getBitWidth() + 1,
4918 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004919 case BO_And: return Success(LHS & RHS, E);
4920 case BO_Xor: return Success(LHS ^ RHS, E);
4921 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004922 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004923 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004924 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004925 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004926 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4927 // actually undefined behavior in C++11 due to a language defect.
4928 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4929 LHS.isSigned() && LHS.isMinSignedValue())
4930 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4931 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004932 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004933 // During constant-folding, a negative shift is an opposite shift. Such a
4934 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004935 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004936 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004937 RHS = -RHS;
4938 goto shift_right;
4939 }
4940
4941 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004942 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4943 // shifted type.
4944 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4945 if (SA != RHS) {
4946 CCEDiag(E, diag::note_constexpr_large_shift)
4947 << RHS << E->getType() << LHS.getBitWidth();
4948 } else if (LHS.isSigned()) {
4949 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
Richard Smith925d8e72012-02-08 06:14:53 +00004950 // operand, and must not overflow the corresponding unsigned type.
Richard Smith789f9b62012-01-31 04:08:20 +00004951 if (LHS.isNegative())
4952 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
Richard Smith925d8e72012-02-08 06:14:53 +00004953 else if (LHS.countLeadingZeros() < SA)
4954 CCEDiag(E, diag::note_constexpr_lshift_discards);
Richard Smith789f9b62012-01-31 04:08:20 +00004955 }
4956
Richard Smithc49bd112011-10-28 17:51:58 +00004957 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004958 }
John McCall2de56d12010-08-25 11:45:40 +00004959 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004960 // During constant-folding, a negative shift is an opposite shift. Such a
4961 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004962 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004963 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004964 RHS = -RHS;
4965 goto shift_left;
4966 }
4967
4968 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004969 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4970 // shifted type.
4971 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4972 if (SA != RHS)
4973 CCEDiag(E, diag::note_constexpr_large_shift)
4974 << RHS << E->getType() << LHS.getBitWidth();
4975
Richard Smithc49bd112011-10-28 17:51:58 +00004976 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004977 }
Mike Stump1eb44332009-09-09 15:08:12 +00004978
Richard Smithc49bd112011-10-28 17:51:58 +00004979 case BO_LT: return Success(LHS < RHS, E);
4980 case BO_GT: return Success(LHS > RHS, E);
4981 case BO_LE: return Success(LHS <= RHS, E);
4982 case BO_GE: return Success(LHS >= RHS, E);
4983 case BO_EQ: return Success(LHS == RHS, E);
4984 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004985 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004986}
4987
Ken Dyck8b752f12010-01-27 17:10:57 +00004988CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004989 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4990 // result shall be the alignment of the referenced type."
4991 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4992 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004993
4994 // __alignof is defined to return the preferred alignment.
4995 return Info.Ctx.toCharUnitsFromBits(
4996 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004997}
4998
Ken Dyck8b752f12010-01-27 17:10:57 +00004999CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005000 E = E->IgnoreParens();
5001
5002 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005003 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005004 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005005 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5006 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005007
Chris Lattneraf707ab2009-01-24 21:53:27 +00005008 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005009 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5010 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005011
Chris Lattnere9feb472009-01-24 21:09:06 +00005012 return GetAlignOfType(E->getType());
5013}
5014
5015
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005016/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5017/// a result as the expression's type.
5018bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5019 const UnaryExprOrTypeTraitExpr *E) {
5020 switch(E->getKind()) {
5021 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005022 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005023 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005024 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005025 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005026 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005027
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005028 case UETT_VecStep: {
5029 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005030
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005031 if (Ty->isVectorType()) {
5032 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005033
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005034 // The vec_step built-in functions that take a 3-component
5035 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5036 if (n == 3)
5037 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005038
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005039 return Success(n, E);
5040 } else
5041 return Success(1, E);
5042 }
5043
5044 case UETT_SizeOf: {
5045 QualType SrcTy = E->getTypeOfArgument();
5046 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5047 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005048 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5049 SrcTy = Ref->getPointeeType();
5050
Richard Smith180f4792011-11-10 06:34:14 +00005051 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005052 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005053 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005054 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005055 }
5056 }
5057
5058 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005059}
5060
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005061bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005062 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005063 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005064 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005065 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005066 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005067 for (unsigned i = 0; i != n; ++i) {
5068 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5069 switch (ON.getKind()) {
5070 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005071 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005072 APSInt IdxResult;
5073 if (!EvaluateInteger(Idx, IdxResult, Info))
5074 return false;
5075 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5076 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005077 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005078 CurrentType = AT->getElementType();
5079 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5080 Result += IdxResult.getSExtValue() * ElementSize;
5081 break;
5082 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005083
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005084 case OffsetOfExpr::OffsetOfNode::Field: {
5085 FieldDecl *MemberDecl = ON.getField();
5086 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005087 if (!RT)
5088 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005089 RecordDecl *RD = RT->getDecl();
5090 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005091 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005092 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005093 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005094 CurrentType = MemberDecl->getType().getNonReferenceType();
5095 break;
5096 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005097
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005098 case OffsetOfExpr::OffsetOfNode::Identifier:
5099 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005100
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005101 case OffsetOfExpr::OffsetOfNode::Base: {
5102 CXXBaseSpecifier *BaseSpec = ON.getBase();
5103 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005104 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005105
5106 // Find the layout of the class whose base we are looking into.
5107 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005108 if (!RT)
5109 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005110 RecordDecl *RD = RT->getDecl();
5111 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5112
5113 // Find the base class itself.
5114 CurrentType = BaseSpec->getType();
5115 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5116 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005117 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005118
5119 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005120 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005121 break;
5122 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005123 }
5124 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005125 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005126}
5127
Chris Lattnerb542afe2008-07-11 19:10:17 +00005128bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005129 switch (E->getOpcode()) {
5130 default:
5131 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5132 // See C99 6.6p3.
5133 return Error(E);
5134 case UO_Extension:
5135 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5136 // If so, we could clear the diagnostic ID.
5137 return Visit(E->getSubExpr());
5138 case UO_Plus:
5139 // The result is just the value.
5140 return Visit(E->getSubExpr());
5141 case UO_Minus: {
5142 if (!Visit(E->getSubExpr()))
5143 return false;
5144 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005145 const APSInt &Value = Result.getInt();
5146 if (Value.isSigned() && Value.isMinSignedValue())
5147 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5148 E->getType());
5149 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005150 }
5151 case UO_Not: {
5152 if (!Visit(E->getSubExpr()))
5153 return false;
5154 if (!Result.isInt()) return Error(E);
5155 return Success(~Result.getInt(), E);
5156 }
5157 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005158 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005159 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005160 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005161 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005162 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005163 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005164}
Mike Stump1eb44332009-09-09 15:08:12 +00005165
Chris Lattner732b2232008-07-12 01:15:53 +00005166/// HandleCast - This is used to evaluate implicit or explicit casts where the
5167/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005168bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5169 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005170 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005171 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005172
Eli Friedman46a52322011-03-25 00:43:55 +00005173 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005174 case CK_BaseToDerived:
5175 case CK_DerivedToBase:
5176 case CK_UncheckedDerivedToBase:
5177 case CK_Dynamic:
5178 case CK_ToUnion:
5179 case CK_ArrayToPointerDecay:
5180 case CK_FunctionToPointerDecay:
5181 case CK_NullToPointer:
5182 case CK_NullToMemberPointer:
5183 case CK_BaseToDerivedMemberPointer:
5184 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005185 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005186 case CK_ConstructorConversion:
5187 case CK_IntegralToPointer:
5188 case CK_ToVoid:
5189 case CK_VectorSplat:
5190 case CK_IntegralToFloating:
5191 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005192 case CK_CPointerToObjCPointerCast:
5193 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005194 case CK_AnyPointerToBlockPointerCast:
5195 case CK_ObjCObjectLValueCast:
5196 case CK_FloatingRealToComplex:
5197 case CK_FloatingComplexToReal:
5198 case CK_FloatingComplexCast:
5199 case CK_FloatingComplexToIntegralComplex:
5200 case CK_IntegralRealToComplex:
5201 case CK_IntegralComplexCast:
5202 case CK_IntegralComplexToFloatingComplex:
5203 llvm_unreachable("invalid cast kind for integral value");
5204
Eli Friedmane50c2972011-03-25 19:07:11 +00005205 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005206 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005207 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005208 case CK_ARCProduceObject:
5209 case CK_ARCConsumeObject:
5210 case CK_ARCReclaimReturnedObject:
5211 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005212 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005213 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005214
Richard Smith7d580a42012-01-17 21:17:26 +00005215 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005216 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005217 case CK_AtomicToNonAtomic:
5218 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005219 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005220 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005221
5222 case CK_MemberPointerToBoolean:
5223 case CK_PointerToBoolean:
5224 case CK_IntegralToBoolean:
5225 case CK_FloatingToBoolean:
5226 case CK_FloatingComplexToBoolean:
5227 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005228 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005229 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005230 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005231 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005232 }
5233
Eli Friedman46a52322011-03-25 00:43:55 +00005234 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005235 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005236 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005237
Eli Friedmanbe265702009-02-20 01:15:07 +00005238 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005239 // Allow casts of address-of-label differences if they are no-ops
5240 // or narrowing. (The narrowing case isn't actually guaranteed to
5241 // be constant-evaluatable except in some narrow cases which are hard
5242 // to detect here. We let it through on the assumption the user knows
5243 // what they are doing.)
5244 if (Result.isAddrLabelDiff())
5245 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005246 // Only allow casts of lvalues if they are lossless.
5247 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5248 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005249
Richard Smithf72fccf2012-01-30 22:27:01 +00005250 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5251 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005252 }
Mike Stump1eb44332009-09-09 15:08:12 +00005253
Eli Friedman46a52322011-03-25 00:43:55 +00005254 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005255 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5256
John McCallefdb83e2010-05-07 21:00:08 +00005257 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005258 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005259 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005260
Daniel Dunbardd211642009-02-19 22:24:01 +00005261 if (LV.getLValueBase()) {
5262 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005263 // FIXME: Allow a larger integer size than the pointer size, and allow
5264 // narrowing back down to pointer width in subsequent integral casts.
5265 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005266 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005267 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005268
Richard Smithb755a9d2011-11-16 07:18:12 +00005269 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005270 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005271 return true;
5272 }
5273
Ken Dycka7305832010-01-15 12:37:54 +00005274 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5275 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005276 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005277 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005278
Eli Friedman46a52322011-03-25 00:43:55 +00005279 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005280 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005281 if (!EvaluateComplex(SubExpr, C, Info))
5282 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005283 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005284 }
Eli Friedman2217c872009-02-22 11:46:18 +00005285
Eli Friedman46a52322011-03-25 00:43:55 +00005286 case CK_FloatingToIntegral: {
5287 APFloat F(0.0);
5288 if (!EvaluateFloat(SubExpr, F, Info))
5289 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005290
Richard Smithc1c5f272011-12-13 06:39:58 +00005291 APSInt Value;
5292 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5293 return false;
5294 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005295 }
5296 }
Mike Stump1eb44332009-09-09 15:08:12 +00005297
Eli Friedman46a52322011-03-25 00:43:55 +00005298 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005299}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005300
Eli Friedman722c7172009-02-28 03:59:05 +00005301bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5302 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005303 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005304 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5305 return false;
5306 if (!LV.isComplexInt())
5307 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005308 return Success(LV.getComplexIntReal(), E);
5309 }
5310
5311 return Visit(E->getSubExpr());
5312}
5313
Eli Friedman664a1042009-02-27 04:45:43 +00005314bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005315 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005316 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005317 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5318 return false;
5319 if (!LV.isComplexInt())
5320 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005321 return Success(LV.getComplexIntImag(), E);
5322 }
5323
Richard Smith8327fad2011-10-24 18:44:57 +00005324 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005325 return Success(0, E);
5326}
5327
Douglas Gregoree8aff02011-01-04 17:33:58 +00005328bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5329 return Success(E->getPackLength(), E);
5330}
5331
Sebastian Redl295995c2010-09-10 20:55:47 +00005332bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5333 return Success(E->getValue(), E);
5334}
5335
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005336//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005337// Float Evaluation
5338//===----------------------------------------------------------------------===//
5339
5340namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005341class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005342 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005343 APFloat &Result;
5344public:
5345 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005346 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005347
Richard Smith47a1eed2011-10-29 20:57:55 +00005348 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005349 Result = V.getFloat();
5350 return true;
5351 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005352
Richard Smith51201882011-12-30 21:15:51 +00005353 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005354 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5355 return true;
5356 }
5357
Chris Lattner019f4e82008-10-06 05:28:25 +00005358 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005359
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005360 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005361 bool VisitBinaryOperator(const BinaryOperator *E);
5362 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005363 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005364
John McCallabd3a852010-05-07 22:08:54 +00005365 bool VisitUnaryReal(const UnaryOperator *E);
5366 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005367
Richard Smith51201882011-12-30 21:15:51 +00005368 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005369};
5370} // end anonymous namespace
5371
5372static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005373 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005374 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005375}
5376
Jay Foad4ba2a172011-01-12 09:06:06 +00005377static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005378 QualType ResultTy,
5379 const Expr *Arg,
5380 bool SNaN,
5381 llvm::APFloat &Result) {
5382 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5383 if (!S) return false;
5384
5385 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5386
5387 llvm::APInt fill;
5388
5389 // Treat empty strings as if they were zero.
5390 if (S->getString().empty())
5391 fill = llvm::APInt(32, 0);
5392 else if (S->getString().getAsInteger(0, fill))
5393 return false;
5394
5395 if (SNaN)
5396 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5397 else
5398 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5399 return true;
5400}
5401
Chris Lattner019f4e82008-10-06 05:28:25 +00005402bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005403 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005404 default:
5405 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5406
Chris Lattner019f4e82008-10-06 05:28:25 +00005407 case Builtin::BI__builtin_huge_val:
5408 case Builtin::BI__builtin_huge_valf:
5409 case Builtin::BI__builtin_huge_vall:
5410 case Builtin::BI__builtin_inf:
5411 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005412 case Builtin::BI__builtin_infl: {
5413 const llvm::fltSemantics &Sem =
5414 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005415 Result = llvm::APFloat::getInf(Sem);
5416 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005417 }
Mike Stump1eb44332009-09-09 15:08:12 +00005418
John McCalldb7b72a2010-02-28 13:00:19 +00005419 case Builtin::BI__builtin_nans:
5420 case Builtin::BI__builtin_nansf:
5421 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005422 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5423 true, Result))
5424 return Error(E);
5425 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005426
Chris Lattner9e621712008-10-06 06:31:58 +00005427 case Builtin::BI__builtin_nan:
5428 case Builtin::BI__builtin_nanf:
5429 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005430 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005431 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005432 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5433 false, Result))
5434 return Error(E);
5435 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005436
5437 case Builtin::BI__builtin_fabs:
5438 case Builtin::BI__builtin_fabsf:
5439 case Builtin::BI__builtin_fabsl:
5440 if (!EvaluateFloat(E->getArg(0), Result, Info))
5441 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005442
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005443 if (Result.isNegative())
5444 Result.changeSign();
5445 return true;
5446
Mike Stump1eb44332009-09-09 15:08:12 +00005447 case Builtin::BI__builtin_copysign:
5448 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005449 case Builtin::BI__builtin_copysignl: {
5450 APFloat RHS(0.);
5451 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5452 !EvaluateFloat(E->getArg(1), RHS, Info))
5453 return false;
5454 Result.copySign(RHS);
5455 return true;
5456 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005457 }
5458}
5459
John McCallabd3a852010-05-07 22:08:54 +00005460bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005461 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5462 ComplexValue CV;
5463 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5464 return false;
5465 Result = CV.FloatReal;
5466 return true;
5467 }
5468
5469 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005470}
5471
5472bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005473 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5474 ComplexValue CV;
5475 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5476 return false;
5477 Result = CV.FloatImag;
5478 return true;
5479 }
5480
Richard Smith8327fad2011-10-24 18:44:57 +00005481 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005482 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5483 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005484 return true;
5485}
5486
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005487bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005488 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005489 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005490 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005491 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005492 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005493 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5494 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005495 Result.changeSign();
5496 return true;
5497 }
5498}
Chris Lattner019f4e82008-10-06 05:28:25 +00005499
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005500bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005501 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5502 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005503
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005504 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005505 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5506 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005507 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005508 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005509 return false;
5510
5511 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005512 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005513 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005514 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005515 break;
John McCall2de56d12010-08-25 11:45:40 +00005516 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005517 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005518 break;
John McCall2de56d12010-08-25 11:45:40 +00005519 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005520 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005521 break;
John McCall2de56d12010-08-25 11:45:40 +00005522 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005523 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005524 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005525 }
Richard Smith7b48a292012-02-01 05:53:12 +00005526
5527 if (Result.isInfinity() || Result.isNaN())
5528 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5529 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005530}
5531
5532bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5533 Result = E->getValue();
5534 return true;
5535}
5536
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005537bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5538 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005539
Eli Friedman2a523ee2011-03-25 00:54:52 +00005540 switch (E->getCastKind()) {
5541 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005542 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005543
5544 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005545 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005546 return EvaluateInteger(SubExpr, IntResult, Info) &&
5547 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5548 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005549 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005550
5551 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005552 if (!Visit(SubExpr))
5553 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005554 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5555 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005556 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005557
Eli Friedman2a523ee2011-03-25 00:54:52 +00005558 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005559 ComplexValue V;
5560 if (!EvaluateComplex(SubExpr, V, Info))
5561 return false;
5562 Result = V.getComplexFloatReal();
5563 return true;
5564 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005565 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005566}
5567
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005568//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005569// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005570//===----------------------------------------------------------------------===//
5571
5572namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005573class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005574 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005575 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005576
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005577public:
John McCallf4cf1a12010-05-07 17:22:02 +00005578 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005579 : ExprEvaluatorBaseTy(info), Result(Result) {}
5580
Richard Smith47a1eed2011-10-29 20:57:55 +00005581 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005582 Result.setFrom(V);
5583 return true;
5584 }
Mike Stump1eb44332009-09-09 15:08:12 +00005585
Eli Friedman7ead5c72012-01-10 04:58:17 +00005586 bool ZeroInitialization(const Expr *E);
5587
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005588 //===--------------------------------------------------------------------===//
5589 // Visitor Methods
5590 //===--------------------------------------------------------------------===//
5591
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005592 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005593 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005594 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005595 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005596 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005597};
5598} // end anonymous namespace
5599
John McCallf4cf1a12010-05-07 17:22:02 +00005600static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5601 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005602 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005603 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005604}
5605
Eli Friedman7ead5c72012-01-10 04:58:17 +00005606bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005607 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005608 if (ElemTy->isRealFloatingType()) {
5609 Result.makeComplexFloat();
5610 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5611 Result.FloatReal = Zero;
5612 Result.FloatImag = Zero;
5613 } else {
5614 Result.makeComplexInt();
5615 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5616 Result.IntReal = Zero;
5617 Result.IntImag = Zero;
5618 }
5619 return true;
5620}
5621
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005622bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5623 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005624
5625 if (SubExpr->getType()->isRealFloatingType()) {
5626 Result.makeComplexFloat();
5627 APFloat &Imag = Result.FloatImag;
5628 if (!EvaluateFloat(SubExpr, Imag, Info))
5629 return false;
5630
5631 Result.FloatReal = APFloat(Imag.getSemantics());
5632 return true;
5633 } else {
5634 assert(SubExpr->getType()->isIntegerType() &&
5635 "Unexpected imaginary literal.");
5636
5637 Result.makeComplexInt();
5638 APSInt &Imag = Result.IntImag;
5639 if (!EvaluateInteger(SubExpr, Imag, Info))
5640 return false;
5641
5642 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5643 return true;
5644 }
5645}
5646
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005647bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005648
John McCall8786da72010-12-14 17:51:41 +00005649 switch (E->getCastKind()) {
5650 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005651 case CK_BaseToDerived:
5652 case CK_DerivedToBase:
5653 case CK_UncheckedDerivedToBase:
5654 case CK_Dynamic:
5655 case CK_ToUnion:
5656 case CK_ArrayToPointerDecay:
5657 case CK_FunctionToPointerDecay:
5658 case CK_NullToPointer:
5659 case CK_NullToMemberPointer:
5660 case CK_BaseToDerivedMemberPointer:
5661 case CK_DerivedToBaseMemberPointer:
5662 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005663 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005664 case CK_ConstructorConversion:
5665 case CK_IntegralToPointer:
5666 case CK_PointerToIntegral:
5667 case CK_PointerToBoolean:
5668 case CK_ToVoid:
5669 case CK_VectorSplat:
5670 case CK_IntegralCast:
5671 case CK_IntegralToBoolean:
5672 case CK_IntegralToFloating:
5673 case CK_FloatingToIntegral:
5674 case CK_FloatingToBoolean:
5675 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005676 case CK_CPointerToObjCPointerCast:
5677 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005678 case CK_AnyPointerToBlockPointerCast:
5679 case CK_ObjCObjectLValueCast:
5680 case CK_FloatingComplexToReal:
5681 case CK_FloatingComplexToBoolean:
5682 case CK_IntegralComplexToReal:
5683 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005684 case CK_ARCProduceObject:
5685 case CK_ARCConsumeObject:
5686 case CK_ARCReclaimReturnedObject:
5687 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005688 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005689 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005690
John McCall8786da72010-12-14 17:51:41 +00005691 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005692 case CK_AtomicToNonAtomic:
5693 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005694 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005695 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005696
5697 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005698 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005699 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005700 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005701
5702 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005703 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005704 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005705 return false;
5706
John McCall8786da72010-12-14 17:51:41 +00005707 Result.makeComplexFloat();
5708 Result.FloatImag = APFloat(Real.getSemantics());
5709 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005710 }
5711
John McCall8786da72010-12-14 17:51:41 +00005712 case CK_FloatingComplexCast: {
5713 if (!Visit(E->getSubExpr()))
5714 return false;
5715
5716 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5717 QualType From
5718 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5719
Richard Smithc1c5f272011-12-13 06:39:58 +00005720 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5721 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005722 }
5723
5724 case CK_FloatingComplexToIntegralComplex: {
5725 if (!Visit(E->getSubExpr()))
5726 return false;
5727
5728 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5729 QualType From
5730 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5731 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005732 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5733 To, Result.IntReal) &&
5734 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5735 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005736 }
5737
5738 case CK_IntegralRealToComplex: {
5739 APSInt &Real = Result.IntReal;
5740 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5741 return false;
5742
5743 Result.makeComplexInt();
5744 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5745 return true;
5746 }
5747
5748 case CK_IntegralComplexCast: {
5749 if (!Visit(E->getSubExpr()))
5750 return false;
5751
5752 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5753 QualType From
5754 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5755
Richard Smithf72fccf2012-01-30 22:27:01 +00005756 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5757 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005758 return true;
5759 }
5760
5761 case CK_IntegralComplexToFloatingComplex: {
5762 if (!Visit(E->getSubExpr()))
5763 return false;
5764
5765 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5766 QualType From
5767 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5768 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005769 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5770 To, Result.FloatReal) &&
5771 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5772 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005773 }
5774 }
5775
5776 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005777}
5778
John McCallf4cf1a12010-05-07 17:22:02 +00005779bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005780 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005781 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5782
Richard Smith745f5142012-01-27 01:14:48 +00005783 bool LHSOK = Visit(E->getLHS());
5784 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005785 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005786
John McCallf4cf1a12010-05-07 17:22:02 +00005787 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005788 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005789 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005790
Daniel Dunbar3f279872009-01-29 01:32:56 +00005791 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5792 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005793 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005794 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005795 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005796 if (Result.isComplexFloat()) {
5797 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5798 APFloat::rmNearestTiesToEven);
5799 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5800 APFloat::rmNearestTiesToEven);
5801 } else {
5802 Result.getComplexIntReal() += RHS.getComplexIntReal();
5803 Result.getComplexIntImag() += RHS.getComplexIntImag();
5804 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005805 break;
John McCall2de56d12010-08-25 11:45:40 +00005806 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005807 if (Result.isComplexFloat()) {
5808 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5809 APFloat::rmNearestTiesToEven);
5810 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5811 APFloat::rmNearestTiesToEven);
5812 } else {
5813 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5814 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5815 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005816 break;
John McCall2de56d12010-08-25 11:45:40 +00005817 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005818 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005819 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005820 APFloat &LHS_r = LHS.getComplexFloatReal();
5821 APFloat &LHS_i = LHS.getComplexFloatImag();
5822 APFloat &RHS_r = RHS.getComplexFloatReal();
5823 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005824
Daniel Dunbar3f279872009-01-29 01:32:56 +00005825 APFloat Tmp = LHS_r;
5826 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5827 Result.getComplexFloatReal() = Tmp;
5828 Tmp = LHS_i;
5829 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5830 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5831
5832 Tmp = LHS_r;
5833 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5834 Result.getComplexFloatImag() = Tmp;
5835 Tmp = LHS_i;
5836 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5837 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5838 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005839 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005840 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005841 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5842 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005843 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005844 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5845 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5846 }
5847 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005848 case BO_Div:
5849 if (Result.isComplexFloat()) {
5850 ComplexValue LHS = Result;
5851 APFloat &LHS_r = LHS.getComplexFloatReal();
5852 APFloat &LHS_i = LHS.getComplexFloatImag();
5853 APFloat &RHS_r = RHS.getComplexFloatReal();
5854 APFloat &RHS_i = RHS.getComplexFloatImag();
5855 APFloat &Res_r = Result.getComplexFloatReal();
5856 APFloat &Res_i = Result.getComplexFloatImag();
5857
5858 APFloat Den = RHS_r;
5859 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5860 APFloat Tmp = RHS_i;
5861 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5862 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5863
5864 Res_r = LHS_r;
5865 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5866 Tmp = LHS_i;
5867 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5868 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5869 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5870
5871 Res_i = LHS_i;
5872 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5873 Tmp = LHS_r;
5874 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5875 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5876 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5877 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005878 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5879 return Error(E, diag::note_expr_divide_by_zero);
5880
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005881 ComplexValue LHS = Result;
5882 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5883 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5884 Result.getComplexIntReal() =
5885 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5886 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5887 Result.getComplexIntImag() =
5888 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5889 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5890 }
5891 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005892 }
5893
John McCallf4cf1a12010-05-07 17:22:02 +00005894 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005895}
5896
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005897bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5898 // Get the operand value into 'Result'.
5899 if (!Visit(E->getSubExpr()))
5900 return false;
5901
5902 switch (E->getOpcode()) {
5903 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005904 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005905 case UO_Extension:
5906 return true;
5907 case UO_Plus:
5908 // The result is always just the subexpr.
5909 return true;
5910 case UO_Minus:
5911 if (Result.isComplexFloat()) {
5912 Result.getComplexFloatReal().changeSign();
5913 Result.getComplexFloatImag().changeSign();
5914 }
5915 else {
5916 Result.getComplexIntReal() = -Result.getComplexIntReal();
5917 Result.getComplexIntImag() = -Result.getComplexIntImag();
5918 }
5919 return true;
5920 case UO_Not:
5921 if (Result.isComplexFloat())
5922 Result.getComplexFloatImag().changeSign();
5923 else
5924 Result.getComplexIntImag() = -Result.getComplexIntImag();
5925 return true;
5926 }
5927}
5928
Eli Friedman7ead5c72012-01-10 04:58:17 +00005929bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5930 if (E->getNumInits() == 2) {
5931 if (E->getType()->isComplexType()) {
5932 Result.makeComplexFloat();
5933 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5934 return false;
5935 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5936 return false;
5937 } else {
5938 Result.makeComplexInt();
5939 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5940 return false;
5941 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5942 return false;
5943 }
5944 return true;
5945 }
5946 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5947}
5948
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005949//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005950// Void expression evaluation, primarily for a cast to void on the LHS of a
5951// comma operator
5952//===----------------------------------------------------------------------===//
5953
5954namespace {
5955class VoidExprEvaluator
5956 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5957public:
5958 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5959
5960 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005961
5962 bool VisitCastExpr(const CastExpr *E) {
5963 switch (E->getCastKind()) {
5964 default:
5965 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5966 case CK_ToVoid:
5967 VisitIgnoredValue(E->getSubExpr());
5968 return true;
5969 }
5970 }
5971};
5972} // end anonymous namespace
5973
5974static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5975 assert(E->isRValue() && E->getType()->isVoidType());
5976 return VoidExprEvaluator(Info).Visit(E);
5977}
5978
5979//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005980// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005981//===----------------------------------------------------------------------===//
5982
Richard Smith47a1eed2011-10-29 20:57:55 +00005983static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005984 // In C, function designators are not lvalues, but we evaluate them as if they
5985 // are.
5986 if (E->isGLValue() || E->getType()->isFunctionType()) {
5987 LValue LV;
5988 if (!EvaluateLValue(E, LV, Info))
5989 return false;
5990 LV.moveInto(Result);
5991 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005992 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005993 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005994 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005995 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005996 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005997 } else if (E->getType()->hasPointerRepresentation()) {
5998 LValue LV;
5999 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006000 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006001 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006002 } else if (E->getType()->isRealFloatingType()) {
6003 llvm::APFloat F(0.0);
6004 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006005 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00006006 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006007 } else if (E->getType()->isAnyComplexType()) {
6008 ComplexValue C;
6009 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006010 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006011 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006012 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006013 MemberPtr P;
6014 if (!EvaluateMemberPointer(E, P, Info))
6015 return false;
6016 P.moveInto(Result);
6017 return true;
Richard Smith51201882011-12-30 21:15:51 +00006018 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006019 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006020 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006021 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006022 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006023 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006024 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006025 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006026 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006027 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6028 return false;
6029 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006030 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00006031 if (Info.getLangOpts().CPlusPlus0x)
6032 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
6033 << E->getType();
6034 else
6035 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00006036 if (!EvaluateVoid(E, Info))
6037 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006038 } else if (Info.getLangOpts().CPlusPlus0x) {
6039 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
6040 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006041 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00006042 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006043 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006044 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006045
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006046 return true;
6047}
6048
Richard Smith83587db2012-02-15 02:18:13 +00006049/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6050/// cases, the in-place evaluation is essential, since later initializers for
6051/// an object can indirectly refer to subobjects which were initialized earlier.
6052static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6053 const Expr *E, CheckConstantExpressionKind CCEK,
6054 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006055 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006056 return false;
6057
6058 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006059 // Evaluate arrays and record types in-place, so that later initializers can
6060 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006061 if (E->getType()->isArrayType())
6062 return EvaluateArray(E, This, Result, Info);
6063 else if (E->getType()->isRecordType())
6064 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006065 }
6066
6067 // For any other type, in-place evaluation is unimportant.
6068 CCValue CoreConstResult;
Richard Smith83587db2012-02-15 02:18:13 +00006069 if (!Evaluate(CoreConstResult, Info, E))
6070 return false;
6071 Result = CoreConstResult.toAPValue();
6072 return true;
Richard Smith69c2c502011-11-04 05:33:44 +00006073}
6074
Richard Smithf48fdb02011-12-09 22:58:01 +00006075/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6076/// lvalue-to-rvalue cast if it is an lvalue.
6077static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006078 if (!CheckLiteralType(Info, E))
6079 return false;
6080
Richard Smithf48fdb02011-12-09 22:58:01 +00006081 CCValue Value;
6082 if (!::Evaluate(Value, Info, E))
6083 return false;
6084
6085 if (E->isGLValue()) {
6086 LValue LV;
6087 LV.setFrom(Value);
6088 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
6089 return false;
6090 }
6091
6092 // Check this core constant expression is a constant expression, and if so,
6093 // convert it to one.
Richard Smith83587db2012-02-15 02:18:13 +00006094 Result = Value.toAPValue();
6095 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006096}
Richard Smithc49bd112011-10-28 17:51:58 +00006097
Richard Smith51f47082011-10-29 00:50:52 +00006098/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006099/// any crazy technique (that has nothing to do with language standards) that
6100/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006101/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6102/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006103bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006104 // Fast-path evaluations of integer literals, since we sometimes see files
6105 // containing vast quantities of these.
6106 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6107 Result.Val = APValue(APSInt(L->getValue(),
6108 L->getType()->isUnsignedIntegerType()));
6109 return true;
6110 }
6111
Richard Smith2d6a5672012-01-14 04:30:29 +00006112 // FIXME: Evaluating values of large array and record types can cause
6113 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006114 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6115 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006116 return false;
6117
Richard Smithf48fdb02011-12-09 22:58:01 +00006118 EvalInfo Info(Ctx, Result);
6119 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006120}
6121
Jay Foad4ba2a172011-01-12 09:06:06 +00006122bool Expr::EvaluateAsBooleanCondition(bool &Result,
6123 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006124 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006125 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00006126 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
6127 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00006128 Result);
John McCallcd7a4452010-01-05 23:42:56 +00006129}
6130
Richard Smith80d4b552011-12-28 19:48:30 +00006131bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6132 SideEffectsKind AllowSideEffects) const {
6133 if (!getType()->isIntegralOrEnumerationType())
6134 return false;
6135
Richard Smithc49bd112011-10-28 17:51:58 +00006136 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006137 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6138 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006139 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006140
Richard Smithc49bd112011-10-28 17:51:58 +00006141 Result = ExprResult.Val.getInt();
6142 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006143}
6144
Jay Foad4ba2a172011-01-12 09:06:06 +00006145bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006146 EvalInfo Info(Ctx, Result);
6147
John McCallefdb83e2010-05-07 21:00:08 +00006148 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006149 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6150 !CheckLValueConstantExpression(Info, getExprLoc(),
6151 Ctx.getLValueReferenceType(getType()), LV))
6152 return false;
6153
6154 CCValue Tmp;
6155 LV.moveInto(Tmp);
6156 Result.Val = Tmp.toAPValue();
6157 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006158}
6159
Richard Smith099e7f62011-12-19 06:19:21 +00006160bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6161 const VarDecl *VD,
6162 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006163 // FIXME: Evaluating initializers for large array and record types can cause
6164 // performance problems. Only do so in C++11 for now.
6165 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6166 !Ctx.getLangOptions().CPlusPlus0x)
6167 return false;
6168
Richard Smith099e7f62011-12-19 06:19:21 +00006169 Expr::EvalStatus EStatus;
6170 EStatus.Diag = &Notes;
6171
6172 EvalInfo InitInfo(Ctx, EStatus);
6173 InitInfo.setEvaluatingDecl(VD, Value);
6174
6175 LValue LVal;
6176 LVal.set(VD);
6177
Richard Smith51201882011-12-30 21:15:51 +00006178 // C++11 [basic.start.init]p2:
6179 // Variables with static storage duration or thread storage duration shall be
6180 // zero-initialized before any other initialization takes place.
6181 // This behavior is not present in C.
6182 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
6183 !VD->getType()->isReferenceType()) {
6184 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006185 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6186 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006187 return false;
6188 }
6189
Richard Smith83587db2012-02-15 02:18:13 +00006190 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6191 /*AllowNonLiteralTypes=*/true) ||
6192 EStatus.HasSideEffects)
6193 return false;
6194
6195 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6196 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006197}
6198
Richard Smith51f47082011-10-29 00:50:52 +00006199/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6200/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006201bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006202 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006203 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006204}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006205
Jay Foad4ba2a172011-01-12 09:06:06 +00006206bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006207 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006208}
6209
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006210APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006211 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006212 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006213 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006214 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006215 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006216
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006217 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006218}
John McCalld905f5a2010-05-07 05:32:02 +00006219
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006220 bool Expr::EvalResult::isGlobalLValue() const {
6221 assert(Val.isLValue());
6222 return IsGlobalLValue(Val.getLValueBase());
6223 }
6224
6225
John McCalld905f5a2010-05-07 05:32:02 +00006226/// isIntegerConstantExpr - this recursive routine will test if an expression is
6227/// an integer constant expression.
6228
6229/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6230/// comma, etc
6231///
6232/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6233/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6234/// cast+dereference.
6235
6236// CheckICE - This function does the fundamental ICE checking: the returned
6237// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6238// Note that to reduce code duplication, this helper does no evaluation
6239// itself; the caller checks whether the expression is evaluatable, and
6240// in the rare cases where CheckICE actually cares about the evaluated
6241// value, it calls into Evalute.
6242//
6243// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006244// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006245// 1: This expression is not an ICE, but if it isn't evaluated, it's
6246// a legal subexpression for an ICE. This return value is used to handle
6247// the comma operator in C99 mode.
6248// 2: This expression is not an ICE, and is not a legal subexpression for one.
6249
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006250namespace {
6251
John McCalld905f5a2010-05-07 05:32:02 +00006252struct ICEDiag {
6253 unsigned Val;
6254 SourceLocation Loc;
6255
6256 public:
6257 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6258 ICEDiag() : Val(0) {}
6259};
6260
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006261}
6262
6263static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006264
6265static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6266 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006267 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006268 !EVResult.Val.isInt()) {
6269 return ICEDiag(2, E->getLocStart());
6270 }
6271 return NoDiag();
6272}
6273
6274static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6275 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006276 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006277 return ICEDiag(2, E->getLocStart());
6278 }
6279
6280 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006281#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006282#define STMT(Node, Base) case Expr::Node##Class:
6283#define EXPR(Node, Base)
6284#include "clang/AST/StmtNodes.inc"
6285 case Expr::PredefinedExprClass:
6286 case Expr::FloatingLiteralClass:
6287 case Expr::ImaginaryLiteralClass:
6288 case Expr::StringLiteralClass:
6289 case Expr::ArraySubscriptExprClass:
6290 case Expr::MemberExprClass:
6291 case Expr::CompoundAssignOperatorClass:
6292 case Expr::CompoundLiteralExprClass:
6293 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006294 case Expr::DesignatedInitExprClass:
6295 case Expr::ImplicitValueInitExprClass:
6296 case Expr::ParenListExprClass:
6297 case Expr::VAArgExprClass:
6298 case Expr::AddrLabelExprClass:
6299 case Expr::StmtExprClass:
6300 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006301 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006302 case Expr::CXXDynamicCastExprClass:
6303 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006304 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006305 case Expr::CXXNullPtrLiteralExprClass:
6306 case Expr::CXXThisExprClass:
6307 case Expr::CXXThrowExprClass:
6308 case Expr::CXXNewExprClass:
6309 case Expr::CXXDeleteExprClass:
6310 case Expr::CXXPseudoDestructorExprClass:
6311 case Expr::UnresolvedLookupExprClass:
6312 case Expr::DependentScopeDeclRefExprClass:
6313 case Expr::CXXConstructExprClass:
6314 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006315 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006316 case Expr::CXXTemporaryObjectExprClass:
6317 case Expr::CXXUnresolvedConstructExprClass:
6318 case Expr::CXXDependentScopeMemberExprClass:
6319 case Expr::UnresolvedMemberExprClass:
6320 case Expr::ObjCStringLiteralClass:
6321 case Expr::ObjCEncodeExprClass:
6322 case Expr::ObjCMessageExprClass:
6323 case Expr::ObjCSelectorExprClass:
6324 case Expr::ObjCProtocolExprClass:
6325 case Expr::ObjCIvarRefExprClass:
6326 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006327 case Expr::ObjCIsaExprClass:
6328 case Expr::ShuffleVectorExprClass:
6329 case Expr::BlockExprClass:
6330 case Expr::BlockDeclRefExprClass:
6331 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006332 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006333 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006334 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006335 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006336 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006337 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006338 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006339 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006340 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006341 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006342 return ICEDiag(2, E->getLocStart());
6343
Douglas Gregoree8aff02011-01-04 17:33:58 +00006344 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006345 case Expr::GNUNullExprClass:
6346 // GCC considers the GNU __null value to be an integral constant expression.
6347 return NoDiag();
6348
John McCall91a57552011-07-15 05:09:51 +00006349 case Expr::SubstNonTypeTemplateParmExprClass:
6350 return
6351 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6352
John McCalld905f5a2010-05-07 05:32:02 +00006353 case Expr::ParenExprClass:
6354 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006355 case Expr::GenericSelectionExprClass:
6356 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006357 case Expr::IntegerLiteralClass:
6358 case Expr::CharacterLiteralClass:
6359 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006360 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006361 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006362 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006363 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006364 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006365 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006366 return NoDiag();
6367 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006368 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006369 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6370 // constant expressions, but they can never be ICEs because an ICE cannot
6371 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006372 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006373 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006374 return CheckEvalInICE(E, Ctx);
6375 return ICEDiag(2, E->getLocStart());
6376 }
6377 case Expr::DeclRefExprClass:
6378 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6379 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00006380 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006381 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
6382
6383 // Parameter variables are never constants. Without this check,
6384 // getAnyInitializer() can find a default argument, which leads
6385 // to chaos.
6386 if (isa<ParmVarDecl>(D))
6387 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6388
6389 // C++ 7.1.5.1p2
6390 // A variable of non-volatile const-qualified integral or enumeration
6391 // type initialized by an ICE can be used in ICEs.
6392 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006393 if (!Dcl->getType()->isIntegralOrEnumerationType())
6394 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6395
Richard Smith099e7f62011-12-19 06:19:21 +00006396 const VarDecl *VD;
6397 // Look for a declaration of this variable that has an initializer, and
6398 // check whether it is an ICE.
6399 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6400 return NoDiag();
6401 else
6402 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006403 }
6404 }
6405 return ICEDiag(2, E->getLocStart());
6406 case Expr::UnaryOperatorClass: {
6407 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6408 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006409 case UO_PostInc:
6410 case UO_PostDec:
6411 case UO_PreInc:
6412 case UO_PreDec:
6413 case UO_AddrOf:
6414 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006415 // C99 6.6/3 allows increment and decrement within unevaluated
6416 // subexpressions of constant expressions, but they can never be ICEs
6417 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006418 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006419 case UO_Extension:
6420 case UO_LNot:
6421 case UO_Plus:
6422 case UO_Minus:
6423 case UO_Not:
6424 case UO_Real:
6425 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006426 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006427 }
6428
6429 // OffsetOf falls through here.
6430 }
6431 case Expr::OffsetOfExprClass: {
6432 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006433 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006434 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006435 // compliance: we should warn earlier for offsetof expressions with
6436 // array subscripts that aren't ICEs, and if the array subscripts
6437 // are ICEs, the value of the offsetof must be an integer constant.
6438 return CheckEvalInICE(E, Ctx);
6439 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006440 case Expr::UnaryExprOrTypeTraitExprClass: {
6441 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6442 if ((Exp->getKind() == UETT_SizeOf) &&
6443 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006444 return ICEDiag(2, E->getLocStart());
6445 return NoDiag();
6446 }
6447 case Expr::BinaryOperatorClass: {
6448 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6449 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006450 case BO_PtrMemD:
6451 case BO_PtrMemI:
6452 case BO_Assign:
6453 case BO_MulAssign:
6454 case BO_DivAssign:
6455 case BO_RemAssign:
6456 case BO_AddAssign:
6457 case BO_SubAssign:
6458 case BO_ShlAssign:
6459 case BO_ShrAssign:
6460 case BO_AndAssign:
6461 case BO_XorAssign:
6462 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006463 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6464 // constant expressions, but they can never be ICEs because an ICE cannot
6465 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006466 return ICEDiag(2, E->getLocStart());
6467
John McCall2de56d12010-08-25 11:45:40 +00006468 case BO_Mul:
6469 case BO_Div:
6470 case BO_Rem:
6471 case BO_Add:
6472 case BO_Sub:
6473 case BO_Shl:
6474 case BO_Shr:
6475 case BO_LT:
6476 case BO_GT:
6477 case BO_LE:
6478 case BO_GE:
6479 case BO_EQ:
6480 case BO_NE:
6481 case BO_And:
6482 case BO_Xor:
6483 case BO_Or:
6484 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006485 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6486 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006487 if (Exp->getOpcode() == BO_Div ||
6488 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006489 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006490 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006491 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006492 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006493 if (REval == 0)
6494 return ICEDiag(1, E->getLocStart());
6495 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006496 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006497 if (LEval.isMinSignedValue())
6498 return ICEDiag(1, E->getLocStart());
6499 }
6500 }
6501 }
John McCall2de56d12010-08-25 11:45:40 +00006502 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006503 if (Ctx.getLangOptions().C99) {
6504 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6505 // if it isn't evaluated.
6506 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6507 return ICEDiag(1, E->getLocStart());
6508 } else {
6509 // In both C89 and C++, commas in ICEs are illegal.
6510 return ICEDiag(2, E->getLocStart());
6511 }
6512 }
6513 if (LHSResult.Val >= RHSResult.Val)
6514 return LHSResult;
6515 return RHSResult;
6516 }
John McCall2de56d12010-08-25 11:45:40 +00006517 case BO_LAnd:
6518 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006519 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6520 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6521 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6522 // Rare case where the RHS has a comma "side-effect"; we need
6523 // to actually check the condition to see whether the side
6524 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006525 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006526 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006527 return RHSResult;
6528 return NoDiag();
6529 }
6530
6531 if (LHSResult.Val >= RHSResult.Val)
6532 return LHSResult;
6533 return RHSResult;
6534 }
6535 }
6536 }
6537 case Expr::ImplicitCastExprClass:
6538 case Expr::CStyleCastExprClass:
6539 case Expr::CXXFunctionalCastExprClass:
6540 case Expr::CXXStaticCastExprClass:
6541 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006542 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006543 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006544 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006545 if (isa<ExplicitCastExpr>(E)) {
6546 if (const FloatingLiteral *FL
6547 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6548 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6549 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6550 APSInt IgnoredVal(DestWidth, !DestSigned);
6551 bool Ignored;
6552 // If the value does not fit in the destination type, the behavior is
6553 // undefined, so we are not required to treat it as a constant
6554 // expression.
6555 if (FL->getValue().convertToInteger(IgnoredVal,
6556 llvm::APFloat::rmTowardZero,
6557 &Ignored) & APFloat::opInvalidOp)
6558 return ICEDiag(2, E->getLocStart());
6559 return NoDiag();
6560 }
6561 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006562 switch (cast<CastExpr>(E)->getCastKind()) {
6563 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006564 case CK_AtomicToNonAtomic:
6565 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006566 case CK_NoOp:
6567 case CK_IntegralToBoolean:
6568 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006569 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006570 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006571 return ICEDiag(2, E->getLocStart());
6572 }
John McCalld905f5a2010-05-07 05:32:02 +00006573 }
John McCall56ca35d2011-02-17 10:25:35 +00006574 case Expr::BinaryConditionalOperatorClass: {
6575 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6576 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6577 if (CommonResult.Val == 2) return CommonResult;
6578 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6579 if (FalseResult.Val == 2) return FalseResult;
6580 if (CommonResult.Val == 1) return CommonResult;
6581 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006582 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006583 return FalseResult;
6584 }
John McCalld905f5a2010-05-07 05:32:02 +00006585 case Expr::ConditionalOperatorClass: {
6586 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6587 // If the condition (ignoring parens) is a __builtin_constant_p call,
6588 // then only the true side is actually considered in an integer constant
6589 // expression, and it is fully evaluated. This is an important GNU
6590 // extension. See GCC PR38377 for discussion.
6591 if (const CallExpr *CallCE
6592 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006593 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6594 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006595 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006596 if (CondResult.Val == 2)
6597 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006598
Richard Smithf48fdb02011-12-09 22:58:01 +00006599 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6600 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006601
John McCalld905f5a2010-05-07 05:32:02 +00006602 if (TrueResult.Val == 2)
6603 return TrueResult;
6604 if (FalseResult.Val == 2)
6605 return FalseResult;
6606 if (CondResult.Val == 1)
6607 return CondResult;
6608 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6609 return NoDiag();
6610 // Rare case where the diagnostics depend on which side is evaluated
6611 // Note that if we get here, CondResult is 0, and at least one of
6612 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006613 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006614 return FalseResult;
6615 }
6616 return TrueResult;
6617 }
6618 case Expr::CXXDefaultArgExprClass:
6619 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6620 case Expr::ChooseExprClass: {
6621 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6622 }
6623 }
6624
David Blaikie30263482012-01-20 21:50:17 +00006625 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006626}
6627
Richard Smithf48fdb02011-12-09 22:58:01 +00006628/// Evaluate an expression as a C++11 integral constant expression.
6629static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6630 const Expr *E,
6631 llvm::APSInt *Value,
6632 SourceLocation *Loc) {
6633 if (!E->getType()->isIntegralOrEnumerationType()) {
6634 if (Loc) *Loc = E->getExprLoc();
6635 return false;
6636 }
6637
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006638 APValue Result;
6639 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006640 return false;
6641
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006642 assert(Result.isInt() && "pointer cast to int is not an ICE");
6643 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006644 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006645}
6646
Richard Smithdd1f29b2011-12-12 09:28:41 +00006647bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006648 if (Ctx.getLangOptions().CPlusPlus0x)
6649 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6650
John McCalld905f5a2010-05-07 05:32:02 +00006651 ICEDiag d = CheckICE(this, Ctx);
6652 if (d.Val != 0) {
6653 if (Loc) *Loc = d.Loc;
6654 return false;
6655 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006656 return true;
6657}
6658
6659bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6660 SourceLocation *Loc, bool isEvaluated) const {
6661 if (Ctx.getLangOptions().CPlusPlus0x)
6662 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6663
6664 if (!isIntegerConstantExpr(Ctx, Loc))
6665 return false;
6666 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006667 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006668 return true;
6669}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006670
Richard Smith70488e22012-02-14 21:38:30 +00006671bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6672 return CheckICE(this, Ctx).Val == 0;
6673}
6674
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006675bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6676 SourceLocation *Loc) const {
6677 // We support this checking in C++98 mode in order to diagnose compatibility
6678 // issues.
6679 assert(Ctx.getLangOptions().CPlusPlus);
6680
Richard Smith70488e22012-02-14 21:38:30 +00006681 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006682 Expr::EvalStatus Status;
6683 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6684 Status.Diag = &Diags;
6685 EvalInfo Info(Ctx, Status);
6686
6687 APValue Scratch;
6688 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6689
6690 if (!Diags.empty()) {
6691 IsConstExpr = false;
6692 if (Loc) *Loc = Diags[0].first;
6693 } else if (!IsConstExpr) {
6694 // FIXME: This shouldn't happen.
6695 if (Loc) *Loc = getExprLoc();
6696 }
6697
6698 return IsConstExpr;
6699}
Richard Smith745f5142012-01-27 01:14:48 +00006700
6701bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6702 llvm::SmallVectorImpl<
6703 PartialDiagnosticAt> &Diags) {
6704 // FIXME: It would be useful to check constexpr function templates, but at the
6705 // moment the constant expression evaluator cannot cope with the non-rigorous
6706 // ASTs which we build for dependent expressions.
6707 if (FD->isDependentContext())
6708 return true;
6709
6710 Expr::EvalStatus Status;
6711 Status.Diag = &Diags;
6712
6713 EvalInfo Info(FD->getASTContext(), Status);
6714 Info.CheckingPotentialConstantExpression = true;
6715
6716 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6717 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6718
6719 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6720 // is a temporary being used as the 'this' pointer.
6721 LValue This;
6722 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006723 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006724
Richard Smith745f5142012-01-27 01:14:48 +00006725 ArrayRef<const Expr*> Args;
6726
6727 SourceLocation Loc = FD->getLocation();
6728
6729 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Richard Smith83587db2012-02-15 02:18:13 +00006730 APValue Scratch;
Richard Smith745f5142012-01-27 01:14:48 +00006731 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith83587db2012-02-15 02:18:13 +00006732 } else {
6733 CCValue Scratch;
Richard Smith745f5142012-01-27 01:14:48 +00006734 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6735 Args, FD->getBody(), Info, Scratch);
Richard Smith83587db2012-02-15 02:18:13 +00006736 }
Richard Smith745f5142012-01-27 01:14:48 +00006737
6738 return Diags.empty();
6739}