blob: 44e41864f0b3a373fe3efb276a0a93c609fbe58d [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;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000409
Richard Smithbd552ef2011-10-31 05:52:43 +0000410 /// 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");
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001208 CCValue Val;
1209 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001210 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001211 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() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002228 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2229 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002230 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
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004122 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4123 return Success(E->getValue(), E);
4124 }
4125
John Wiegley21ff2e52011-04-28 00:16:57 +00004126 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4127 return Success(E->getValue(), E);
4128 }
4129
John Wiegley55262202011-04-25 06:54:41 +00004130 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4131 return Success(E->getValue(), E);
4132 }
4133
Eli Friedman722c7172009-02-28 03:59:05 +00004134 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004135 bool VisitUnaryImag(const UnaryOperator *E);
4136
Sebastian Redl295995c2010-09-10 20:55:47 +00004137 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004138 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004139
Chris Lattnerfcee0012008-07-11 21:24:13 +00004140private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004141 CharUnits GetAlignOfExpr(const Expr *E);
4142 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004143 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004144 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004145 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004146};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004147} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004148
Richard Smithc49bd112011-10-28 17:51:58 +00004149/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4150/// produce either the integer value or a pointer.
4151///
4152/// GCC has a heinous extension which folds casts between pointer types and
4153/// pointer-sized integral types. We support this by allowing the evaluation of
4154/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4155/// Some simple arithmetic on such values is supported (they are treated much
4156/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00004157static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004158 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004159 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004160 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004161}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004162
Richard Smithf48fdb02011-12-09 22:58:01 +00004163static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004164 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004165 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004166 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004167 if (!Val.isInt()) {
4168 // FIXME: It would be better to produce the diagnostic for casting
4169 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00004170 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004171 return false;
4172 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004173 Result = Val.getInt();
4174 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004175}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004176
Richard Smithf48fdb02011-12-09 22:58:01 +00004177/// Check whether the given declaration can be directly converted to an integral
4178/// rvalue. If not, no diagnostic is produced; there are other things we can
4179/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004180bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004181 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004182 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004183 // Check for signedness/width mismatches between E type and ECD value.
4184 bool SameSign = (ECD->getInitVal().isSigned()
4185 == E->getType()->isSignedIntegerOrEnumerationType());
4186 bool SameWidth = (ECD->getInitVal().getBitWidth()
4187 == Info.Ctx.getIntWidth(E->getType()));
4188 if (SameSign && SameWidth)
4189 return Success(ECD->getInitVal(), E);
4190 else {
4191 // Get rid of mismatch (otherwise Success assertions will fail)
4192 // by computing a new value matching the type of E.
4193 llvm::APSInt Val = ECD->getInitVal();
4194 if (!SameSign)
4195 Val.setIsSigned(!ECD->getInitVal().isSigned());
4196 if (!SameWidth)
4197 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4198 return Success(Val, E);
4199 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004200 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004201 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004202}
4203
Chris Lattnera4d55d82008-10-06 06:40:35 +00004204/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4205/// as GCC.
4206static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4207 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004208 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004209 enum gcc_type_class {
4210 no_type_class = -1,
4211 void_type_class, integer_type_class, char_type_class,
4212 enumeral_type_class, boolean_type_class,
4213 pointer_type_class, reference_type_class, offset_type_class,
4214 real_type_class, complex_type_class,
4215 function_type_class, method_type_class,
4216 record_type_class, union_type_class,
4217 array_type_class, string_type_class,
4218 lang_type_class
4219 };
Mike Stump1eb44332009-09-09 15:08:12 +00004220
4221 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004222 // ideal, however it is what gcc does.
4223 if (E->getNumArgs() == 0)
4224 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004225
Chris Lattnera4d55d82008-10-06 06:40:35 +00004226 QualType ArgTy = E->getArg(0)->getType();
4227 if (ArgTy->isVoidType())
4228 return void_type_class;
4229 else if (ArgTy->isEnumeralType())
4230 return enumeral_type_class;
4231 else if (ArgTy->isBooleanType())
4232 return boolean_type_class;
4233 else if (ArgTy->isCharType())
4234 return string_type_class; // gcc doesn't appear to use char_type_class
4235 else if (ArgTy->isIntegerType())
4236 return integer_type_class;
4237 else if (ArgTy->isPointerType())
4238 return pointer_type_class;
4239 else if (ArgTy->isReferenceType())
4240 return reference_type_class;
4241 else if (ArgTy->isRealType())
4242 return real_type_class;
4243 else if (ArgTy->isComplexType())
4244 return complex_type_class;
4245 else if (ArgTy->isFunctionType())
4246 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004247 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004248 return record_type_class;
4249 else if (ArgTy->isUnionType())
4250 return union_type_class;
4251 else if (ArgTy->isArrayType())
4252 return array_type_class;
4253 else if (ArgTy->isUnionType())
4254 return union_type_class;
4255 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004256 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004257}
4258
Richard Smith80d4b552011-12-28 19:48:30 +00004259/// EvaluateBuiltinConstantPForLValue - Determine the result of
4260/// __builtin_constant_p when applied to the given lvalue.
4261///
4262/// An lvalue is only "constant" if it is a pointer or reference to the first
4263/// character of a string literal.
4264template<typename LValue>
4265static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4266 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
4267 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4268}
4269
4270/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4271/// GCC as we can manage.
4272static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4273 QualType ArgType = Arg->getType();
4274
4275 // __builtin_constant_p always has one operand. The rules which gcc follows
4276 // are not precisely documented, but are as follows:
4277 //
4278 // - If the operand is of integral, floating, complex or enumeration type,
4279 // and can be folded to a known value of that type, it returns 1.
4280 // - If the operand and can be folded to a pointer to the first character
4281 // of a string literal (or such a pointer cast to an integral type), it
4282 // returns 1.
4283 //
4284 // Otherwise, it returns 0.
4285 //
4286 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4287 // its support for this does not currently work.
4288 if (ArgType->isIntegralOrEnumerationType()) {
4289 Expr::EvalResult Result;
4290 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4291 return false;
4292
4293 APValue &V = Result.Val;
4294 if (V.getKind() == APValue::Int)
4295 return true;
4296
4297 return EvaluateBuiltinConstantPForLValue(V);
4298 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4299 return Arg->isEvaluatable(Ctx);
4300 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4301 LValue LV;
4302 Expr::EvalStatus Status;
4303 EvalInfo Info(Ctx, Status);
4304 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4305 : EvaluatePointer(Arg, LV, Info)) &&
4306 !Status.HasSideEffects)
4307 return EvaluateBuiltinConstantPForLValue(LV);
4308 }
4309
4310 // Anything else isn't considered to be sufficiently constant.
4311 return false;
4312}
4313
John McCall42c8f872010-05-10 23:27:23 +00004314/// Retrieves the "underlying object type" of the given expression,
4315/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004316QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4317 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4318 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004319 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004320 } else if (const Expr *E = B.get<const Expr*>()) {
4321 if (isa<CompoundLiteralExpr>(E))
4322 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004323 }
4324
4325 return QualType();
4326}
4327
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004328bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004329 // TODO: Perhaps we should let LLVM lower this?
4330 LValue Base;
4331 if (!EvaluatePointer(E->getArg(0), Base, Info))
4332 return false;
4333
4334 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004335 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004336
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004337 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004338 if (T.isNull() ||
4339 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004340 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004341 T->isVariablyModifiedType() ||
4342 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004343 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004344
4345 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4346 CharUnits Offset = Base.getLValueOffset();
4347
4348 if (!Offset.isNegative() && Offset <= Size)
4349 Size -= Offset;
4350 else
4351 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004352 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004353}
4354
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004355bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004356 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004357 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004358 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004359
4360 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004361 if (TryEvaluateBuiltinObjectSize(E))
4362 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004363
Eric Christopherb2aaf512010-01-19 22:58:35 +00004364 // If evaluating the argument has side-effects we can't determine
4365 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004366 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004367 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004368 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004369 return Success(0, E);
4370 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004371
Richard Smithf48fdb02011-12-09 22:58:01 +00004372 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004373 }
4374
Chris Lattner019f4e82008-10-06 05:28:25 +00004375 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004376 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004377
Richard Smith80d4b552011-12-28 19:48:30 +00004378 case Builtin::BI__builtin_constant_p:
4379 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004380
Chris Lattner21fb98e2009-09-23 06:06:36 +00004381 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004382 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004383 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004384 return Success(Operand, E);
4385 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004386
4387 case Builtin::BI__builtin_expect:
4388 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004389
Douglas Gregor5726d402010-09-10 06:27:15 +00004390 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004391 // A call to strlen is not a constant expression.
4392 if (Info.getLangOpts().CPlusPlus0x)
4393 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4394 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4395 else
4396 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4397 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004398 case Builtin::BI__builtin_strlen:
4399 // As an extension, we support strlen() and __builtin_strlen() as constant
4400 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004401 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004402 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4403 // The string literal may have embedded null characters. Find the first
4404 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004405 StringRef Str = S->getString();
4406 StringRef::size_type Pos = Str.find(0);
4407 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004408 Str = Str.substr(0, Pos);
4409
4410 return Success(Str.size(), E);
4411 }
4412
Richard Smithf48fdb02011-12-09 22:58:01 +00004413 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004414
4415 case Builtin::BI__atomic_is_lock_free: {
4416 APSInt SizeVal;
4417 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4418 return false;
4419
4420 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4421 // of two less than the maximum inline atomic width, we know it is
4422 // lock-free. If the size isn't a power of two, or greater than the
4423 // maximum alignment where we promote atomics, we know it is not lock-free
4424 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4425 // the answer can only be determined at runtime; for example, 16-byte
4426 // atomics have lock-free implementations on some, but not all,
4427 // x86-64 processors.
4428
4429 // Check power-of-two.
4430 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4431 if (!Size.isPowerOfTwo())
4432#if 0
4433 // FIXME: Suppress this folding until the ABI for the promotion width
4434 // settles.
4435 return Success(0, E);
4436#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004437 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004438#endif
4439
4440#if 0
4441 // Check against promotion width.
4442 // FIXME: Suppress this folding until the ABI for the promotion width
4443 // settles.
4444 unsigned PromoteWidthBits =
4445 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4446 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4447 return Success(0, E);
4448#endif
4449
4450 // Check against inlining width.
4451 unsigned InlineWidthBits =
4452 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4453 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4454 return Success(1, E);
4455
Richard Smithf48fdb02011-12-09 22:58:01 +00004456 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004457 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004458 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004459}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004460
Richard Smith625b8072011-10-31 01:37:14 +00004461static bool HasSameBase(const LValue &A, const LValue &B) {
4462 if (!A.getLValueBase())
4463 return !B.getLValueBase();
4464 if (!B.getLValueBase())
4465 return false;
4466
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004467 if (A.getLValueBase().getOpaqueValue() !=
4468 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004469 const Decl *ADecl = GetLValueBaseDecl(A);
4470 if (!ADecl)
4471 return false;
4472 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004473 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004474 return false;
4475 }
4476
4477 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004478 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004479}
4480
Richard Smith7b48a292012-02-01 05:53:12 +00004481/// Perform the given integer operation, which is known to need at most BitWidth
4482/// bits, and check for overflow in the original type (if that type was not an
4483/// unsigned type).
4484template<typename Operation>
4485static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4486 const APSInt &LHS, const APSInt &RHS,
4487 unsigned BitWidth, Operation Op) {
4488 if (LHS.isUnsigned())
4489 return Op(LHS, RHS);
4490
4491 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4492 APSInt Result = Value.trunc(LHS.getBitWidth());
4493 if (Result.extend(BitWidth) != Value)
4494 HandleOverflow(Info, E, Value, E->getType());
4495 return Result;
4496}
4497
Chris Lattnerb542afe2008-07-11 19:10:17 +00004498bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004499 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004500 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004501
John McCall2de56d12010-08-25 11:45:40 +00004502 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004503 VisitIgnoredValue(E->getLHS());
4504 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004505 }
4506
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004507 if (E->isLogicalOp()) {
4508 // These need to be handled specially because the operands aren't
4509 // necessarily integral nor evaluated.
4510 bool lhsResult, rhsResult;
4511
4512 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
4513 // We were able to evaluate the LHS, see if we can get away with not
4514 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
4515 if (lhsResult == (E->getOpcode() == BO_LOr))
4516 return Success(lhsResult, E);
4517
4518 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4519 if (E->getOpcode() == BO_LOr)
4520 return Success(lhsResult || rhsResult, E);
4521 else
4522 return Success(lhsResult && rhsResult, E);
4523 }
4524 } else {
4525 // Since we weren't able to evaluate the left hand side, it
4526 // must have had side effects.
4527 Info.EvalStatus.HasSideEffects = true;
4528
4529 // Suppress diagnostics from this arm.
4530 SpeculativeEvaluationRAII Speculative(Info);
4531 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4532 // We can't evaluate the LHS; however, sometimes the result
4533 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4534 if (rhsResult == (E->getOpcode() == BO_LOr))
4535 return Success(rhsResult, E);
4536 }
4537 }
4538
4539 return false;
4540 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004541
Anders Carlsson286f85e2008-11-16 07:17:21 +00004542 QualType LHSTy = E->getLHS()->getType();
4543 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004544
4545 if (LHSTy->isAnyComplexType()) {
4546 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004547 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004548
Richard Smith745f5142012-01-27 01:14:48 +00004549 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4550 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004551 return false;
4552
Richard Smith745f5142012-01-27 01:14:48 +00004553 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004554 return false;
4555
4556 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004557 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004558 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004559 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004560 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4561
John McCall2de56d12010-08-25 11:45:40 +00004562 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004563 return Success((CR_r == APFloat::cmpEqual &&
4564 CR_i == APFloat::cmpEqual), E);
4565 else {
John McCall2de56d12010-08-25 11:45:40 +00004566 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004567 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004568 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004569 CR_r == APFloat::cmpLessThan ||
4570 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004571 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004572 CR_i == APFloat::cmpLessThan ||
4573 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004574 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004575 } else {
John McCall2de56d12010-08-25 11:45:40 +00004576 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004577 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4578 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4579 else {
John McCall2de56d12010-08-25 11:45:40 +00004580 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004581 "Invalid compex comparison.");
4582 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4583 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4584 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004585 }
4586 }
Mike Stump1eb44332009-09-09 15:08:12 +00004587
Anders Carlsson286f85e2008-11-16 07:17:21 +00004588 if (LHSTy->isRealFloatingType() &&
4589 RHSTy->isRealFloatingType()) {
4590 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004591
Richard Smith745f5142012-01-27 01:14:48 +00004592 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4593 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004594 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004595
Richard Smith745f5142012-01-27 01:14:48 +00004596 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004597 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004598
Anders Carlsson286f85e2008-11-16 07:17:21 +00004599 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004600
Anders Carlsson286f85e2008-11-16 07:17:21 +00004601 switch (E->getOpcode()) {
4602 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004603 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004604 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004605 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004606 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004607 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004608 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004609 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004610 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004611 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004612 E);
John McCall2de56d12010-08-25 11:45:40 +00004613 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004614 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004615 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004616 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004617 || CR == APFloat::cmpLessThan
4618 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004619 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004620 }
Mike Stump1eb44332009-09-09 15:08:12 +00004621
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004622 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004623 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004624 LValue LHSValue, RHSValue;
4625
4626 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4627 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004628 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004629
Richard Smith745f5142012-01-27 01:14:48 +00004630 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004631 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004632
Richard Smith625b8072011-10-31 01:37:14 +00004633 // Reject differing bases from the normal codepath; we special-case
4634 // comparisons to null.
4635 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004636 if (E->getOpcode() == BO_Sub) {
4637 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004638 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4639 return false;
4640 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4641 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4642 if (!LHSExpr || !RHSExpr)
4643 return false;
4644 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4645 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4646 if (!LHSAddrExpr || !RHSAddrExpr)
4647 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004648 // Make sure both labels come from the same function.
4649 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4650 RHSAddrExpr->getLabel()->getDeclContext())
4651 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004652 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4653 return true;
4654 }
Richard Smith9e36b532011-10-31 05:11:32 +00004655 // Inequalities and subtractions between unrelated pointers have
4656 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004657 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004658 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004659 // A constant address may compare equal to the address of a symbol.
4660 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004661 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004662 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4663 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004664 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004665 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004666 // distinct addresses. In clang, the result of such a comparison is
4667 // unspecified, so it is not a constant expression. However, we do know
4668 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004669 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4670 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004671 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004672 // We can't tell whether weak symbols will end up pointing to the same
4673 // object.
4674 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004675 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004676 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004677 // (Note that clang defaults to -fmerge-all-constants, which can
4678 // lead to inconsistent results for comparisons involving the address
4679 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004680 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004681 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004682
Richard Smith15efc4d2012-02-01 08:10:20 +00004683 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4684 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4685
Richard Smithf15fda02012-02-02 01:16:57 +00004686 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4687 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4688
John McCall2de56d12010-08-25 11:45:40 +00004689 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004690 // C++11 [expr.add]p6:
4691 // Unless both pointers point to elements of the same array object, or
4692 // one past the last element of the array object, the behavior is
4693 // undefined.
4694 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4695 !AreElementsOfSameArray(getType(LHSValue.Base),
4696 LHSDesignator, RHSDesignator))
4697 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4698
Chris Lattner4992bdd2010-04-20 17:13:14 +00004699 QualType Type = E->getLHS()->getType();
4700 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004701
Richard Smith180f4792011-11-10 06:34:14 +00004702 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004703 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004704 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004705
Richard Smith15efc4d2012-02-01 08:10:20 +00004706 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4707 // and produce incorrect results when it overflows. Such behavior
4708 // appears to be non-conforming, but is common, so perhaps we should
4709 // assume the standard intended for such cases to be undefined behavior
4710 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004711
Richard Smith15efc4d2012-02-01 08:10:20 +00004712 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4713 // overflow in the final conversion to ptrdiff_t.
4714 APSInt LHS(
4715 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4716 APSInt RHS(
4717 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4718 APSInt ElemSize(
4719 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4720 APSInt TrueResult = (LHS - RHS) / ElemSize;
4721 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4722
4723 if (Result.extend(65) != TrueResult)
4724 HandleOverflow(Info, E, TrueResult, E->getType());
4725 return Success(Result, E);
4726 }
Richard Smith82f28582012-01-31 06:41:30 +00004727
4728 // C++11 [expr.rel]p3:
4729 // Pointers to void (after pointer conversions) can be compared, with a
4730 // result defined as follows: If both pointers represent the same
4731 // address or are both the null pointer value, the result is true if the
4732 // operator is <= or >= and false otherwise; otherwise the result is
4733 // unspecified.
4734 // We interpret this as applying to pointers to *cv* void.
4735 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004736 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004737 CCEDiag(E, diag::note_constexpr_void_comparison);
4738
Richard Smithf15fda02012-02-02 01:16:57 +00004739 // C++11 [expr.rel]p2:
4740 // - If two pointers point to non-static data members of the same object,
4741 // or to subobjects or array elements fo such members, recursively, the
4742 // pointer to the later declared member compares greater provided the
4743 // two members have the same access control and provided their class is
4744 // not a union.
4745 // [...]
4746 // - Otherwise pointer comparisons are unspecified.
4747 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4748 E->isRelationalOp()) {
4749 bool WasArrayIndex;
4750 unsigned Mismatch =
4751 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4752 RHSDesignator, WasArrayIndex);
4753 // At the point where the designators diverge, the comparison has a
4754 // specified value if:
4755 // - we are comparing array indices
4756 // - we are comparing fields of a union, or fields with the same access
4757 // Otherwise, the result is unspecified and thus the comparison is not a
4758 // constant expression.
4759 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4760 Mismatch < RHSDesignator.Entries.size()) {
4761 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4762 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4763 if (!LF && !RF)
4764 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4765 else if (!LF)
4766 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4767 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4768 << RF->getParent() << RF;
4769 else if (!RF)
4770 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4771 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4772 << LF->getParent() << LF;
4773 else if (!LF->getParent()->isUnion() &&
4774 LF->getAccess() != RF->getAccess())
4775 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4776 << LF << LF->getAccess() << RF << RF->getAccess()
4777 << LF->getParent();
4778 }
4779 }
4780
Richard Smith625b8072011-10-31 01:37:14 +00004781 switch (E->getOpcode()) {
4782 default: llvm_unreachable("missing comparison operator");
4783 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4784 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4785 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4786 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4787 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4788 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004789 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004790 }
4791 }
Richard Smithb02e4622012-02-01 01:42:44 +00004792
4793 if (LHSTy->isMemberPointerType()) {
4794 assert(E->isEqualityOp() && "unexpected member pointer operation");
4795 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4796
4797 MemberPtr LHSValue, RHSValue;
4798
4799 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4800 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4801 return false;
4802
4803 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4804 return false;
4805
4806 // C++11 [expr.eq]p2:
4807 // If both operands are null, they compare equal. Otherwise if only one is
4808 // null, they compare unequal.
4809 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4810 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4811 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4812 }
4813
4814 // Otherwise if either is a pointer to a virtual member function, the
4815 // result is unspecified.
4816 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4817 if (MD->isVirtual())
4818 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4819 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4820 if (MD->isVirtual())
4821 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4822
4823 // Otherwise they compare equal if and only if they would refer to the
4824 // same member of the same most derived object or the same subobject if
4825 // they were dereferenced with a hypothetical object of the associated
4826 // class type.
4827 bool Equal = LHSValue == RHSValue;
4828 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4829 }
4830
Richard Smith26f2cac2012-02-14 22:35:28 +00004831 if (LHSTy->isNullPtrType()) {
4832 assert(E->isComparisonOp() && "unexpected nullptr operation");
4833 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
4834 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
4835 // are compared, the result is true of the operator is <=, >= or ==, and
4836 // false otherwise.
4837 BinaryOperator::Opcode Opcode = E->getOpcode();
4838 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
4839 }
4840
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004841 if (!LHSTy->isIntegralOrEnumerationType() ||
4842 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004843 // We can't continue from here for non-integral types.
4844 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004845 }
4846
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004847 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004848 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004849
4850 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4851 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004852 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004853
Richard Smith745f5142012-01-27 01:14:48 +00004854 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004855 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004856
Richard Smith47a1eed2011-10-29 20:57:55 +00004857 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004858
4859 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004860 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004861 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4862 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004863 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004864 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004865 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004866 LHSVal.getLValueOffset() -= AdditionalOffset;
4867 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004868 return true;
4869 }
4870
4871 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004872 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004873 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004874 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4875 LHSVal.getInt().getZExtValue());
4876 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004877 return true;
4878 }
4879
Eli Friedman65639282012-01-04 23:13:47 +00004880 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4881 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004882 if (!LHSVal.getLValueOffset().isZero() ||
4883 !RHSVal.getLValueOffset().isZero())
4884 return false;
4885 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4886 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4887 if (!LHSExpr || !RHSExpr)
4888 return false;
4889 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4890 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4891 if (!LHSAddrExpr || !RHSAddrExpr)
4892 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004893 // Make sure both labels come from the same function.
4894 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4895 RHSAddrExpr->getLabel()->getDeclContext())
4896 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004897 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4898 return true;
4899 }
4900
Eli Friedman42edd0d2009-03-24 01:14:50 +00004901 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004902 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004903 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004904
Richard Smithc49bd112011-10-28 17:51:58 +00004905 APSInt &LHS = LHSVal.getInt();
4906 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004907
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004908 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004909 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004910 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004911 case BO_Mul:
4912 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4913 LHS.getBitWidth() * 2,
4914 std::multiplies<APSInt>()), E);
4915 case BO_Add:
4916 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4917 LHS.getBitWidth() + 1,
4918 std::plus<APSInt>()), E);
4919 case BO_Sub:
4920 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4921 LHS.getBitWidth() + 1,
4922 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004923 case BO_And: return Success(LHS & RHS, E);
4924 case BO_Xor: return Success(LHS ^ RHS, E);
4925 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004926 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004927 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004928 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004929 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004930 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4931 // actually undefined behavior in C++11 due to a language defect.
4932 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4933 LHS.isSigned() && LHS.isMinSignedValue())
4934 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4935 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004936 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004937 // During constant-folding, a negative shift is an opposite shift. Such a
4938 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004939 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004940 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004941 RHS = -RHS;
4942 goto shift_right;
4943 }
4944
4945 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004946 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4947 // shifted type.
4948 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4949 if (SA != RHS) {
4950 CCEDiag(E, diag::note_constexpr_large_shift)
4951 << RHS << E->getType() << LHS.getBitWidth();
4952 } else if (LHS.isSigned()) {
4953 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
Richard Smith925d8e72012-02-08 06:14:53 +00004954 // operand, and must not overflow the corresponding unsigned type.
Richard Smith789f9b62012-01-31 04:08:20 +00004955 if (LHS.isNegative())
4956 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
Richard Smith925d8e72012-02-08 06:14:53 +00004957 else if (LHS.countLeadingZeros() < SA)
4958 CCEDiag(E, diag::note_constexpr_lshift_discards);
Richard Smith789f9b62012-01-31 04:08:20 +00004959 }
4960
Richard Smithc49bd112011-10-28 17:51:58 +00004961 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004962 }
John McCall2de56d12010-08-25 11:45:40 +00004963 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004964 // During constant-folding, a negative shift is an opposite shift. Such a
4965 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004966 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004967 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004968 RHS = -RHS;
4969 goto shift_left;
4970 }
4971
4972 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004973 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4974 // shifted type.
4975 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4976 if (SA != RHS)
4977 CCEDiag(E, diag::note_constexpr_large_shift)
4978 << RHS << E->getType() << LHS.getBitWidth();
4979
Richard Smithc49bd112011-10-28 17:51:58 +00004980 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004981 }
Mike Stump1eb44332009-09-09 15:08:12 +00004982
Richard Smithc49bd112011-10-28 17:51:58 +00004983 case BO_LT: return Success(LHS < RHS, E);
4984 case BO_GT: return Success(LHS > RHS, E);
4985 case BO_LE: return Success(LHS <= RHS, E);
4986 case BO_GE: return Success(LHS >= RHS, E);
4987 case BO_EQ: return Success(LHS == RHS, E);
4988 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004989 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004990}
4991
Ken Dyck8b752f12010-01-27 17:10:57 +00004992CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004993 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4994 // result shall be the alignment of the referenced type."
4995 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4996 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004997
4998 // __alignof is defined to return the preferred alignment.
4999 return Info.Ctx.toCharUnitsFromBits(
5000 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005001}
5002
Ken Dyck8b752f12010-01-27 17:10:57 +00005003CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005004 E = E->IgnoreParens();
5005
5006 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005007 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005008 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005009 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5010 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005011
Chris Lattneraf707ab2009-01-24 21:53:27 +00005012 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005013 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5014 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005015
Chris Lattnere9feb472009-01-24 21:09:06 +00005016 return GetAlignOfType(E->getType());
5017}
5018
5019
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005020/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5021/// a result as the expression's type.
5022bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5023 const UnaryExprOrTypeTraitExpr *E) {
5024 switch(E->getKind()) {
5025 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005026 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005027 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005028 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005029 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005030 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005031
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005032 case UETT_VecStep: {
5033 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005034
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005035 if (Ty->isVectorType()) {
5036 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005037
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005038 // The vec_step built-in functions that take a 3-component
5039 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5040 if (n == 3)
5041 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005042
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005043 return Success(n, E);
5044 } else
5045 return Success(1, E);
5046 }
5047
5048 case UETT_SizeOf: {
5049 QualType SrcTy = E->getTypeOfArgument();
5050 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5051 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005052 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5053 SrcTy = Ref->getPointeeType();
5054
Richard Smith180f4792011-11-10 06:34:14 +00005055 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005056 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005057 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005058 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005059 }
5060 }
5061
5062 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005063}
5064
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005065bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005066 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005067 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005068 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005069 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005070 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005071 for (unsigned i = 0; i != n; ++i) {
5072 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5073 switch (ON.getKind()) {
5074 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005075 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005076 APSInt IdxResult;
5077 if (!EvaluateInteger(Idx, IdxResult, Info))
5078 return false;
5079 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5080 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005081 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005082 CurrentType = AT->getElementType();
5083 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5084 Result += IdxResult.getSExtValue() * ElementSize;
5085 break;
5086 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005087
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005088 case OffsetOfExpr::OffsetOfNode::Field: {
5089 FieldDecl *MemberDecl = ON.getField();
5090 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005091 if (!RT)
5092 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005093 RecordDecl *RD = RT->getDecl();
5094 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005095 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005096 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005097 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005098 CurrentType = MemberDecl->getType().getNonReferenceType();
5099 break;
5100 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005101
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005102 case OffsetOfExpr::OffsetOfNode::Identifier:
5103 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005104
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005105 case OffsetOfExpr::OffsetOfNode::Base: {
5106 CXXBaseSpecifier *BaseSpec = ON.getBase();
5107 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005108 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005109
5110 // Find the layout of the class whose base we are looking into.
5111 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005112 if (!RT)
5113 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005114 RecordDecl *RD = RT->getDecl();
5115 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5116
5117 // Find the base class itself.
5118 CurrentType = BaseSpec->getType();
5119 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5120 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005121 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005122
5123 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005124 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005125 break;
5126 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005127 }
5128 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005129 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005130}
5131
Chris Lattnerb542afe2008-07-11 19:10:17 +00005132bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005133 switch (E->getOpcode()) {
5134 default:
5135 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5136 // See C99 6.6p3.
5137 return Error(E);
5138 case UO_Extension:
5139 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5140 // If so, we could clear the diagnostic ID.
5141 return Visit(E->getSubExpr());
5142 case UO_Plus:
5143 // The result is just the value.
5144 return Visit(E->getSubExpr());
5145 case UO_Minus: {
5146 if (!Visit(E->getSubExpr()))
5147 return false;
5148 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005149 const APSInt &Value = Result.getInt();
5150 if (Value.isSigned() && Value.isMinSignedValue())
5151 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5152 E->getType());
5153 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005154 }
5155 case UO_Not: {
5156 if (!Visit(E->getSubExpr()))
5157 return false;
5158 if (!Result.isInt()) return Error(E);
5159 return Success(~Result.getInt(), E);
5160 }
5161 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005162 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005163 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005164 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005165 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005166 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005167 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005168}
Mike Stump1eb44332009-09-09 15:08:12 +00005169
Chris Lattner732b2232008-07-12 01:15:53 +00005170/// HandleCast - This is used to evaluate implicit or explicit casts where the
5171/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005172bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5173 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005174 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005175 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005176
Eli Friedman46a52322011-03-25 00:43:55 +00005177 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005178 case CK_BaseToDerived:
5179 case CK_DerivedToBase:
5180 case CK_UncheckedDerivedToBase:
5181 case CK_Dynamic:
5182 case CK_ToUnion:
5183 case CK_ArrayToPointerDecay:
5184 case CK_FunctionToPointerDecay:
5185 case CK_NullToPointer:
5186 case CK_NullToMemberPointer:
5187 case CK_BaseToDerivedMemberPointer:
5188 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005189 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005190 case CK_ConstructorConversion:
5191 case CK_IntegralToPointer:
5192 case CK_ToVoid:
5193 case CK_VectorSplat:
5194 case CK_IntegralToFloating:
5195 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005196 case CK_CPointerToObjCPointerCast:
5197 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005198 case CK_AnyPointerToBlockPointerCast:
5199 case CK_ObjCObjectLValueCast:
5200 case CK_FloatingRealToComplex:
5201 case CK_FloatingComplexToReal:
5202 case CK_FloatingComplexCast:
5203 case CK_FloatingComplexToIntegralComplex:
5204 case CK_IntegralRealToComplex:
5205 case CK_IntegralComplexCast:
5206 case CK_IntegralComplexToFloatingComplex:
5207 llvm_unreachable("invalid cast kind for integral value");
5208
Eli Friedmane50c2972011-03-25 19:07:11 +00005209 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005210 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005211 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005212 case CK_ARCProduceObject:
5213 case CK_ARCConsumeObject:
5214 case CK_ARCReclaimReturnedObject:
5215 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005216 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005217 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005218
Richard Smith7d580a42012-01-17 21:17:26 +00005219 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005220 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005221 case CK_AtomicToNonAtomic:
5222 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005223 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005224 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005225
5226 case CK_MemberPointerToBoolean:
5227 case CK_PointerToBoolean:
5228 case CK_IntegralToBoolean:
5229 case CK_FloatingToBoolean:
5230 case CK_FloatingComplexToBoolean:
5231 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005232 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005233 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005234 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005235 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005236 }
5237
Eli Friedman46a52322011-03-25 00:43:55 +00005238 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005239 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005240 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005241
Eli Friedmanbe265702009-02-20 01:15:07 +00005242 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005243 // Allow casts of address-of-label differences if they are no-ops
5244 // or narrowing. (The narrowing case isn't actually guaranteed to
5245 // be constant-evaluatable except in some narrow cases which are hard
5246 // to detect here. We let it through on the assumption the user knows
5247 // what they are doing.)
5248 if (Result.isAddrLabelDiff())
5249 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005250 // Only allow casts of lvalues if they are lossless.
5251 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5252 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005253
Richard Smithf72fccf2012-01-30 22:27:01 +00005254 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5255 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005256 }
Mike Stump1eb44332009-09-09 15:08:12 +00005257
Eli Friedman46a52322011-03-25 00:43:55 +00005258 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005259 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5260
John McCallefdb83e2010-05-07 21:00:08 +00005261 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005262 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005263 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005264
Daniel Dunbardd211642009-02-19 22:24:01 +00005265 if (LV.getLValueBase()) {
5266 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005267 // FIXME: Allow a larger integer size than the pointer size, and allow
5268 // narrowing back down to pointer width in subsequent integral casts.
5269 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005270 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005271 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005272
Richard Smithb755a9d2011-11-16 07:18:12 +00005273 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005274 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005275 return true;
5276 }
5277
Ken Dycka7305832010-01-15 12:37:54 +00005278 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5279 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005280 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005281 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005282
Eli Friedman46a52322011-03-25 00:43:55 +00005283 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005284 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005285 if (!EvaluateComplex(SubExpr, C, Info))
5286 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005287 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005288 }
Eli Friedman2217c872009-02-22 11:46:18 +00005289
Eli Friedman46a52322011-03-25 00:43:55 +00005290 case CK_FloatingToIntegral: {
5291 APFloat F(0.0);
5292 if (!EvaluateFloat(SubExpr, F, Info))
5293 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005294
Richard Smithc1c5f272011-12-13 06:39:58 +00005295 APSInt Value;
5296 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5297 return false;
5298 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005299 }
5300 }
Mike Stump1eb44332009-09-09 15:08:12 +00005301
Eli Friedman46a52322011-03-25 00:43:55 +00005302 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005303}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005304
Eli Friedman722c7172009-02-28 03:59:05 +00005305bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5306 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005307 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005308 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5309 return false;
5310 if (!LV.isComplexInt())
5311 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005312 return Success(LV.getComplexIntReal(), E);
5313 }
5314
5315 return Visit(E->getSubExpr());
5316}
5317
Eli Friedman664a1042009-02-27 04:45:43 +00005318bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005319 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005320 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005321 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5322 return false;
5323 if (!LV.isComplexInt())
5324 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005325 return Success(LV.getComplexIntImag(), E);
5326 }
5327
Richard Smith8327fad2011-10-24 18:44:57 +00005328 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005329 return Success(0, E);
5330}
5331
Douglas Gregoree8aff02011-01-04 17:33:58 +00005332bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5333 return Success(E->getPackLength(), E);
5334}
5335
Sebastian Redl295995c2010-09-10 20:55:47 +00005336bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5337 return Success(E->getValue(), E);
5338}
5339
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005340//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005341// Float Evaluation
5342//===----------------------------------------------------------------------===//
5343
5344namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005345class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005346 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005347 APFloat &Result;
5348public:
5349 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005350 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005351
Richard Smith47a1eed2011-10-29 20:57:55 +00005352 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005353 Result = V.getFloat();
5354 return true;
5355 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005356
Richard Smith51201882011-12-30 21:15:51 +00005357 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005358 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5359 return true;
5360 }
5361
Chris Lattner019f4e82008-10-06 05:28:25 +00005362 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005363
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005364 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005365 bool VisitBinaryOperator(const BinaryOperator *E);
5366 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005367 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005368
John McCallabd3a852010-05-07 22:08:54 +00005369 bool VisitUnaryReal(const UnaryOperator *E);
5370 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005371
Richard Smith51201882011-12-30 21:15:51 +00005372 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005373};
5374} // end anonymous namespace
5375
5376static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005377 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005378 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005379}
5380
Jay Foad4ba2a172011-01-12 09:06:06 +00005381static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005382 QualType ResultTy,
5383 const Expr *Arg,
5384 bool SNaN,
5385 llvm::APFloat &Result) {
5386 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5387 if (!S) return false;
5388
5389 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5390
5391 llvm::APInt fill;
5392
5393 // Treat empty strings as if they were zero.
5394 if (S->getString().empty())
5395 fill = llvm::APInt(32, 0);
5396 else if (S->getString().getAsInteger(0, fill))
5397 return false;
5398
5399 if (SNaN)
5400 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5401 else
5402 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5403 return true;
5404}
5405
Chris Lattner019f4e82008-10-06 05:28:25 +00005406bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005407 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005408 default:
5409 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5410
Chris Lattner019f4e82008-10-06 05:28:25 +00005411 case Builtin::BI__builtin_huge_val:
5412 case Builtin::BI__builtin_huge_valf:
5413 case Builtin::BI__builtin_huge_vall:
5414 case Builtin::BI__builtin_inf:
5415 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005416 case Builtin::BI__builtin_infl: {
5417 const llvm::fltSemantics &Sem =
5418 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005419 Result = llvm::APFloat::getInf(Sem);
5420 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005421 }
Mike Stump1eb44332009-09-09 15:08:12 +00005422
John McCalldb7b72a2010-02-28 13:00:19 +00005423 case Builtin::BI__builtin_nans:
5424 case Builtin::BI__builtin_nansf:
5425 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005426 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5427 true, Result))
5428 return Error(E);
5429 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005430
Chris Lattner9e621712008-10-06 06:31:58 +00005431 case Builtin::BI__builtin_nan:
5432 case Builtin::BI__builtin_nanf:
5433 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005434 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005435 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005436 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5437 false, Result))
5438 return Error(E);
5439 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005440
5441 case Builtin::BI__builtin_fabs:
5442 case Builtin::BI__builtin_fabsf:
5443 case Builtin::BI__builtin_fabsl:
5444 if (!EvaluateFloat(E->getArg(0), Result, Info))
5445 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005446
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005447 if (Result.isNegative())
5448 Result.changeSign();
5449 return true;
5450
Mike Stump1eb44332009-09-09 15:08:12 +00005451 case Builtin::BI__builtin_copysign:
5452 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005453 case Builtin::BI__builtin_copysignl: {
5454 APFloat RHS(0.);
5455 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5456 !EvaluateFloat(E->getArg(1), RHS, Info))
5457 return false;
5458 Result.copySign(RHS);
5459 return true;
5460 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005461 }
5462}
5463
John McCallabd3a852010-05-07 22:08:54 +00005464bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005465 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5466 ComplexValue CV;
5467 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5468 return false;
5469 Result = CV.FloatReal;
5470 return true;
5471 }
5472
5473 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005474}
5475
5476bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005477 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5478 ComplexValue CV;
5479 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5480 return false;
5481 Result = CV.FloatImag;
5482 return true;
5483 }
5484
Richard Smith8327fad2011-10-24 18:44:57 +00005485 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005486 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5487 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005488 return true;
5489}
5490
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005491bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005492 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005493 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005494 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005495 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005496 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005497 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5498 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005499 Result.changeSign();
5500 return true;
5501 }
5502}
Chris Lattner019f4e82008-10-06 05:28:25 +00005503
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005504bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005505 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5506 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005507
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005508 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005509 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5510 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005511 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005512 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005513 return false;
5514
5515 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005516 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005517 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005518 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005519 break;
John McCall2de56d12010-08-25 11:45:40 +00005520 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005521 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005522 break;
John McCall2de56d12010-08-25 11:45:40 +00005523 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005524 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005525 break;
John McCall2de56d12010-08-25 11:45:40 +00005526 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005527 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005528 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005529 }
Richard Smith7b48a292012-02-01 05:53:12 +00005530
5531 if (Result.isInfinity() || Result.isNaN())
5532 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5533 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005534}
5535
5536bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5537 Result = E->getValue();
5538 return true;
5539}
5540
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005541bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5542 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005543
Eli Friedman2a523ee2011-03-25 00:54:52 +00005544 switch (E->getCastKind()) {
5545 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005546 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005547
5548 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005549 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005550 return EvaluateInteger(SubExpr, IntResult, Info) &&
5551 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5552 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005553 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005554
5555 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005556 if (!Visit(SubExpr))
5557 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005558 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5559 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005560 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005561
Eli Friedman2a523ee2011-03-25 00:54:52 +00005562 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005563 ComplexValue V;
5564 if (!EvaluateComplex(SubExpr, V, Info))
5565 return false;
5566 Result = V.getComplexFloatReal();
5567 return true;
5568 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005569 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005570}
5571
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005572//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005573// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005574//===----------------------------------------------------------------------===//
5575
5576namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005577class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005578 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005579 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005580
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005581public:
John McCallf4cf1a12010-05-07 17:22:02 +00005582 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005583 : ExprEvaluatorBaseTy(info), Result(Result) {}
5584
Richard Smith47a1eed2011-10-29 20:57:55 +00005585 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005586 Result.setFrom(V);
5587 return true;
5588 }
Mike Stump1eb44332009-09-09 15:08:12 +00005589
Eli Friedman7ead5c72012-01-10 04:58:17 +00005590 bool ZeroInitialization(const Expr *E);
5591
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005592 //===--------------------------------------------------------------------===//
5593 // Visitor Methods
5594 //===--------------------------------------------------------------------===//
5595
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005596 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005597 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005598 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005599 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005600 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005601};
5602} // end anonymous namespace
5603
John McCallf4cf1a12010-05-07 17:22:02 +00005604static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5605 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005606 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005607 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005608}
5609
Eli Friedman7ead5c72012-01-10 04:58:17 +00005610bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005611 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005612 if (ElemTy->isRealFloatingType()) {
5613 Result.makeComplexFloat();
5614 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5615 Result.FloatReal = Zero;
5616 Result.FloatImag = Zero;
5617 } else {
5618 Result.makeComplexInt();
5619 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5620 Result.IntReal = Zero;
5621 Result.IntImag = Zero;
5622 }
5623 return true;
5624}
5625
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005626bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5627 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005628
5629 if (SubExpr->getType()->isRealFloatingType()) {
5630 Result.makeComplexFloat();
5631 APFloat &Imag = Result.FloatImag;
5632 if (!EvaluateFloat(SubExpr, Imag, Info))
5633 return false;
5634
5635 Result.FloatReal = APFloat(Imag.getSemantics());
5636 return true;
5637 } else {
5638 assert(SubExpr->getType()->isIntegerType() &&
5639 "Unexpected imaginary literal.");
5640
5641 Result.makeComplexInt();
5642 APSInt &Imag = Result.IntImag;
5643 if (!EvaluateInteger(SubExpr, Imag, Info))
5644 return false;
5645
5646 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5647 return true;
5648 }
5649}
5650
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005651bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005652
John McCall8786da72010-12-14 17:51:41 +00005653 switch (E->getCastKind()) {
5654 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005655 case CK_BaseToDerived:
5656 case CK_DerivedToBase:
5657 case CK_UncheckedDerivedToBase:
5658 case CK_Dynamic:
5659 case CK_ToUnion:
5660 case CK_ArrayToPointerDecay:
5661 case CK_FunctionToPointerDecay:
5662 case CK_NullToPointer:
5663 case CK_NullToMemberPointer:
5664 case CK_BaseToDerivedMemberPointer:
5665 case CK_DerivedToBaseMemberPointer:
5666 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005667 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005668 case CK_ConstructorConversion:
5669 case CK_IntegralToPointer:
5670 case CK_PointerToIntegral:
5671 case CK_PointerToBoolean:
5672 case CK_ToVoid:
5673 case CK_VectorSplat:
5674 case CK_IntegralCast:
5675 case CK_IntegralToBoolean:
5676 case CK_IntegralToFloating:
5677 case CK_FloatingToIntegral:
5678 case CK_FloatingToBoolean:
5679 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005680 case CK_CPointerToObjCPointerCast:
5681 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005682 case CK_AnyPointerToBlockPointerCast:
5683 case CK_ObjCObjectLValueCast:
5684 case CK_FloatingComplexToReal:
5685 case CK_FloatingComplexToBoolean:
5686 case CK_IntegralComplexToReal:
5687 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005688 case CK_ARCProduceObject:
5689 case CK_ARCConsumeObject:
5690 case CK_ARCReclaimReturnedObject:
5691 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005692 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005693 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005694
John McCall8786da72010-12-14 17:51:41 +00005695 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005696 case CK_AtomicToNonAtomic:
5697 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005698 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005699 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005700
5701 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005702 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005703 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005704 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005705
5706 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005707 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005708 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005709 return false;
5710
John McCall8786da72010-12-14 17:51:41 +00005711 Result.makeComplexFloat();
5712 Result.FloatImag = APFloat(Real.getSemantics());
5713 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005714 }
5715
John McCall8786da72010-12-14 17:51:41 +00005716 case CK_FloatingComplexCast: {
5717 if (!Visit(E->getSubExpr()))
5718 return false;
5719
5720 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5721 QualType From
5722 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5723
Richard Smithc1c5f272011-12-13 06:39:58 +00005724 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5725 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005726 }
5727
5728 case CK_FloatingComplexToIntegralComplex: {
5729 if (!Visit(E->getSubExpr()))
5730 return false;
5731
5732 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5733 QualType From
5734 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5735 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005736 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5737 To, Result.IntReal) &&
5738 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5739 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005740 }
5741
5742 case CK_IntegralRealToComplex: {
5743 APSInt &Real = Result.IntReal;
5744 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5745 return false;
5746
5747 Result.makeComplexInt();
5748 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5749 return true;
5750 }
5751
5752 case CK_IntegralComplexCast: {
5753 if (!Visit(E->getSubExpr()))
5754 return false;
5755
5756 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5757 QualType From
5758 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5759
Richard Smithf72fccf2012-01-30 22:27:01 +00005760 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5761 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005762 return true;
5763 }
5764
5765 case CK_IntegralComplexToFloatingComplex: {
5766 if (!Visit(E->getSubExpr()))
5767 return false;
5768
5769 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5770 QualType From
5771 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5772 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005773 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5774 To, Result.FloatReal) &&
5775 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5776 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005777 }
5778 }
5779
5780 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005781}
5782
John McCallf4cf1a12010-05-07 17:22:02 +00005783bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005784 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005785 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5786
Richard Smith745f5142012-01-27 01:14:48 +00005787 bool LHSOK = Visit(E->getLHS());
5788 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005789 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005790
John McCallf4cf1a12010-05-07 17:22:02 +00005791 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005792 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005793 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005794
Daniel Dunbar3f279872009-01-29 01:32:56 +00005795 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5796 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005797 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005798 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005799 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005800 if (Result.isComplexFloat()) {
5801 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5802 APFloat::rmNearestTiesToEven);
5803 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5804 APFloat::rmNearestTiesToEven);
5805 } else {
5806 Result.getComplexIntReal() += RHS.getComplexIntReal();
5807 Result.getComplexIntImag() += RHS.getComplexIntImag();
5808 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005809 break;
John McCall2de56d12010-08-25 11:45:40 +00005810 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005811 if (Result.isComplexFloat()) {
5812 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5813 APFloat::rmNearestTiesToEven);
5814 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5815 APFloat::rmNearestTiesToEven);
5816 } else {
5817 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5818 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5819 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005820 break;
John McCall2de56d12010-08-25 11:45:40 +00005821 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005822 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005823 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005824 APFloat &LHS_r = LHS.getComplexFloatReal();
5825 APFloat &LHS_i = LHS.getComplexFloatImag();
5826 APFloat &RHS_r = RHS.getComplexFloatReal();
5827 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005828
Daniel Dunbar3f279872009-01-29 01:32:56 +00005829 APFloat Tmp = LHS_r;
5830 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5831 Result.getComplexFloatReal() = Tmp;
5832 Tmp = LHS_i;
5833 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5834 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5835
5836 Tmp = LHS_r;
5837 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5838 Result.getComplexFloatImag() = Tmp;
5839 Tmp = LHS_i;
5840 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5841 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5842 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005843 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005844 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005845 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5846 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005847 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005848 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5849 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5850 }
5851 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005852 case BO_Div:
5853 if (Result.isComplexFloat()) {
5854 ComplexValue LHS = Result;
5855 APFloat &LHS_r = LHS.getComplexFloatReal();
5856 APFloat &LHS_i = LHS.getComplexFloatImag();
5857 APFloat &RHS_r = RHS.getComplexFloatReal();
5858 APFloat &RHS_i = RHS.getComplexFloatImag();
5859 APFloat &Res_r = Result.getComplexFloatReal();
5860 APFloat &Res_i = Result.getComplexFloatImag();
5861
5862 APFloat Den = RHS_r;
5863 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5864 APFloat Tmp = RHS_i;
5865 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5866 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5867
5868 Res_r = LHS_r;
5869 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5870 Tmp = LHS_i;
5871 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5872 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5873 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5874
5875 Res_i = LHS_i;
5876 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5877 Tmp = LHS_r;
5878 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5879 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5880 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5881 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005882 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5883 return Error(E, diag::note_expr_divide_by_zero);
5884
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005885 ComplexValue LHS = Result;
5886 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5887 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5888 Result.getComplexIntReal() =
5889 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5890 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5891 Result.getComplexIntImag() =
5892 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5893 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5894 }
5895 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005896 }
5897
John McCallf4cf1a12010-05-07 17:22:02 +00005898 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005899}
5900
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005901bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5902 // Get the operand value into 'Result'.
5903 if (!Visit(E->getSubExpr()))
5904 return false;
5905
5906 switch (E->getOpcode()) {
5907 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005908 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005909 case UO_Extension:
5910 return true;
5911 case UO_Plus:
5912 // The result is always just the subexpr.
5913 return true;
5914 case UO_Minus:
5915 if (Result.isComplexFloat()) {
5916 Result.getComplexFloatReal().changeSign();
5917 Result.getComplexFloatImag().changeSign();
5918 }
5919 else {
5920 Result.getComplexIntReal() = -Result.getComplexIntReal();
5921 Result.getComplexIntImag() = -Result.getComplexIntImag();
5922 }
5923 return true;
5924 case UO_Not:
5925 if (Result.isComplexFloat())
5926 Result.getComplexFloatImag().changeSign();
5927 else
5928 Result.getComplexIntImag() = -Result.getComplexIntImag();
5929 return true;
5930 }
5931}
5932
Eli Friedman7ead5c72012-01-10 04:58:17 +00005933bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5934 if (E->getNumInits() == 2) {
5935 if (E->getType()->isComplexType()) {
5936 Result.makeComplexFloat();
5937 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5938 return false;
5939 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5940 return false;
5941 } else {
5942 Result.makeComplexInt();
5943 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5944 return false;
5945 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5946 return false;
5947 }
5948 return true;
5949 }
5950 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5951}
5952
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005953//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005954// Void expression evaluation, primarily for a cast to void on the LHS of a
5955// comma operator
5956//===----------------------------------------------------------------------===//
5957
5958namespace {
5959class VoidExprEvaluator
5960 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5961public:
5962 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5963
5964 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005965
5966 bool VisitCastExpr(const CastExpr *E) {
5967 switch (E->getCastKind()) {
5968 default:
5969 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5970 case CK_ToVoid:
5971 VisitIgnoredValue(E->getSubExpr());
5972 return true;
5973 }
5974 }
5975};
5976} // end anonymous namespace
5977
5978static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5979 assert(E->isRValue() && E->getType()->isVoidType());
5980 return VoidExprEvaluator(Info).Visit(E);
5981}
5982
5983//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005984// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005985//===----------------------------------------------------------------------===//
5986
Richard Smith47a1eed2011-10-29 20:57:55 +00005987static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005988 // In C, function designators are not lvalues, but we evaluate them as if they
5989 // are.
5990 if (E->isGLValue() || E->getType()->isFunctionType()) {
5991 LValue LV;
5992 if (!EvaluateLValue(E, LV, Info))
5993 return false;
5994 LV.moveInto(Result);
5995 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005996 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005997 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005998 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005999 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006000 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006001 } else if (E->getType()->hasPointerRepresentation()) {
6002 LValue LV;
6003 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006004 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006005 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006006 } else if (E->getType()->isRealFloatingType()) {
6007 llvm::APFloat F(0.0);
6008 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006009 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00006010 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006011 } else if (E->getType()->isAnyComplexType()) {
6012 ComplexValue C;
6013 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006014 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006015 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006016 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006017 MemberPtr P;
6018 if (!EvaluateMemberPointer(E, P, Info))
6019 return false;
6020 P.moveInto(Result);
6021 return true;
Richard Smith51201882011-12-30 21:15:51 +00006022 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006023 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006024 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006025 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006026 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006027 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006028 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006029 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006030 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006031 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6032 return false;
6033 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006034 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00006035 if (Info.getLangOpts().CPlusPlus0x)
6036 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
6037 << E->getType();
6038 else
6039 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00006040 if (!EvaluateVoid(E, Info))
6041 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006042 } else if (Info.getLangOpts().CPlusPlus0x) {
6043 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
6044 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006045 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00006046 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006047 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006048 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006049
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006050 return true;
6051}
6052
Richard Smith83587db2012-02-15 02:18:13 +00006053/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6054/// cases, the in-place evaluation is essential, since later initializers for
6055/// an object can indirectly refer to subobjects which were initialized earlier.
6056static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6057 const Expr *E, CheckConstantExpressionKind CCEK,
6058 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006059 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006060 return false;
6061
6062 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006063 // Evaluate arrays and record types in-place, so that later initializers can
6064 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006065 if (E->getType()->isArrayType())
6066 return EvaluateArray(E, This, Result, Info);
6067 else if (E->getType()->isRecordType())
6068 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006069 }
6070
6071 // For any other type, in-place evaluation is unimportant.
6072 CCValue CoreConstResult;
Richard Smith83587db2012-02-15 02:18:13 +00006073 if (!Evaluate(CoreConstResult, Info, E))
6074 return false;
6075 Result = CoreConstResult.toAPValue();
6076 return true;
Richard Smith69c2c502011-11-04 05:33:44 +00006077}
6078
Richard Smithf48fdb02011-12-09 22:58:01 +00006079/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6080/// lvalue-to-rvalue cast if it is an lvalue.
6081static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006082 if (!CheckLiteralType(Info, E))
6083 return false;
6084
Richard Smithf48fdb02011-12-09 22:58:01 +00006085 CCValue Value;
6086 if (!::Evaluate(Value, Info, E))
6087 return false;
6088
6089 if (E->isGLValue()) {
6090 LValue LV;
6091 LV.setFrom(Value);
6092 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
6093 return false;
6094 }
6095
6096 // Check this core constant expression is a constant expression, and if so,
6097 // convert it to one.
Richard Smith83587db2012-02-15 02:18:13 +00006098 Result = Value.toAPValue();
6099 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006100}
Richard Smithc49bd112011-10-28 17:51:58 +00006101
Richard Smith51f47082011-10-29 00:50:52 +00006102/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006103/// any crazy technique (that has nothing to do with language standards) that
6104/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006105/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6106/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006107bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006108 // Fast-path evaluations of integer literals, since we sometimes see files
6109 // containing vast quantities of these.
6110 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6111 Result.Val = APValue(APSInt(L->getValue(),
6112 L->getType()->isUnsignedIntegerType()));
6113 return true;
6114 }
6115
Richard Smith2d6a5672012-01-14 04:30:29 +00006116 // FIXME: Evaluating values of large array and record types can cause
6117 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006118 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6119 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006120 return false;
6121
Richard Smithf48fdb02011-12-09 22:58:01 +00006122 EvalInfo Info(Ctx, Result);
6123 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006124}
6125
Jay Foad4ba2a172011-01-12 09:06:06 +00006126bool Expr::EvaluateAsBooleanCondition(bool &Result,
6127 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006128 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006129 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00006130 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
6131 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00006132 Result);
John McCallcd7a4452010-01-05 23:42:56 +00006133}
6134
Richard Smith80d4b552011-12-28 19:48:30 +00006135bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6136 SideEffectsKind AllowSideEffects) const {
6137 if (!getType()->isIntegralOrEnumerationType())
6138 return false;
6139
Richard Smithc49bd112011-10-28 17:51:58 +00006140 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006141 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6142 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006143 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006144
Richard Smithc49bd112011-10-28 17:51:58 +00006145 Result = ExprResult.Val.getInt();
6146 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006147}
6148
Jay Foad4ba2a172011-01-12 09:06:06 +00006149bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006150 EvalInfo Info(Ctx, Result);
6151
John McCallefdb83e2010-05-07 21:00:08 +00006152 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006153 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6154 !CheckLValueConstantExpression(Info, getExprLoc(),
6155 Ctx.getLValueReferenceType(getType()), LV))
6156 return false;
6157
6158 CCValue Tmp;
6159 LV.moveInto(Tmp);
6160 Result.Val = Tmp.toAPValue();
6161 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006162}
6163
Richard Smith099e7f62011-12-19 06:19:21 +00006164bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6165 const VarDecl *VD,
6166 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006167 // FIXME: Evaluating initializers for large array and record types can cause
6168 // performance problems. Only do so in C++11 for now.
6169 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6170 !Ctx.getLangOptions().CPlusPlus0x)
6171 return false;
6172
Richard Smith099e7f62011-12-19 06:19:21 +00006173 Expr::EvalStatus EStatus;
6174 EStatus.Diag = &Notes;
6175
6176 EvalInfo InitInfo(Ctx, EStatus);
6177 InitInfo.setEvaluatingDecl(VD, Value);
6178
6179 LValue LVal;
6180 LVal.set(VD);
6181
Richard Smith51201882011-12-30 21:15:51 +00006182 // C++11 [basic.start.init]p2:
6183 // Variables with static storage duration or thread storage duration shall be
6184 // zero-initialized before any other initialization takes place.
6185 // This behavior is not present in C.
6186 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
6187 !VD->getType()->isReferenceType()) {
6188 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006189 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6190 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006191 return false;
6192 }
6193
Richard Smith83587db2012-02-15 02:18:13 +00006194 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6195 /*AllowNonLiteralTypes=*/true) ||
6196 EStatus.HasSideEffects)
6197 return false;
6198
6199 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6200 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006201}
6202
Richard Smith51f47082011-10-29 00:50:52 +00006203/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6204/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006205bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006206 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006207 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006208}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006209
Jay Foad4ba2a172011-01-12 09:06:06 +00006210bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006211 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006212}
6213
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006214APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006215 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006216 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006217 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006218 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006219 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006220
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006221 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006222}
John McCalld905f5a2010-05-07 05:32:02 +00006223
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006224 bool Expr::EvalResult::isGlobalLValue() const {
6225 assert(Val.isLValue());
6226 return IsGlobalLValue(Val.getLValueBase());
6227 }
6228
6229
John McCalld905f5a2010-05-07 05:32:02 +00006230/// isIntegerConstantExpr - this recursive routine will test if an expression is
6231/// an integer constant expression.
6232
6233/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6234/// comma, etc
6235///
6236/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6237/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6238/// cast+dereference.
6239
6240// CheckICE - This function does the fundamental ICE checking: the returned
6241// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6242// Note that to reduce code duplication, this helper does no evaluation
6243// itself; the caller checks whether the expression is evaluatable, and
6244// in the rare cases where CheckICE actually cares about the evaluated
6245// value, it calls into Evalute.
6246//
6247// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006248// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006249// 1: This expression is not an ICE, but if it isn't evaluated, it's
6250// a legal subexpression for an ICE. This return value is used to handle
6251// the comma operator in C99 mode.
6252// 2: This expression is not an ICE, and is not a legal subexpression for one.
6253
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006254namespace {
6255
John McCalld905f5a2010-05-07 05:32:02 +00006256struct ICEDiag {
6257 unsigned Val;
6258 SourceLocation Loc;
6259
6260 public:
6261 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6262 ICEDiag() : Val(0) {}
6263};
6264
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006265}
6266
6267static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006268
6269static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6270 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006271 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006272 !EVResult.Val.isInt()) {
6273 return ICEDiag(2, E->getLocStart());
6274 }
6275 return NoDiag();
6276}
6277
6278static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6279 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006280 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006281 return ICEDiag(2, E->getLocStart());
6282 }
6283
6284 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006285#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006286#define STMT(Node, Base) case Expr::Node##Class:
6287#define EXPR(Node, Base)
6288#include "clang/AST/StmtNodes.inc"
6289 case Expr::PredefinedExprClass:
6290 case Expr::FloatingLiteralClass:
6291 case Expr::ImaginaryLiteralClass:
6292 case Expr::StringLiteralClass:
6293 case Expr::ArraySubscriptExprClass:
6294 case Expr::MemberExprClass:
6295 case Expr::CompoundAssignOperatorClass:
6296 case Expr::CompoundLiteralExprClass:
6297 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006298 case Expr::DesignatedInitExprClass:
6299 case Expr::ImplicitValueInitExprClass:
6300 case Expr::ParenListExprClass:
6301 case Expr::VAArgExprClass:
6302 case Expr::AddrLabelExprClass:
6303 case Expr::StmtExprClass:
6304 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006305 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006306 case Expr::CXXDynamicCastExprClass:
6307 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006308 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006309 case Expr::CXXNullPtrLiteralExprClass:
6310 case Expr::CXXThisExprClass:
6311 case Expr::CXXThrowExprClass:
6312 case Expr::CXXNewExprClass:
6313 case Expr::CXXDeleteExprClass:
6314 case Expr::CXXPseudoDestructorExprClass:
6315 case Expr::UnresolvedLookupExprClass:
6316 case Expr::DependentScopeDeclRefExprClass:
6317 case Expr::CXXConstructExprClass:
6318 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006319 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006320 case Expr::CXXTemporaryObjectExprClass:
6321 case Expr::CXXUnresolvedConstructExprClass:
6322 case Expr::CXXDependentScopeMemberExprClass:
6323 case Expr::UnresolvedMemberExprClass:
6324 case Expr::ObjCStringLiteralClass:
6325 case Expr::ObjCEncodeExprClass:
6326 case Expr::ObjCMessageExprClass:
6327 case Expr::ObjCSelectorExprClass:
6328 case Expr::ObjCProtocolExprClass:
6329 case Expr::ObjCIvarRefExprClass:
6330 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006331 case Expr::ObjCIsaExprClass:
6332 case Expr::ShuffleVectorExprClass:
6333 case Expr::BlockExprClass:
6334 case Expr::BlockDeclRefExprClass:
6335 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006336 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006337 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006338 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006339 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006340 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006341 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006342 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006343 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006344 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006345 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006346 return ICEDiag(2, E->getLocStart());
6347
Douglas Gregoree8aff02011-01-04 17:33:58 +00006348 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006349 case Expr::GNUNullExprClass:
6350 // GCC considers the GNU __null value to be an integral constant expression.
6351 return NoDiag();
6352
John McCall91a57552011-07-15 05:09:51 +00006353 case Expr::SubstNonTypeTemplateParmExprClass:
6354 return
6355 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6356
John McCalld905f5a2010-05-07 05:32:02 +00006357 case Expr::ParenExprClass:
6358 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006359 case Expr::GenericSelectionExprClass:
6360 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006361 case Expr::IntegerLiteralClass:
6362 case Expr::CharacterLiteralClass:
6363 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006364 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006365 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006366 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006367 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006368 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006369 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006370 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006371 return NoDiag();
6372 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006373 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006374 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6375 // constant expressions, but they can never be ICEs because an ICE cannot
6376 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006377 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006378 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006379 return CheckEvalInICE(E, Ctx);
6380 return ICEDiag(2, E->getLocStart());
6381 }
Richard Smith359c89d2012-02-24 22:12:32 +00006382 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006383 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6384 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006385 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
6386 if (Ctx.getLangOptions().CPlusPlus &&
6387 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006388 // Parameter variables are never constants. Without this check,
6389 // getAnyInitializer() can find a default argument, which leads
6390 // to chaos.
6391 if (isa<ParmVarDecl>(D))
6392 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6393
6394 // C++ 7.1.5.1p2
6395 // A variable of non-volatile const-qualified integral or enumeration
6396 // type initialized by an ICE can be used in ICEs.
6397 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006398 if (!Dcl->getType()->isIntegralOrEnumerationType())
6399 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6400
Richard Smith099e7f62011-12-19 06:19:21 +00006401 const VarDecl *VD;
6402 // Look for a declaration of this variable that has an initializer, and
6403 // check whether it is an ICE.
6404 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6405 return NoDiag();
6406 else
6407 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006408 }
6409 }
6410 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006411 }
John McCalld905f5a2010-05-07 05:32:02 +00006412 case Expr::UnaryOperatorClass: {
6413 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6414 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006415 case UO_PostInc:
6416 case UO_PostDec:
6417 case UO_PreInc:
6418 case UO_PreDec:
6419 case UO_AddrOf:
6420 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006421 // C99 6.6/3 allows increment and decrement within unevaluated
6422 // subexpressions of constant expressions, but they can never be ICEs
6423 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006424 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006425 case UO_Extension:
6426 case UO_LNot:
6427 case UO_Plus:
6428 case UO_Minus:
6429 case UO_Not:
6430 case UO_Real:
6431 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006432 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006433 }
6434
6435 // OffsetOf falls through here.
6436 }
6437 case Expr::OffsetOfExprClass: {
6438 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006439 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006440 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006441 // compliance: we should warn earlier for offsetof expressions with
6442 // array subscripts that aren't ICEs, and if the array subscripts
6443 // are ICEs, the value of the offsetof must be an integer constant.
6444 return CheckEvalInICE(E, Ctx);
6445 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006446 case Expr::UnaryExprOrTypeTraitExprClass: {
6447 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6448 if ((Exp->getKind() == UETT_SizeOf) &&
6449 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006450 return ICEDiag(2, E->getLocStart());
6451 return NoDiag();
6452 }
6453 case Expr::BinaryOperatorClass: {
6454 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6455 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006456 case BO_PtrMemD:
6457 case BO_PtrMemI:
6458 case BO_Assign:
6459 case BO_MulAssign:
6460 case BO_DivAssign:
6461 case BO_RemAssign:
6462 case BO_AddAssign:
6463 case BO_SubAssign:
6464 case BO_ShlAssign:
6465 case BO_ShrAssign:
6466 case BO_AndAssign:
6467 case BO_XorAssign:
6468 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006469 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6470 // constant expressions, but they can never be ICEs because an ICE cannot
6471 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006472 return ICEDiag(2, E->getLocStart());
6473
John McCall2de56d12010-08-25 11:45:40 +00006474 case BO_Mul:
6475 case BO_Div:
6476 case BO_Rem:
6477 case BO_Add:
6478 case BO_Sub:
6479 case BO_Shl:
6480 case BO_Shr:
6481 case BO_LT:
6482 case BO_GT:
6483 case BO_LE:
6484 case BO_GE:
6485 case BO_EQ:
6486 case BO_NE:
6487 case BO_And:
6488 case BO_Xor:
6489 case BO_Or:
6490 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006491 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6492 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006493 if (Exp->getOpcode() == BO_Div ||
6494 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006495 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006496 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006497 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006498 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006499 if (REval == 0)
6500 return ICEDiag(1, E->getLocStart());
6501 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006502 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006503 if (LEval.isMinSignedValue())
6504 return ICEDiag(1, E->getLocStart());
6505 }
6506 }
6507 }
John McCall2de56d12010-08-25 11:45:40 +00006508 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006509 if (Ctx.getLangOptions().C99) {
6510 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6511 // if it isn't evaluated.
6512 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6513 return ICEDiag(1, E->getLocStart());
6514 } else {
6515 // In both C89 and C++, commas in ICEs are illegal.
6516 return ICEDiag(2, E->getLocStart());
6517 }
6518 }
6519 if (LHSResult.Val >= RHSResult.Val)
6520 return LHSResult;
6521 return RHSResult;
6522 }
John McCall2de56d12010-08-25 11:45:40 +00006523 case BO_LAnd:
6524 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006525 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6526 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6527 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6528 // Rare case where the RHS has a comma "side-effect"; we need
6529 // to actually check the condition to see whether the side
6530 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006531 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006532 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006533 return RHSResult;
6534 return NoDiag();
6535 }
6536
6537 if (LHSResult.Val >= RHSResult.Val)
6538 return LHSResult;
6539 return RHSResult;
6540 }
6541 }
6542 }
6543 case Expr::ImplicitCastExprClass:
6544 case Expr::CStyleCastExprClass:
6545 case Expr::CXXFunctionalCastExprClass:
6546 case Expr::CXXStaticCastExprClass:
6547 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006548 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006549 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006550 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006551 if (isa<ExplicitCastExpr>(E)) {
6552 if (const FloatingLiteral *FL
6553 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6554 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6555 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6556 APSInt IgnoredVal(DestWidth, !DestSigned);
6557 bool Ignored;
6558 // If the value does not fit in the destination type, the behavior is
6559 // undefined, so we are not required to treat it as a constant
6560 // expression.
6561 if (FL->getValue().convertToInteger(IgnoredVal,
6562 llvm::APFloat::rmTowardZero,
6563 &Ignored) & APFloat::opInvalidOp)
6564 return ICEDiag(2, E->getLocStart());
6565 return NoDiag();
6566 }
6567 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006568 switch (cast<CastExpr>(E)->getCastKind()) {
6569 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006570 case CK_AtomicToNonAtomic:
6571 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006572 case CK_NoOp:
6573 case CK_IntegralToBoolean:
6574 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006575 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006576 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006577 return ICEDiag(2, E->getLocStart());
6578 }
John McCalld905f5a2010-05-07 05:32:02 +00006579 }
John McCall56ca35d2011-02-17 10:25:35 +00006580 case Expr::BinaryConditionalOperatorClass: {
6581 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6582 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6583 if (CommonResult.Val == 2) return CommonResult;
6584 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6585 if (FalseResult.Val == 2) return FalseResult;
6586 if (CommonResult.Val == 1) return CommonResult;
6587 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006588 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006589 return FalseResult;
6590 }
John McCalld905f5a2010-05-07 05:32:02 +00006591 case Expr::ConditionalOperatorClass: {
6592 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6593 // If the condition (ignoring parens) is a __builtin_constant_p call,
6594 // then only the true side is actually considered in an integer constant
6595 // expression, and it is fully evaluated. This is an important GNU
6596 // extension. See GCC PR38377 for discussion.
6597 if (const CallExpr *CallCE
6598 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006599 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6600 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006601 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006602 if (CondResult.Val == 2)
6603 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006604
Richard Smithf48fdb02011-12-09 22:58:01 +00006605 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6606 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006607
John McCalld905f5a2010-05-07 05:32:02 +00006608 if (TrueResult.Val == 2)
6609 return TrueResult;
6610 if (FalseResult.Val == 2)
6611 return FalseResult;
6612 if (CondResult.Val == 1)
6613 return CondResult;
6614 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6615 return NoDiag();
6616 // Rare case where the diagnostics depend on which side is evaluated
6617 // Note that if we get here, CondResult is 0, and at least one of
6618 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006619 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006620 return FalseResult;
6621 }
6622 return TrueResult;
6623 }
6624 case Expr::CXXDefaultArgExprClass:
6625 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6626 case Expr::ChooseExprClass: {
6627 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6628 }
6629 }
6630
David Blaikie30263482012-01-20 21:50:17 +00006631 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006632}
6633
Richard Smithf48fdb02011-12-09 22:58:01 +00006634/// Evaluate an expression as a C++11 integral constant expression.
6635static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6636 const Expr *E,
6637 llvm::APSInt *Value,
6638 SourceLocation *Loc) {
6639 if (!E->getType()->isIntegralOrEnumerationType()) {
6640 if (Loc) *Loc = E->getExprLoc();
6641 return false;
6642 }
6643
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006644 APValue Result;
6645 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006646 return false;
6647
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006648 assert(Result.isInt() && "pointer cast to int is not an ICE");
6649 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006650 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006651}
6652
Richard Smithdd1f29b2011-12-12 09:28:41 +00006653bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006654 if (Ctx.getLangOptions().CPlusPlus0x)
6655 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6656
John McCalld905f5a2010-05-07 05:32:02 +00006657 ICEDiag d = CheckICE(this, Ctx);
6658 if (d.Val != 0) {
6659 if (Loc) *Loc = d.Loc;
6660 return false;
6661 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006662 return true;
6663}
6664
6665bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6666 SourceLocation *Loc, bool isEvaluated) const {
6667 if (Ctx.getLangOptions().CPlusPlus0x)
6668 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6669
6670 if (!isIntegerConstantExpr(Ctx, Loc))
6671 return false;
6672 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006673 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006674 return true;
6675}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006676
Richard Smith70488e22012-02-14 21:38:30 +00006677bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6678 return CheckICE(this, Ctx).Val == 0;
6679}
6680
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006681bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6682 SourceLocation *Loc) const {
6683 // We support this checking in C++98 mode in order to diagnose compatibility
6684 // issues.
6685 assert(Ctx.getLangOptions().CPlusPlus);
6686
Richard Smith70488e22012-02-14 21:38:30 +00006687 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006688 Expr::EvalStatus Status;
6689 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6690 Status.Diag = &Diags;
6691 EvalInfo Info(Ctx, Status);
6692
6693 APValue Scratch;
6694 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6695
6696 if (!Diags.empty()) {
6697 IsConstExpr = false;
6698 if (Loc) *Loc = Diags[0].first;
6699 } else if (!IsConstExpr) {
6700 // FIXME: This shouldn't happen.
6701 if (Loc) *Loc = getExprLoc();
6702 }
6703
6704 return IsConstExpr;
6705}
Richard Smith745f5142012-01-27 01:14:48 +00006706
6707bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6708 llvm::SmallVectorImpl<
6709 PartialDiagnosticAt> &Diags) {
6710 // FIXME: It would be useful to check constexpr function templates, but at the
6711 // moment the constant expression evaluator cannot cope with the non-rigorous
6712 // ASTs which we build for dependent expressions.
6713 if (FD->isDependentContext())
6714 return true;
6715
6716 Expr::EvalStatus Status;
6717 Status.Diag = &Diags;
6718
6719 EvalInfo Info(FD->getASTContext(), Status);
6720 Info.CheckingPotentialConstantExpression = true;
6721
6722 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6723 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6724
6725 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6726 // is a temporary being used as the 'this' pointer.
6727 LValue This;
6728 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006729 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006730
Richard Smith745f5142012-01-27 01:14:48 +00006731 ArrayRef<const Expr*> Args;
6732
6733 SourceLocation Loc = FD->getLocation();
6734
6735 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Richard Smith83587db2012-02-15 02:18:13 +00006736 APValue Scratch;
Richard Smith745f5142012-01-27 01:14:48 +00006737 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith83587db2012-02-15 02:18:13 +00006738 } else {
6739 CCValue Scratch;
Richard Smith745f5142012-01-27 01:14:48 +00006740 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6741 Args, FD->getBody(), Info, Scratch);
Richard Smith83587db2012-02-15 02:18:13 +00006742 }
Richard Smith745f5142012-01-27 01:14:48 +00006743
6744 return Diags.empty();
6745}