blob: 31750ead25cd1699f6ec012266c55040b76b83b2 [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"
Argyrios Kyrtzidisc1b66e62012-02-27 23:18:37 +000047#include "llvm/ADT/SaveAndRestore.h"
Mike Stump4572bab2009-05-30 03:56:50 +000048#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000049#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000050
Anders Carlssonc44eec62008-07-03 04:20:39 +000051using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000054
Richard Smith83587db2012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCallf4cf1a12010-05-07 17:22:02 +000057namespace {
Richard Smith180f4792011-11-10 06:34:14 +000058 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000061
Richard Smith83587db2012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
66 return B.get<const Expr*>()->getType();
67 }
68
Richard Smith180f4792011-11-10 06:34:14 +000069 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000070 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000071 static
Richard Smithf15fda02012-02-02 01:16:57 +000072 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000073 APValue::BaseOrMemberType Value;
74 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000075 return Value;
76 }
77
78 /// Get an LValue path entry, which is known to not be an array index, as a
79 /// field declaration.
Richard Smith83587db2012-02-15 02:18:13 +000080 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000081 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000082 }
83 /// Get an LValue path entry, which is known to not be an array index, as a
84 /// base class declaration.
Richard Smith83587db2012-02-15 02:18:13 +000085 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000086 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000087 }
88 /// Determine whether this LValue path entry for a base class names a virtual
89 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +000090 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000091 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +000092 }
93
Richard Smithb4e85ed2012-01-06 16:39:00 +000094 /// Find the path length and type of the most-derived subobject in the given
95 /// path, and find the size of the containing array, if any.
96 static
97 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
98 ArrayRef<APValue::LValuePathEntry> Path,
99 uint64_t &ArraySize, QualType &Type) {
100 unsigned MostDerivedLength = 0;
101 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000102 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000103 if (Type->isArrayType()) {
104 const ConstantArrayType *CAT =
105 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
106 Type = CAT->getElementType();
107 ArraySize = CAT->getSize().getZExtValue();
108 MostDerivedLength = I + 1;
Richard Smith86024012012-02-18 22:04:06 +0000109 } else if (Type->isAnyComplexType()) {
110 const ComplexType *CT = Type->castAs<ComplexType>();
111 Type = CT->getElementType();
112 ArraySize = 2;
113 MostDerivedLength = I + 1;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000114 } else if (const FieldDecl *FD = getAsField(Path[I])) {
115 Type = FD->getType();
116 ArraySize = 0;
117 MostDerivedLength = I + 1;
118 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000119 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000120 ArraySize = 0;
121 }
Richard Smith9a17a682011-11-07 05:07:52 +0000122 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000123 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000124 }
125
Richard Smithb4e85ed2012-01-06 16:39:00 +0000126 // The order of this enum is important for diagnostics.
127 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000128 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith86024012012-02-18 22:04:06 +0000129 CSK_This, CSK_Real, CSK_Imag
Richard Smithb4e85ed2012-01-06 16:39:00 +0000130 };
131
Richard Smith0a3bdb62011-11-04 02:25:55 +0000132 /// A path from a glvalue to a subobject of that glvalue.
133 struct SubobjectDesignator {
134 /// True if the subobject was named in a manner not supported by C++11. Such
135 /// lvalues can still be folded, but they are not core constant expressions
136 /// and we cannot perform lvalue-to-rvalue conversions on them.
137 bool Invalid : 1;
138
Richard Smithb4e85ed2012-01-06 16:39:00 +0000139 /// Is this a pointer one past the end of an object?
140 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000141
Richard Smithb4e85ed2012-01-06 16:39:00 +0000142 /// The length of the path to the most-derived object of which this is a
143 /// subobject.
144 unsigned MostDerivedPathLength : 30;
145
146 /// The size of the array of which the most-derived object is an element, or
147 /// 0 if the most-derived object is not an array element.
148 uint64_t MostDerivedArraySize;
149
150 /// The type of the most derived object referred to by this address.
151 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000152
Richard Smith9a17a682011-11-07 05:07:52 +0000153 typedef APValue::LValuePathEntry PathEntry;
154
Richard Smith0a3bdb62011-11-04 02:25:55 +0000155 /// The entries on the path from the glvalue to the designated subobject.
156 SmallVector<PathEntry, 8> Entries;
157
Richard Smithb4e85ed2012-01-06 16:39:00 +0000158 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000159
Richard Smithb4e85ed2012-01-06 16:39:00 +0000160 explicit SubobjectDesignator(QualType T)
161 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
162 MostDerivedArraySize(0), MostDerivedType(T) {}
163
164 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
165 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
166 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000167 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000168 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000169 ArrayRef<PathEntry> VEntries = V.getLValuePath();
170 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
171 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000172 MostDerivedPathLength =
173 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
174 V.getLValuePath(), MostDerivedArraySize,
175 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000176 }
177 }
178
Richard Smith0a3bdb62011-11-04 02:25:55 +0000179 void setInvalid() {
180 Invalid = true;
181 Entries.clear();
182 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000183
184 /// Determine whether this is a one-past-the-end pointer.
185 bool isOnePastTheEnd() const {
186 if (IsOnePastTheEnd)
187 return true;
188 if (MostDerivedArraySize &&
189 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
190 return true;
191 return false;
192 }
193
194 /// Check that this refers to a valid subobject.
195 bool isValidSubobject() const {
196 if (Invalid)
197 return false;
198 return !isOnePastTheEnd();
199 }
200 /// Check that this refers to a valid subobject, and if not, produce a
201 /// relevant diagnostic and set the designator as invalid.
202 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
203
204 /// Update this designator to refer to the first element within this array.
205 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000206 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000207 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000208 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000209
210 // This is a most-derived object.
211 MostDerivedType = CAT->getElementType();
212 MostDerivedArraySize = CAT->getSize().getZExtValue();
213 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000214 }
215 /// Update this designator to refer to the given base or member of this
216 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000217 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000218 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000219 APValue::BaseOrMemberType Value(D, Virtual);
220 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000221 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000222
223 // If this isn't a base class, it's a new most-derived object.
224 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
225 MostDerivedType = FD->getType();
226 MostDerivedArraySize = 0;
227 MostDerivedPathLength = Entries.size();
228 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000229 }
Richard Smith86024012012-02-18 22:04:06 +0000230 /// Update this designator to refer to the given complex component.
231 void addComplexUnchecked(QualType EltTy, bool Imag) {
232 PathEntry Entry;
233 Entry.ArrayIndex = Imag;
234 Entries.push_back(Entry);
235
236 // This is technically a most-derived object, though in practice this
237 // is unlikely to matter.
238 MostDerivedType = EltTy;
239 MostDerivedArraySize = 2;
240 MostDerivedPathLength = Entries.size();
241 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000242 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000243 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000244 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000245 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000246 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000247 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000248 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
249 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
250 setInvalid();
251 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000252 return;
253 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000254 // [expr.add]p4: For the purposes of these operators, a pointer to a
255 // nonarray object behaves the same as a pointer to the first element of
256 // an array of length one with the type of the object as its element type.
257 if (IsOnePastTheEnd && N == (uint64_t)-1)
258 IsOnePastTheEnd = false;
259 else if (!IsOnePastTheEnd && N == 1)
260 IsOnePastTheEnd = true;
261 else if (N != 0) {
262 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000263 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000264 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000265 }
266 };
267
Richard Smith47a1eed2011-10-29 20:57:55 +0000268 /// A core constant value. This can be the value of any constant expression,
269 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000270 ///
271 /// For an LValue, the base and offset are stored in the APValue subobject,
272 /// but the other information is stored in the SubobjectDesignator. For all
273 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000274 class CCValue : public APValue {
275 typedef llvm::APSInt APSInt;
276 typedef llvm::APFloat APFloat;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000277 /// If the value is a reference or pointer, this is a description of how the
278 /// subobject was specified.
279 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000280 public:
Richard Smith177dce72011-11-01 16:57:24 +0000281 struct GlobalValue {};
282
Richard Smith47a1eed2011-10-29 20:57:55 +0000283 CCValue() {}
284 explicit CCValue(const APSInt &I) : APValue(I) {}
285 explicit CCValue(const APFloat &F) : APValue(F) {}
286 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
287 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
288 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith83587db2012-02-15 02:18:13 +0000289 CCValue(const CCValue &V) : APValue(V), Designator(V.Designator) {}
290 CCValue(LValueBase B, const CharUnits &O, unsigned I,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000291 const SubobjectDesignator &D) :
Richard Smith83587db2012-02-15 02:18:13 +0000292 APValue(B, O, APValue::NoLValuePath(), I), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000293 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
Richard Smith83587db2012-02-15 02:18:13 +0000294 APValue(V), Designator(Ctx, V) {
295 }
Richard Smithe24f5fc2011-11-17 22:56:20 +0000296 CCValue(const ValueDecl *D, bool IsDerivedMember,
297 ArrayRef<const CXXRecordDecl*> Path) :
298 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000299 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
300 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000301
Richard Smith0a3bdb62011-11-04 02:25:55 +0000302 SubobjectDesignator &getLValueDesignator() {
303 assert(getKind() == LValue);
304 return Designator;
305 }
306 const SubobjectDesignator &getLValueDesignator() const {
307 return const_cast<CCValue*>(this)->getLValueDesignator();
308 }
Richard Smith83587db2012-02-15 02:18:13 +0000309 APValue toAPValue() const {
310 if (!isLValue())
311 return *this;
312
313 if (Designator.Invalid) {
314 // This is not a core constant expression. An appropriate diagnostic
315 // will have already been produced.
316 return APValue(getLValueBase(), getLValueOffset(),
317 APValue::NoLValuePath(), getLValueCallIndex());
318 }
319
320 return APValue(getLValueBase(), getLValueOffset(),
321 Designator.Entries, Designator.IsOnePastTheEnd,
322 getLValueCallIndex());
323 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000324 };
325
Richard Smithd0dccea2011-10-28 22:34:42 +0000326 /// A stack frame in the constexpr call stack.
327 struct CallStackFrame {
328 EvalInfo &Info;
329
330 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000331 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000332
Richard Smith08d6e032011-12-16 19:06:07 +0000333 /// CallLoc - The location of the call expression for this call.
334 SourceLocation CallLoc;
335
336 /// Callee - The function which was called.
337 const FunctionDecl *Callee;
338
Richard Smith83587db2012-02-15 02:18:13 +0000339 /// Index - The call index of this call.
340 unsigned Index;
341
Richard Smith180f4792011-11-10 06:34:14 +0000342 /// This - The binding for the this pointer in this call, if any.
343 const LValue *This;
344
Richard Smithd0dccea2011-10-28 22:34:42 +0000345 /// ParmBindings - Parameter bindings for this function call, indexed by
346 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000347 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000348
Richard Smithbd552ef2011-10-31 05:52:43 +0000349 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
350 typedef MapTy::const_iterator temp_iterator;
351 /// Temporaries - Temporary lvalues materialized within this stack frame.
352 MapTy Temporaries;
353
Richard Smith08d6e032011-12-16 19:06:07 +0000354 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
355 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000356 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000357 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000358 };
359
Richard Smithdd1f29b2011-12-12 09:28:41 +0000360 /// A partial diagnostic which we might know in advance that we are not going
361 /// to emit.
362 class OptionalDiagnostic {
363 PartialDiagnostic *Diag;
364
365 public:
366 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
367
368 template<typename T>
369 OptionalDiagnostic &operator<<(const T &v) {
370 if (Diag)
371 *Diag << v;
372 return *this;
373 }
Richard Smith789f9b62012-01-31 04:08:20 +0000374
375 OptionalDiagnostic &operator<<(const APSInt &I) {
376 if (Diag) {
377 llvm::SmallVector<char, 32> Buffer;
378 I.toString(Buffer);
379 *Diag << StringRef(Buffer.data(), Buffer.size());
380 }
381 return *this;
382 }
383
384 OptionalDiagnostic &operator<<(const APFloat &F) {
385 if (Diag) {
386 llvm::SmallVector<char, 32> Buffer;
387 F.toString(Buffer);
388 *Diag << StringRef(Buffer.data(), Buffer.size());
389 }
390 return *this;
391 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000392 };
393
Richard Smith83587db2012-02-15 02:18:13 +0000394 /// EvalInfo - This is a private struct used by the evaluator to capture
395 /// information about a subexpression as it is folded. It retains information
396 /// about the AST context, but also maintains information about the folded
397 /// expression.
398 ///
399 /// If an expression could be evaluated, it is still possible it is not a C
400 /// "integer constant expression" or constant expression. If not, this struct
401 /// captures information about how and why not.
402 ///
403 /// One bit of information passed *into* the request for constant folding
404 /// indicates whether the subexpression is "evaluated" or not according to C
405 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
406 /// evaluate the expression regardless of what the RHS is, but C only allows
407 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000408 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000409 ASTContext &Ctx;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000410
Richard Smithbd552ef2011-10-31 05:52:43 +0000411 /// EvalStatus - Contains information about the evaluation.
412 Expr::EvalStatus &EvalStatus;
413
414 /// CurrentCall - The top of the constexpr call stack.
415 CallStackFrame *CurrentCall;
416
Richard Smithbd552ef2011-10-31 05:52:43 +0000417 /// CallStackDepth - The number of calls in the call stack right now.
418 unsigned CallStackDepth;
419
Richard Smith83587db2012-02-15 02:18:13 +0000420 /// NextCallIndex - The next call index to assign.
421 unsigned NextCallIndex;
422
Richard Smithbd552ef2011-10-31 05:52:43 +0000423 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
424 /// OpaqueValues - Values used as the common expression in a
425 /// BinaryConditionalOperator.
426 MapTy OpaqueValues;
427
428 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000429 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000430 CallStackFrame BottomFrame;
431
Richard Smith180f4792011-11-10 06:34:14 +0000432 /// EvaluatingDecl - This is the declaration whose initializer is being
433 /// evaluated, if any.
434 const VarDecl *EvaluatingDecl;
435
436 /// EvaluatingDeclValue - This is the value being constructed for the
437 /// declaration whose initializer is being evaluated, if any.
438 APValue *EvaluatingDeclValue;
439
Richard Smithc1c5f272011-12-13 06:39:58 +0000440 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
441 /// notes attached to it will also be stored, otherwise they will not be.
442 bool HasActiveDiagnostic;
443
Richard Smith745f5142012-01-27 01:14:48 +0000444 /// CheckingPotentialConstantExpression - Are we checking whether the
445 /// expression is a potential constant expression? If so, some diagnostics
446 /// are suppressed.
447 bool CheckingPotentialConstantExpression;
448
Argyrios Kyrtzidisc1b66e62012-02-27 23:18:37 +0000449 /// \brief Stack depth of IntExprEvaluator.
450 /// We check this against a maximum value to avoid stack overflow, see
451 /// test case in test/Sema/many-logical-ops.c.
452 // FIXME: This is a hack; handle properly unlimited logical ops.
453 unsigned IntExprEvaluatorDepth;
Richard Smithbd552ef2011-10-31 05:52:43 +0000454
455 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000456 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000457 CallStackDepth(0), NextCallIndex(1),
458 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000459 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Argyrios Kyrtzidisc1b66e62012-02-27 23:18:37 +0000460 CheckingPotentialConstantExpression(false), IntExprEvaluatorDepth(0) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000461
Richard Smithbd552ef2011-10-31 05:52:43 +0000462 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
463 MapTy::const_iterator i = OpaqueValues.find(e);
464 if (i == OpaqueValues.end()) return 0;
465 return &i->second;
466 }
467
Richard Smith180f4792011-11-10 06:34:14 +0000468 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
469 EvaluatingDecl = VD;
470 EvaluatingDeclValue = &Value;
471 }
472
Richard Smithc18c4232011-11-21 19:36:32 +0000473 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
474
Richard Smithc1c5f272011-12-13 06:39:58 +0000475 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000476 // Don't perform any constexpr calls (other than the call we're checking)
477 // when checking a potential constant expression.
478 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
479 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000480 if (NextCallIndex == 0) {
481 // NextCallIndex has wrapped around.
482 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
483 return false;
484 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000485 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
486 return true;
487 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
488 << getLangOpts().ConstexprCallDepth;
489 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000490 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000491
Richard Smith83587db2012-02-15 02:18:13 +0000492 CallStackFrame *getCallFrame(unsigned CallIndex) {
493 assert(CallIndex && "no call index in getCallFrame");
494 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
495 // be null in this loop.
496 CallStackFrame *Frame = CurrentCall;
497 while (Frame->Index > CallIndex)
498 Frame = Frame->Caller;
499 return (Frame->Index == CallIndex) ? Frame : 0;
500 }
501
Richard Smithc1c5f272011-12-13 06:39:58 +0000502 private:
503 /// Add a diagnostic to the diagnostics list.
504 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
505 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
506 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
507 return EvalStatus.Diag->back().second;
508 }
509
Richard Smith08d6e032011-12-16 19:06:07 +0000510 /// Add notes containing a call stack to the current point of evaluation.
511 void addCallStack(unsigned Limit);
512
Richard Smithc1c5f272011-12-13 06:39:58 +0000513 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000514 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000515 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
516 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000517 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000518 // If we have a prior diagnostic, it will be noting that the expression
519 // isn't a constant expression. This diagnostic is more important.
520 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000521 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000522 unsigned CallStackNotes = CallStackDepth - 1;
523 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
524 if (Limit)
525 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000526 if (CheckingPotentialConstantExpression)
527 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000528
Richard Smithc1c5f272011-12-13 06:39:58 +0000529 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000530 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000531 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
532 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000533 if (!CheckingPotentialConstantExpression)
534 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000535 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000536 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000537 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000538 return OptionalDiagnostic();
539 }
540
541 /// Diagnose that the evaluation does not produce a C++11 core constant
542 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000543 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
544 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000545 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000546 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000547 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
548 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000549 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000550 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000551 return Diag(Loc, DiagId, ExtraNotes);
552 }
553
554 /// Add a note to a prior diagnostic.
555 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
556 if (!HasActiveDiagnostic)
557 return OptionalDiagnostic();
558 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000559 }
Richard Smith099e7f62011-12-19 06:19:21 +0000560
561 /// Add a stack of notes to a prior diagnostic.
562 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
563 if (HasActiveDiagnostic) {
564 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
565 Diags.begin(), Diags.end());
566 }
567 }
Richard Smith745f5142012-01-27 01:14:48 +0000568
569 /// Should we continue evaluation as much as possible after encountering a
570 /// construct which can't be folded?
571 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000572 return CheckingPotentialConstantExpression &&
573 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000574 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000575 };
Richard Smithf15fda02012-02-02 01:16:57 +0000576
577 /// Object used to treat all foldable expressions as constant expressions.
578 struct FoldConstant {
579 bool Enabled;
580
581 explicit FoldConstant(EvalInfo &Info)
582 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
583 !Info.EvalStatus.HasSideEffects) {
584 }
585 // Treat the value we've computed since this object was created as constant.
586 void Fold(EvalInfo &Info) {
587 if (Enabled && !Info.EvalStatus.Diag->empty() &&
588 !Info.EvalStatus.HasSideEffects)
589 Info.EvalStatus.Diag->clear();
590 }
591 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000592
593 /// RAII object used to suppress diagnostics and side-effects from a
594 /// speculative evaluation.
595 class SpeculativeEvaluationRAII {
596 EvalInfo &Info;
597 Expr::EvalStatus Old;
598
599 public:
600 SpeculativeEvaluationRAII(EvalInfo &Info,
601 llvm::SmallVectorImpl<PartialDiagnosticAt>
602 *NewDiag = 0)
603 : Info(Info), Old(Info.EvalStatus) {
604 Info.EvalStatus.Diag = NewDiag;
605 }
606 ~SpeculativeEvaluationRAII() {
607 Info.EvalStatus = Old;
608 }
609 };
Richard Smith08d6e032011-12-16 19:06:07 +0000610}
Richard Smithbd552ef2011-10-31 05:52:43 +0000611
Richard Smithb4e85ed2012-01-06 16:39:00 +0000612bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
613 CheckSubobjectKind CSK) {
614 if (Invalid)
615 return false;
616 if (isOnePastTheEnd()) {
617 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
618 << CSK;
619 setInvalid();
620 return false;
621 }
622 return true;
623}
624
625void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
626 const Expr *E, uint64_t N) {
627 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
628 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
629 << static_cast<int>(N) << /*array*/ 0
630 << static_cast<unsigned>(MostDerivedArraySize);
631 else
632 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
633 << static_cast<int>(N) << /*non-array*/ 1;
634 setInvalid();
635}
636
Richard Smith08d6e032011-12-16 19:06:07 +0000637CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
638 const FunctionDecl *Callee, const LValue *This,
639 const CCValue *Arguments)
640 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000641 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000642 Info.CurrentCall = this;
643 ++Info.CallStackDepth;
644}
645
646CallStackFrame::~CallStackFrame() {
647 assert(Info.CurrentCall == this && "calls retired out of order");
648 --Info.CallStackDepth;
649 Info.CurrentCall = Caller;
650}
651
652/// Produce a string describing the given constexpr call.
653static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
654 unsigned ArgIndex = 0;
655 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000656 !isa<CXXConstructorDecl>(Frame->Callee) &&
657 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000658
659 if (!IsMemberCall)
660 Out << *Frame->Callee << '(';
661
662 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
663 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000664 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000665 Out << ", ";
666
667 const ParmVarDecl *Param = *I;
668 const CCValue &Arg = Frame->Arguments[ArgIndex];
669 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
670 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
671 else {
Richard Smith83587db2012-02-15 02:18:13 +0000672 // Convert the CCValue to an APValue without checking for constantness.
Richard Smith08d6e032011-12-16 19:06:07 +0000673 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
674 Arg.getLValueDesignator().Entries,
Richard Smith83587db2012-02-15 02:18:13 +0000675 Arg.getLValueDesignator().IsOnePastTheEnd,
676 Arg.getLValueCallIndex());
Richard Smith08d6e032011-12-16 19:06:07 +0000677 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
678 }
679
680 if (ArgIndex == 0 && IsMemberCall)
681 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000682 }
683
Richard Smith08d6e032011-12-16 19:06:07 +0000684 Out << ')';
685}
686
687void EvalInfo::addCallStack(unsigned Limit) {
688 // Determine which calls to skip, if any.
689 unsigned ActiveCalls = CallStackDepth - 1;
690 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
691 if (Limit && Limit < ActiveCalls) {
692 SkipStart = Limit / 2 + Limit % 2;
693 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000694 }
695
Richard Smith08d6e032011-12-16 19:06:07 +0000696 // Walk the call stack and add the diagnostics.
697 unsigned CallIdx = 0;
698 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
699 Frame = Frame->Caller, ++CallIdx) {
700 // Skip this call?
701 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
702 if (CallIdx == SkipStart) {
703 // Note that we're skipping calls.
704 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
705 << unsigned(ActiveCalls - Limit);
706 }
707 continue;
708 }
709
710 llvm::SmallVector<char, 128> Buffer;
711 llvm::raw_svector_ostream Out(Buffer);
712 describeCall(Frame, Out);
713 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
714 }
715}
716
717namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000718 struct ComplexValue {
719 private:
720 bool IsInt;
721
722 public:
723 APSInt IntReal, IntImag;
724 APFloat FloatReal, FloatImag;
725
726 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
727
728 void makeComplexFloat() { IsInt = false; }
729 bool isComplexFloat() const { return !IsInt; }
730 APFloat &getComplexFloatReal() { return FloatReal; }
731 APFloat &getComplexFloatImag() { return FloatImag; }
732
733 void makeComplexInt() { IsInt = true; }
734 bool isComplexInt() const { return IsInt; }
735 APSInt &getComplexIntReal() { return IntReal; }
736 APSInt &getComplexIntImag() { return IntImag; }
737
Richard Smith47a1eed2011-10-29 20:57:55 +0000738 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000739 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000740 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000741 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000742 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000743 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000744 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000745 assert(v.isComplexFloat() || v.isComplexInt());
746 if (v.isComplexFloat()) {
747 makeComplexFloat();
748 FloatReal = v.getComplexFloatReal();
749 FloatImag = v.getComplexFloatImag();
750 } else {
751 makeComplexInt();
752 IntReal = v.getComplexIntReal();
753 IntImag = v.getComplexIntImag();
754 }
755 }
John McCallf4cf1a12010-05-07 17:22:02 +0000756 };
John McCallefdb83e2010-05-07 21:00:08 +0000757
758 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000759 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000760 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000761 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000762 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000763
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000764 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000765 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000766 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000767 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000768 SubobjectDesignator &getLValueDesignator() { return Designator; }
769 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000770
Richard Smith47a1eed2011-10-29 20:57:55 +0000771 void moveInto(CCValue &V) const {
Richard Smith83587db2012-02-15 02:18:13 +0000772 V = CCValue(Base, Offset, CallIndex, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000773 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000774 void setFrom(const CCValue &V) {
775 assert(V.isLValue());
776 Base = V.getLValueBase();
777 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000778 CallIndex = V.getLValueCallIndex();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000779 Designator = V.getLValueDesignator();
780 }
781
Richard Smith83587db2012-02-15 02:18:13 +0000782 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000783 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000784 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000785 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000786 Designator = SubobjectDesignator(getType(B));
787 }
788
789 // Check that this LValue is not based on a null pointer. If it is, produce
790 // a diagnostic and mark the designator as invalid.
791 bool checkNullPointer(EvalInfo &Info, const Expr *E,
792 CheckSubobjectKind CSK) {
793 if (Designator.Invalid)
794 return false;
795 if (!Base) {
796 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
797 << CSK;
798 Designator.setInvalid();
799 return false;
800 }
801 return true;
802 }
803
804 // Check this LValue refers to an object. If not, set the designator to be
805 // invalid and emit a diagnostic.
806 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
807 return checkNullPointer(Info, E, CSK) &&
808 Designator.checkSubobject(Info, E, CSK);
809 }
810
811 void addDecl(EvalInfo &Info, const Expr *E,
812 const Decl *D, bool Virtual = false) {
813 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
814 Designator.addDeclUnchecked(D, Virtual);
815 }
816 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
817 checkSubobject(Info, E, CSK_ArrayToPointer);
818 Designator.addArrayUnchecked(CAT);
819 }
Richard Smith86024012012-02-18 22:04:06 +0000820 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
821 checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real);
822 Designator.addComplexUnchecked(EltTy, Imag);
823 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000824 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
825 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
826 return;
827 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000828 }
John McCallefdb83e2010-05-07 21:00:08 +0000829 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000830
831 struct MemberPtr {
832 MemberPtr() {}
833 explicit MemberPtr(const ValueDecl *Decl) :
834 DeclAndIsDerivedMember(Decl, false), Path() {}
835
836 /// The member or (direct or indirect) field referred to by this member
837 /// pointer, or 0 if this is a null member pointer.
838 const ValueDecl *getDecl() const {
839 return DeclAndIsDerivedMember.getPointer();
840 }
841 /// Is this actually a member of some type derived from the relevant class?
842 bool isDerivedMember() const {
843 return DeclAndIsDerivedMember.getInt();
844 }
845 /// Get the class which the declaration actually lives in.
846 const CXXRecordDecl *getContainingRecord() const {
847 return cast<CXXRecordDecl>(
848 DeclAndIsDerivedMember.getPointer()->getDeclContext());
849 }
850
851 void moveInto(CCValue &V) const {
852 V = CCValue(getDecl(), isDerivedMember(), Path);
853 }
854 void setFrom(const CCValue &V) {
855 assert(V.isMemberPointer());
856 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
857 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
858 Path.clear();
859 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
860 Path.insert(Path.end(), P.begin(), P.end());
861 }
862
863 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
864 /// whether the member is a member of some class derived from the class type
865 /// of the member pointer.
866 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
867 /// Path - The path of base/derived classes from the member declaration's
868 /// class (exclusive) to the class type of the member pointer (inclusive).
869 SmallVector<const CXXRecordDecl*, 4> Path;
870
871 /// Perform a cast towards the class of the Decl (either up or down the
872 /// hierarchy).
873 bool castBack(const CXXRecordDecl *Class) {
874 assert(!Path.empty());
875 const CXXRecordDecl *Expected;
876 if (Path.size() >= 2)
877 Expected = Path[Path.size() - 2];
878 else
879 Expected = getContainingRecord();
880 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
881 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
882 // if B does not contain the original member and is not a base or
883 // derived class of the class containing the original member, the result
884 // of the cast is undefined.
885 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
886 // (D::*). We consider that to be a language defect.
887 return false;
888 }
889 Path.pop_back();
890 return true;
891 }
892 /// Perform a base-to-derived member pointer cast.
893 bool castToDerived(const CXXRecordDecl *Derived) {
894 if (!getDecl())
895 return true;
896 if (!isDerivedMember()) {
897 Path.push_back(Derived);
898 return true;
899 }
900 if (!castBack(Derived))
901 return false;
902 if (Path.empty())
903 DeclAndIsDerivedMember.setInt(false);
904 return true;
905 }
906 /// Perform a derived-to-base member pointer cast.
907 bool castToBase(const CXXRecordDecl *Base) {
908 if (!getDecl())
909 return true;
910 if (Path.empty())
911 DeclAndIsDerivedMember.setInt(true);
912 if (isDerivedMember()) {
913 Path.push_back(Base);
914 return true;
915 }
916 return castBack(Base);
917 }
918 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000919
Richard Smithb02e4622012-02-01 01:42:44 +0000920 /// Compare two member pointers, which are assumed to be of the same type.
921 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
922 if (!LHS.getDecl() || !RHS.getDecl())
923 return !LHS.getDecl() && !RHS.getDecl();
924 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
925 return false;
926 return LHS.Path == RHS.Path;
927 }
928
Richard Smithc1c5f272011-12-13 06:39:58 +0000929 /// Kinds of constant expression checking, for diagnostics.
930 enum CheckConstantExpressionKind {
931 CCEK_Constant, ///< A normal constant.
932 CCEK_ReturnValue, ///< A constexpr function return value.
933 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
934 };
John McCallf4cf1a12010-05-07 17:22:02 +0000935}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000936
Richard Smith47a1eed2011-10-29 20:57:55 +0000937static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000938static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
939 const LValue &This, const Expr *E,
940 CheckConstantExpressionKind CCEK = CCEK_Constant,
941 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000942static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
943static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000944static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
945 EvalInfo &Info);
946static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000947static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000948static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000949 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000950static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000951static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000952
953//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000954// Misc utilities
955//===----------------------------------------------------------------------===//
956
Richard Smith180f4792011-11-10 06:34:14 +0000957/// Should this call expression be treated as a string literal?
958static bool IsStringLiteralCall(const CallExpr *E) {
959 unsigned Builtin = E->isBuiltinCall();
960 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
961 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
962}
963
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000964static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000965 // C++11 [expr.const]p3 An address constant expression is a prvalue core
966 // constant expression of pointer type that evaluates to...
967
968 // ... a null pointer value, or a prvalue core constant expression of type
969 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000970 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000971
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000972 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
973 // ... the address of an object with static storage duration,
974 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
975 return VD->hasGlobalStorage();
976 // ... the address of a function,
977 return isa<FunctionDecl>(D);
978 }
979
980 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000981 switch (E->getStmtClass()) {
982 default:
983 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000984 case Expr::CompoundLiteralExprClass: {
985 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
986 return CLE->isFileScope() && CLE->isLValue();
987 }
Richard Smith180f4792011-11-10 06:34:14 +0000988 // A string literal has static storage duration.
989 case Expr::StringLiteralClass:
990 case Expr::PredefinedExprClass:
991 case Expr::ObjCStringLiteralClass:
992 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000993 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000994 return true;
995 case Expr::CallExprClass:
996 return IsStringLiteralCall(cast<CallExpr>(E));
997 // For GCC compatibility, &&label has static storage duration.
998 case Expr::AddrLabelExprClass:
999 return true;
1000 // A Block literal expression may be used as the initialization value for
1001 // Block variables at global or local static scope.
1002 case Expr::BlockExprClass:
1003 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +00001004 case Expr::ImplicitValueInitExprClass:
1005 // FIXME:
1006 // We can never form an lvalue with an implicit value initialization as its
1007 // base through expression evaluation, so these only appear in one case: the
1008 // implicit variable declaration we invent when checking whether a constexpr
1009 // constructor can produce a constant expression. We must assume that such
1010 // an expression might be a global lvalue.
1011 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001012 }
John McCall42c8f872010-05-10 23:27:23 +00001013}
1014
Richard Smith83587db2012-02-15 02:18:13 +00001015static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1016 assert(Base && "no location for a null lvalue");
1017 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1018 if (VD)
1019 Info.Note(VD->getLocation(), diag::note_declared_at);
1020 else
1021 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
1022 diag::note_constexpr_temporary_here);
1023}
1024
Richard Smith9a17a682011-11-07 05:07:52 +00001025/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +00001026/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +00001027/// either LValue or CCValue. Return true if we can fold this expression,
1028/// whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00001029static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1030 QualType Type, const LValue &LVal) {
1031 bool IsReferenceType = Type->isReferenceType();
1032
Richard Smithc1c5f272011-12-13 06:39:58 +00001033 APValue::LValueBase Base = LVal.getLValueBase();
1034 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1035
Richard Smithb78ae972012-02-18 04:58:18 +00001036 // Check that the object is a global. Note that the fake 'this' object we
1037 // manufacture when checking potential constant expressions is conservatively
1038 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +00001039 if (!IsGlobalLValue(Base)) {
1040 if (Info.getLangOpts().CPlusPlus0x) {
1041 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001042 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1043 << IsReferenceType << !Designator.Entries.empty()
1044 << !!VD << VD;
1045 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001046 } else {
Richard Smith83587db2012-02-15 02:18:13 +00001047 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +00001048 }
Richard Smith61e61622012-01-12 06:08:57 +00001049 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +00001050 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001051 }
Richard Smith83587db2012-02-15 02:18:13 +00001052 assert((Info.CheckingPotentialConstantExpression ||
1053 LVal.getLValueCallIndex() == 0) &&
1054 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +00001055
1056 // Allow address constant expressions to be past-the-end pointers. This is
1057 // an extension: the standard requires them to point to an object.
1058 if (!IsReferenceType)
1059 return true;
1060
1061 // A reference constant expression must refer to an object.
1062 if (!Base) {
1063 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001064 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001065 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001066 }
1067
Richard Smithc1c5f272011-12-13 06:39:58 +00001068 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001069 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001070 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001071 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001072 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001073 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001074 }
1075
Richard Smith9a17a682011-11-07 05:07:52 +00001076 return true;
1077}
1078
Richard Smith51201882011-12-30 21:15:51 +00001079/// Check that this core constant expression is of literal type, and if not,
1080/// produce an appropriate diagnostic.
1081static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1082 if (!E->isRValue() || E->getType()->isLiteralType())
1083 return true;
1084
1085 // Prvalue constant expressions must be of literal types.
1086 if (Info.getLangOpts().CPlusPlus0x)
1087 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
1088 << E->getType();
1089 else
1090 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1091 return false;
1092}
1093
Richard Smith47a1eed2011-10-29 20:57:55 +00001094/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001095/// constant expression. If not, report an appropriate diagnostic. Does not
1096/// check that the expression is of literal type.
1097static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1098 QualType Type, const APValue &Value) {
1099 // Core issue 1454: For a literal constant expression of array or class type,
1100 // each subobject of its value shall have been initialized by a constant
1101 // expression.
1102 if (Value.isArray()) {
1103 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1104 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1105 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1106 Value.getArrayInitializedElt(I)))
1107 return false;
1108 }
1109 if (!Value.hasArrayFiller())
1110 return true;
1111 return CheckConstantExpression(Info, DiagLoc, EltTy,
1112 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001113 }
Richard Smith83587db2012-02-15 02:18:13 +00001114 if (Value.isUnion() && Value.getUnionField()) {
1115 return CheckConstantExpression(Info, DiagLoc,
1116 Value.getUnionField()->getType(),
1117 Value.getUnionValue());
1118 }
1119 if (Value.isStruct()) {
1120 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1121 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1122 unsigned BaseIndex = 0;
1123 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1124 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1125 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1126 Value.getStructBase(BaseIndex)))
1127 return false;
1128 }
1129 }
1130 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1131 I != E; ++I) {
1132 if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
1133 Value.getStructField((*I)->getFieldIndex())))
1134 return false;
1135 }
1136 }
1137
1138 if (Value.isLValue()) {
1139 CCValue Val(Info.Ctx, Value, CCValue::GlobalValue());
1140 LValue LVal;
1141 LVal.setFrom(Val);
1142 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1143 }
1144
1145 // Everything else is fine.
1146 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001147}
1148
Richard Smith9e36b532011-10-31 05:11:32 +00001149const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001150 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001151}
1152
1153static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001154 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001155}
1156
Richard Smith65ac5982011-11-01 21:06:14 +00001157static bool IsWeakLValue(const LValue &Value) {
1158 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001159 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001160}
1161
Richard Smithe24f5fc2011-11-17 22:56:20 +00001162static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001163 // A null base expression indicates a null pointer. These are always
1164 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001165 if (!Value.getLValueBase()) {
1166 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001167 return true;
1168 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001169
Richard Smithe24f5fc2011-11-17 22:56:20 +00001170 // We have a non-null base. These are generally known to be true, but if it's
1171 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001172 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001173 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001174 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001175}
1176
Richard Smith47a1eed2011-10-29 20:57:55 +00001177static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001178 switch (Val.getKind()) {
1179 case APValue::Uninitialized:
1180 return false;
1181 case APValue::Int:
1182 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001183 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001184 case APValue::Float:
1185 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001186 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001187 case APValue::ComplexInt:
1188 Result = Val.getComplexIntReal().getBoolValue() ||
1189 Val.getComplexIntImag().getBoolValue();
1190 return true;
1191 case APValue::ComplexFloat:
1192 Result = !Val.getComplexFloatReal().isZero() ||
1193 !Val.getComplexFloatImag().isZero();
1194 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001195 case APValue::LValue:
1196 return EvalPointerValueAsBool(Val, Result);
1197 case APValue::MemberPointer:
1198 Result = Val.getMemberPointerDecl();
1199 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001200 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001201 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001202 case APValue::Struct:
1203 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001204 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001205 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001206 }
1207
Richard Smithc49bd112011-10-28 17:51:58 +00001208 llvm_unreachable("unknown APValue kind");
1209}
1210
1211static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1212 EvalInfo &Info) {
1213 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001214 CCValue Val;
1215 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001216 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001217 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001218}
1219
Richard Smithc1c5f272011-12-13 06:39:58 +00001220template<typename T>
1221static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1222 const T &SrcValue, QualType DestType) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001223 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001224 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001225 return false;
1226}
1227
1228static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1229 QualType SrcType, const APFloat &Value,
1230 QualType DestType, APSInt &Result) {
1231 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001232 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001233 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Richard Smithc1c5f272011-12-13 06:39:58 +00001235 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001236 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001237 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1238 & APFloat::opInvalidOp)
1239 return HandleOverflow(Info, E, Value, DestType);
1240 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001241}
1242
Richard Smithc1c5f272011-12-13 06:39:58 +00001243static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1244 QualType SrcType, QualType DestType,
1245 APFloat &Result) {
1246 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001247 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001248 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1249 APFloat::rmNearestTiesToEven, &ignored)
1250 & APFloat::opOverflow)
1251 return HandleOverflow(Info, E, Value, DestType);
1252 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001253}
1254
Richard Smithf72fccf2012-01-30 22:27:01 +00001255static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1256 QualType DestType, QualType SrcType,
1257 APSInt &Value) {
1258 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001259 APSInt Result = Value;
1260 // Figure out if this is a truncate, extend or noop cast.
1261 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001262 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001263 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001264 return Result;
1265}
1266
Richard Smithc1c5f272011-12-13 06:39:58 +00001267static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1268 QualType SrcType, const APSInt &Value,
1269 QualType DestType, APFloat &Result) {
1270 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1271 if (Result.convertFromAPInt(Value, Value.isSigned(),
1272 APFloat::rmNearestTiesToEven)
1273 & APFloat::opOverflow)
1274 return HandleOverflow(Info, E, Value, DestType);
1275 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001276}
1277
Eli Friedmane6a24e82011-12-22 03:51:45 +00001278static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1279 llvm::APInt &Res) {
1280 CCValue SVal;
1281 if (!Evaluate(SVal, Info, E))
1282 return false;
1283 if (SVal.isInt()) {
1284 Res = SVal.getInt();
1285 return true;
1286 }
1287 if (SVal.isFloat()) {
1288 Res = SVal.getFloat().bitcastToAPInt();
1289 return true;
1290 }
1291 if (SVal.isVector()) {
1292 QualType VecTy = E->getType();
1293 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1294 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1295 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1296 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1297 Res = llvm::APInt::getNullValue(VecSize);
1298 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1299 APValue &Elt = SVal.getVectorElt(i);
1300 llvm::APInt EltAsInt;
1301 if (Elt.isInt()) {
1302 EltAsInt = Elt.getInt();
1303 } else if (Elt.isFloat()) {
1304 EltAsInt = Elt.getFloat().bitcastToAPInt();
1305 } else {
1306 // Don't try to handle vectors of anything other than int or float
1307 // (not sure if it's possible to hit this case).
1308 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1309 return false;
1310 }
1311 unsigned BaseEltSize = EltAsInt.getBitWidth();
1312 if (BigEndian)
1313 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1314 else
1315 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1316 }
1317 return true;
1318 }
1319 // Give up if the input isn't an int, float, or vector. For example, we
1320 // reject "(v4i16)(intptr_t)&a".
1321 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1322 return false;
1323}
1324
Richard Smithb4e85ed2012-01-06 16:39:00 +00001325/// Cast an lvalue referring to a base subobject to a derived class, by
1326/// truncating the lvalue's path to the given length.
1327static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1328 const RecordDecl *TruncatedType,
1329 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001330 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001331
1332 // Check we actually point to a derived class object.
1333 if (TruncatedElements == D.Entries.size())
1334 return true;
1335 assert(TruncatedElements >= D.MostDerivedPathLength &&
1336 "not casting to a derived class");
1337 if (!Result.checkSubobject(Info, E, CSK_Derived))
1338 return false;
1339
1340 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001341 const RecordDecl *RD = TruncatedType;
1342 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001343 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1344 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001345 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001346 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001347 else
Richard Smith180f4792011-11-10 06:34:14 +00001348 Result.Offset -= Layout.getBaseClassOffset(Base);
1349 RD = Base;
1350 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001351 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001352 return true;
1353}
1354
Richard Smithb4e85ed2012-01-06 16:39:00 +00001355static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001356 const CXXRecordDecl *Derived,
1357 const CXXRecordDecl *Base,
1358 const ASTRecordLayout *RL = 0) {
1359 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1360 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001361 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001362}
1363
Richard Smithb4e85ed2012-01-06 16:39:00 +00001364static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001365 const CXXRecordDecl *DerivedDecl,
1366 const CXXBaseSpecifier *Base) {
1367 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1368
1369 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001370 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001371 return true;
1372 }
1373
Richard Smithb4e85ed2012-01-06 16:39:00 +00001374 SubobjectDesignator &D = Obj.Designator;
1375 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001376 return false;
1377
Richard Smithb4e85ed2012-01-06 16:39:00 +00001378 // Extract most-derived object and corresponding type.
1379 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1380 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1381 return false;
1382
1383 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001384 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1385 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001386 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001387 return true;
1388}
1389
1390/// Update LVal to refer to the given field, which must be a member of the type
1391/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001392static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001393 const FieldDecl *FD,
1394 const ASTRecordLayout *RL = 0) {
1395 if (!RL)
1396 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1397
1398 unsigned I = FD->getFieldIndex();
1399 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001400 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001401}
1402
Richard Smithd9b02e72012-01-25 22:15:11 +00001403/// Update LVal to refer to the given indirect field.
1404static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1405 LValue &LVal,
1406 const IndirectFieldDecl *IFD) {
1407 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1408 CE = IFD->chain_end(); C != CE; ++C)
1409 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1410}
1411
Richard Smith180f4792011-11-10 06:34:14 +00001412/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001413static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1414 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001415 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1416 // extension.
1417 if (Type->isVoidType() || Type->isFunctionType()) {
1418 Size = CharUnits::One();
1419 return true;
1420 }
1421
1422 if (!Type->isConstantSizeType()) {
1423 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001424 // FIXME: Better diagnostic.
1425 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001426 return false;
1427 }
1428
1429 Size = Info.Ctx.getTypeSizeInChars(Type);
1430 return true;
1431}
1432
1433/// Update a pointer value to model pointer arithmetic.
1434/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001435/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001436/// \param LVal - The pointer value to be updated.
1437/// \param EltTy - The pointee type represented by LVal.
1438/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001439static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1440 LValue &LVal, QualType EltTy,
1441 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001442 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001443 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001444 return false;
1445
1446 // Compute the new offset in the appropriate width.
1447 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001448 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001449 return true;
1450}
1451
Richard Smith86024012012-02-18 22:04:06 +00001452/// Update an lvalue to refer to a component of a complex number.
1453/// \param Info - Information about the ongoing evaluation.
1454/// \param LVal - The lvalue to be updated.
1455/// \param EltTy - The complex number's component type.
1456/// \param Imag - False for the real component, true for the imaginary.
1457static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1458 LValue &LVal, QualType EltTy,
1459 bool Imag) {
1460 if (Imag) {
1461 CharUnits SizeOfComponent;
1462 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1463 return false;
1464 LVal.Offset += SizeOfComponent;
1465 }
1466 LVal.addComplex(Info, E, EltTy, Imag);
1467 return true;
1468}
1469
Richard Smith03f96112011-10-24 17:54:18 +00001470/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001471static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1472 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001473 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001474 // If this is a parameter to an active constexpr function call, perform
1475 // argument substitution.
1476 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001477 // Assume arguments of a potential constant expression are unknown
1478 // constant expressions.
1479 if (Info.CheckingPotentialConstantExpression)
1480 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001481 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001482 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001483 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001484 }
Richard Smith177dce72011-11-01 16:57:24 +00001485 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1486 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001487 }
Richard Smith03f96112011-10-24 17:54:18 +00001488
Richard Smith099e7f62011-12-19 06:19:21 +00001489 // Dig out the initializer, and use the declaration which it's attached to.
1490 const Expr *Init = VD->getAnyInitializer(VD);
1491 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001492 // If we're checking a potential constant expression, the variable could be
1493 // initialized later.
1494 if (!Info.CheckingPotentialConstantExpression)
1495 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001496 return false;
1497 }
1498
Richard Smith180f4792011-11-10 06:34:14 +00001499 // If we're currently evaluating the initializer of this declaration, use that
1500 // in-flight value.
1501 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001502 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1503 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001504 return !Result.isUninit();
1505 }
1506
Richard Smith65ac5982011-11-01 21:06:14 +00001507 // Never evaluate the initializer of a weak variable. We can't be sure that
1508 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001509 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001510 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001511 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001512 }
Richard Smith65ac5982011-11-01 21:06:14 +00001513
Richard Smith099e7f62011-12-19 06:19:21 +00001514 // Check that we can fold the initializer. In C++, we will have already done
1515 // this in the cases where it matters for conformance.
1516 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1517 if (!VD->evaluateValue(Notes)) {
1518 Info.Diag(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 Smith47a1eed2011-10-29 20:57:55 +00001522 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001523 } else if (!VD->checkInitIsICE()) {
1524 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1525 Notes.size() + 1) << VD;
1526 Info.Note(VD->getLocation(), diag::note_declared_at);
1527 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001528 }
Richard Smith03f96112011-10-24 17:54:18 +00001529
Richard Smithb4e85ed2012-01-06 16:39:00 +00001530 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001531 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001532}
1533
Richard Smithc49bd112011-10-28 17:51:58 +00001534static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001535 Qualifiers Quals = T.getQualifiers();
1536 return Quals.hasConst() && !Quals.hasVolatile();
1537}
1538
Richard Smith59efe262011-11-11 04:05:33 +00001539/// Get the base index of the given base class within an APValue representing
1540/// the given derived class.
1541static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1542 const CXXRecordDecl *Base) {
1543 Base = Base->getCanonicalDecl();
1544 unsigned Index = 0;
1545 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1546 E = Derived->bases_end(); I != E; ++I, ++Index) {
1547 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1548 return Index;
1549 }
1550
1551 llvm_unreachable("base class missing from derived class's bases list");
1552}
1553
Richard Smithf3908f22012-02-17 03:35:37 +00001554/// Extract the value of a character from a string literal.
1555static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1556 uint64_t Index) {
1557 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1558 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1559 assert(S && "unexpected string literal expression kind");
1560
1561 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1562 Lit->getType()->getArrayElementTypeNoTypeQual()->isUnsignedIntegerType());
1563 if (Index < S->getLength())
1564 Value = S->getCodeUnit(Index);
1565 return Value;
1566}
1567
Richard Smithcc5d4f62011-11-07 09:22:26 +00001568/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001569static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1570 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001571 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001572 if (Sub.Invalid)
1573 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001574 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001575 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001576 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001577 (unsigned)diag::note_constexpr_read_past_end :
1578 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001579 return false;
1580 }
Richard Smithf64699e2011-11-11 08:28:03 +00001581 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001582 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001583 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1584 // This object might be initialized later.
1585 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001586
Richard Smithcc5d4f62011-11-07 09:22:26 +00001587 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001588 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001589 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001590 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001591 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001592 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001593 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001594 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001595 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001596 // Note, it should not be possible to form a pointer with a valid
1597 // designator which points more than one past the end of the array.
1598 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001599 (unsigned)diag::note_constexpr_read_past_end :
1600 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001601 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001602 }
Richard Smithf3908f22012-02-17 03:35:37 +00001603 // An array object is represented as either an Array APValue or as an
1604 // LValue which refers to a string literal.
1605 if (O->isLValue()) {
1606 assert(I == N - 1 && "extracting subobject of character?");
1607 assert(!O->hasLValuePath() || O->getLValuePath().empty());
1608 Obj = CCValue(ExtractStringLiteralCharacter(
1609 Info, O->getLValueBase().get<const Expr*>(), Index));
1610 return true;
1611 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001612 O = &O->getArrayInitializedElt(Index);
1613 else
1614 O = &O->getArrayFiller();
1615 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001616 } else if (ObjType->isAnyComplexType()) {
1617 // Next subobject is a complex number.
1618 uint64_t Index = Sub.Entries[I].ArrayIndex;
1619 if (Index > 1) {
1620 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
1621 (unsigned)diag::note_constexpr_read_past_end :
1622 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1623 return false;
1624 }
1625 assert(I == N - 1 && "extracting subobject of scalar?");
1626 if (O->isComplexInt()) {
1627 Obj = CCValue(Index ? O->getComplexIntImag()
1628 : O->getComplexIntReal());
1629 } else {
1630 assert(O->isComplexFloat());
1631 Obj = CCValue(Index ? O->getComplexFloatImag()
1632 : O->getComplexFloatReal());
1633 }
1634 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001635 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001636 if (Field->isMutable()) {
1637 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_mutable, 1)
1638 << Field;
1639 Info.Note(Field->getLocation(), diag::note_declared_at);
1640 return false;
1641 }
1642
Richard Smith180f4792011-11-10 06:34:14 +00001643 // Next subobject is a class, struct or union field.
1644 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1645 if (RD->isUnion()) {
1646 const FieldDecl *UnionField = O->getUnionField();
1647 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001648 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001649 Info.Diag(E->getExprLoc(),
1650 diag::note_constexpr_read_inactive_union_member)
1651 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001652 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001653 }
Richard Smith180f4792011-11-10 06:34:14 +00001654 O = &O->getUnionValue();
1655 } else
1656 O = &O->getStructField(Field->getFieldIndex());
1657 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001658
1659 if (ObjType.isVolatileQualified()) {
1660 if (Info.getLangOpts().CPlusPlus) {
1661 // FIXME: Include a description of the path to the volatile subobject.
1662 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1663 << 2 << Field;
1664 Info.Note(Field->getLocation(), diag::note_declared_at);
1665 } else {
1666 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1667 }
1668 return false;
1669 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001670 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001671 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001672 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1673 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1674 O = &O->getStructBase(getBaseIndex(Derived, Base));
1675 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001676 }
Richard Smith180f4792011-11-10 06:34:14 +00001677
Richard Smithf48fdb02011-12-09 22:58:01 +00001678 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001679 if (!Info.CheckingPotentialConstantExpression)
1680 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001681 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001682 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001683 }
1684
Richard Smithb4e85ed2012-01-06 16:39:00 +00001685 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001686 return true;
1687}
1688
Richard Smithf15fda02012-02-02 01:16:57 +00001689/// Find the position where two subobject designators diverge, or equivalently
1690/// the length of the common initial subsequence.
1691static unsigned FindDesignatorMismatch(QualType ObjType,
1692 const SubobjectDesignator &A,
1693 const SubobjectDesignator &B,
1694 bool &WasArrayIndex) {
1695 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1696 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001697 if (!ObjType.isNull() &&
1698 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001699 // Next subobject is an array element.
1700 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1701 WasArrayIndex = true;
1702 return I;
1703 }
Richard Smith86024012012-02-18 22:04:06 +00001704 if (ObjType->isAnyComplexType())
1705 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1706 else
1707 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001708 } else {
1709 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1710 WasArrayIndex = false;
1711 return I;
1712 }
1713 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1714 // Next subobject is a field.
1715 ObjType = FD->getType();
1716 else
1717 // Next subobject is a base class.
1718 ObjType = QualType();
1719 }
1720 }
1721 WasArrayIndex = false;
1722 return I;
1723}
1724
1725/// Determine whether the given subobject designators refer to elements of the
1726/// same array object.
1727static bool AreElementsOfSameArray(QualType ObjType,
1728 const SubobjectDesignator &A,
1729 const SubobjectDesignator &B) {
1730 if (A.Entries.size() != B.Entries.size())
1731 return false;
1732
1733 bool IsArray = A.MostDerivedArraySize != 0;
1734 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1735 // A is a subobject of the array element.
1736 return false;
1737
1738 // If A (and B) designates an array element, the last entry will be the array
1739 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1740 // of length 1' case, and the entire path must match.
1741 bool WasArrayIndex;
1742 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1743 return CommonLength >= A.Entries.size() - IsArray;
1744}
1745
Richard Smith180f4792011-11-10 06:34:14 +00001746/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1747/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1748/// for looking up the glvalue referred to by an entity of reference type.
1749///
1750/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001751/// \param Conv - The expression for which we are performing the conversion.
1752/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001753/// \param Type - The type we expect this conversion to produce, before
1754/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001755/// \param LVal - The glvalue on which we are attempting to perform this action.
1756/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001757static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1758 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001759 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001760 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1761 if (!Info.getLangOpts().CPlusPlus)
1762 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1763
Richard Smithb4e85ed2012-01-06 16:39:00 +00001764 if (LVal.Designator.Invalid)
1765 // A diagnostic will have already been produced.
1766 return false;
1767
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001768 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith7098cbd2011-12-21 05:04:46 +00001769 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001770
Richard Smithf48fdb02011-12-09 22:58:01 +00001771 if (!LVal.Base) {
1772 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001773 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1774 return false;
1775 }
1776
Richard Smith83587db2012-02-15 02:18:13 +00001777 CallStackFrame *Frame = 0;
1778 if (LVal.CallIndex) {
1779 Frame = Info.getCallFrame(LVal.CallIndex);
1780 if (!Frame) {
1781 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1782 NoteLValueLocation(Info, LVal.Base);
1783 return false;
1784 }
1785 }
1786
Richard Smith7098cbd2011-12-21 05:04:46 +00001787 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1788 // is not a constant expression (even if the object is non-volatile). We also
1789 // apply this rule to C++98, in order to conform to the expected 'volatile'
1790 // semantics.
1791 if (Type.isVolatileQualified()) {
1792 if (Info.getLangOpts().CPlusPlus)
1793 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1794 else
1795 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001796 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001797 }
Richard Smithc49bd112011-10-28 17:51:58 +00001798
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001799 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001800 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1801 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001802 // expressions are constant expressions too. Inside constexpr functions,
1803 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001804 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001805 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf15fda02012-02-02 01:16:57 +00001806 if (const VarDecl *VDef = VD->getDefinition())
1807 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001808 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001809 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001810 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001811 }
1812
Richard Smith7098cbd2011-12-21 05:04:46 +00001813 // DR1313: If the object is volatile-qualified but the glvalue was not,
1814 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001815 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001816 if (VT.isVolatileQualified()) {
1817 if (Info.getLangOpts().CPlusPlus) {
1818 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1819 Info.Note(VD->getLocation(), diag::note_declared_at);
1820 } else {
1821 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001822 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001823 return false;
1824 }
1825
1826 if (!isa<ParmVarDecl>(VD)) {
1827 if (VD->isConstexpr()) {
1828 // OK, we can read this variable.
1829 } else if (VT->isIntegralOrEnumerationType()) {
1830 if (!VT.isConstQualified()) {
1831 if (Info.getLangOpts().CPlusPlus) {
1832 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1833 Info.Note(VD->getLocation(), diag::note_declared_at);
1834 } else {
1835 Info.Diag(Loc);
1836 }
1837 return false;
1838 }
1839 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1840 // We support folding of const floating-point types, in order to make
1841 // static const data members of such types (supported as an extension)
1842 // more useful.
1843 if (Info.getLangOpts().CPlusPlus0x) {
1844 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1845 Info.Note(VD->getLocation(), diag::note_declared_at);
1846 } else {
1847 Info.CCEDiag(Loc);
1848 }
1849 } else {
1850 // FIXME: Allow folding of values of any literal type in all languages.
1851 if (Info.getLangOpts().CPlusPlus0x) {
1852 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1853 Info.Note(VD->getLocation(), diag::note_declared_at);
1854 } else {
1855 Info.Diag(Loc);
1856 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001857 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001858 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001859 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001860
Richard Smithf48fdb02011-12-09 22:58:01 +00001861 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001862 return false;
1863
Richard Smith47a1eed2011-10-29 20:57:55 +00001864 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001865 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001866
1867 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1868 // conversion. This happens when the declaration and the lvalue should be
1869 // considered synonymous, for instance when initializing an array of char
1870 // from a string literal. Continue as if the initializer lvalue was the
1871 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001872 assert(RVal.getLValueOffset().isZero() &&
1873 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001874 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001875
1876 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1877 Frame = Info.getCallFrame(CallIndex);
1878 if (!Frame) {
1879 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1880 NoteLValueLocation(Info, RVal.getLValueBase());
1881 return false;
1882 }
1883 } else {
1884 Frame = 0;
1885 }
Richard Smithc49bd112011-10-28 17:51:58 +00001886 }
1887
Richard Smith7098cbd2011-12-21 05:04:46 +00001888 // Volatile temporary objects cannot be read in constant expressions.
1889 if (Base->getType().isVolatileQualified()) {
1890 if (Info.getLangOpts().CPlusPlus) {
1891 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1892 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1893 } else {
1894 Info.Diag(Loc);
1895 }
1896 return false;
1897 }
1898
Richard Smithcc5d4f62011-11-07 09:22:26 +00001899 if (Frame) {
1900 // If this is a temporary expression with a nontrivial initializer, grab the
1901 // value from the relevant stack frame.
1902 RVal = Frame->Temporaries[Base];
1903 } else if (const CompoundLiteralExpr *CLE
1904 = dyn_cast<CompoundLiteralExpr>(Base)) {
1905 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1906 // initializer until now for such expressions. Such an expression can't be
1907 // an ICE in C, so this only matters for fold.
1908 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1909 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1910 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001911 } else if (isa<StringLiteral>(Base)) {
1912 // We represent a string literal array as an lvalue pointing at the
1913 // corresponding expression, rather than building an array of chars.
1914 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1915 RVal = CCValue(Info.Ctx,
1916 APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0),
1917 CCValue::GlobalValue());
Richard Smithf48fdb02011-12-09 22:58:01 +00001918 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001919 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001920 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001921 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001922
Richard Smithf48fdb02011-12-09 22:58:01 +00001923 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1924 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001925}
1926
Richard Smith59efe262011-11-11 04:05:33 +00001927/// Build an lvalue for the object argument of a member function call.
1928static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1929 LValue &This) {
1930 if (Object->getType()->isPointerType())
1931 return EvaluatePointer(Object, This, Info);
1932
1933 if (Object->isGLValue())
1934 return EvaluateLValue(Object, This, Info);
1935
Richard Smithe24f5fc2011-11-17 22:56:20 +00001936 if (Object->getType()->isLiteralType())
1937 return EvaluateTemporary(Object, This, Info);
1938
1939 return false;
1940}
1941
1942/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1943/// lvalue referring to the result.
1944///
1945/// \param Info - Information about the ongoing evaluation.
1946/// \param BO - The member pointer access operation.
1947/// \param LV - Filled in with a reference to the resulting object.
1948/// \param IncludeMember - Specifies whether the member itself is included in
1949/// the resulting LValue subobject designator. This is not possible when
1950/// creating a bound member function.
1951/// \return The field or method declaration to which the member pointer refers,
1952/// or 0 if evaluation fails.
1953static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1954 const BinaryOperator *BO,
1955 LValue &LV,
1956 bool IncludeMember = true) {
1957 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1958
Richard Smith745f5142012-01-27 01:14:48 +00001959 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1960 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001961 return 0;
1962
1963 MemberPtr MemPtr;
1964 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1965 return 0;
1966
1967 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1968 // member value, the behavior is undefined.
1969 if (!MemPtr.getDecl())
1970 return 0;
1971
Richard Smith745f5142012-01-27 01:14:48 +00001972 if (!EvalObjOK)
1973 return 0;
1974
Richard Smithe24f5fc2011-11-17 22:56:20 +00001975 if (MemPtr.isDerivedMember()) {
1976 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001977 // The end of the derived-to-base path for the base object must match the
1978 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001979 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001980 LV.Designator.Entries.size())
1981 return 0;
1982 unsigned PathLengthToMember =
1983 LV.Designator.Entries.size() - MemPtr.Path.size();
1984 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1985 const CXXRecordDecl *LVDecl = getAsBaseClass(
1986 LV.Designator.Entries[PathLengthToMember + I]);
1987 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1988 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1989 return 0;
1990 }
1991
1992 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001993 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1994 PathLengthToMember))
1995 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001996 } else if (!MemPtr.Path.empty()) {
1997 // Extend the LValue path with the member pointer's path.
1998 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1999 MemPtr.Path.size() + IncludeMember);
2000
2001 // Walk down to the appropriate base class.
2002 QualType LVType = BO->getLHS()->getType();
2003 if (const PointerType *PT = LVType->getAs<PointerType>())
2004 LVType = PT->getPointeeType();
2005 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2006 assert(RD && "member pointer access on non-class-type expression");
2007 // The first class in the path is that of the lvalue.
2008 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2009 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00002010 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002011 RD = Base;
2012 }
2013 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002014 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002015 }
2016
2017 // Add the member. Note that we cannot build bound member functions here.
2018 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002019 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
2020 HandleLValueMember(Info, BO, LV, FD);
2021 else if (const IndirectFieldDecl *IFD =
2022 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
2023 HandleLValueIndirectMember(Info, BO, LV, IFD);
2024 else
2025 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00002026 }
2027
2028 return MemPtr.getDecl();
2029}
2030
2031/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2032/// the provided lvalue, which currently refers to the base object.
2033static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2034 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002035 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002036 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002037 return false;
2038
Richard Smithb4e85ed2012-01-06 16:39:00 +00002039 QualType TargetQT = E->getType();
2040 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2041 TargetQT = PT->getPointeeType();
2042
2043 // Check this cast lands within the final derived-to-base subobject path.
2044 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
2045 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
2046 << D.MostDerivedType << TargetQT;
2047 return false;
2048 }
2049
Richard Smithe24f5fc2011-11-17 22:56:20 +00002050 // Check the type of the final cast. We don't need to check the path,
2051 // since a cast can only be formed if the path is unique.
2052 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002053 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2054 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002055 if (NewEntriesSize == D.MostDerivedPathLength)
2056 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2057 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002058 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002059 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
2060 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
2061 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002062 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002063 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002064
2065 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002066 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002067}
2068
Mike Stumpc4c90452009-10-27 22:09:17 +00002069namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002070enum EvalStmtResult {
2071 /// Evaluation failed.
2072 ESR_Failed,
2073 /// Hit a 'return' statement.
2074 ESR_Returned,
2075 /// Evaluation succeeded.
2076 ESR_Succeeded
2077};
2078}
2079
2080// Evaluate a statement.
Richard Smith83587db2012-02-15 02:18:13 +00002081static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002082 const Stmt *S) {
2083 switch (S->getStmtClass()) {
2084 default:
2085 return ESR_Failed;
2086
2087 case Stmt::NullStmtClass:
2088 case Stmt::DeclStmtClass:
2089 return ESR_Succeeded;
2090
Richard Smithc1c5f272011-12-13 06:39:58 +00002091 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002092 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002093 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002094 return ESR_Failed;
2095 return ESR_Returned;
2096 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002097
2098 case Stmt::CompoundStmtClass: {
2099 const CompoundStmt *CS = cast<CompoundStmt>(S);
2100 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2101 BE = CS->body_end(); BI != BE; ++BI) {
2102 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2103 if (ESR != ESR_Succeeded)
2104 return ESR;
2105 }
2106 return ESR_Succeeded;
2107 }
2108 }
2109}
2110
Richard Smith61802452011-12-22 02:22:31 +00002111/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2112/// default constructor. If so, we'll fold it whether or not it's marked as
2113/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2114/// so we need special handling.
2115static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002116 const CXXConstructorDecl *CD,
2117 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002118 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2119 return false;
2120
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002121 // Value-initialization does not call a trivial default constructor, so such a
2122 // call is a core constant expression whether or not the constructor is
2123 // constexpr.
2124 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002125 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002126 // FIXME: If DiagDecl is an implicitly-declared special member function,
2127 // we should be much more explicit about why it's not constexpr.
2128 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2129 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2130 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002131 } else {
2132 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2133 }
2134 }
2135 return true;
2136}
2137
Richard Smithc1c5f272011-12-13 06:39:58 +00002138/// CheckConstexprFunction - Check that a function can be called in a constant
2139/// expression.
2140static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2141 const FunctionDecl *Declaration,
2142 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002143 // Potential constant expressions can contain calls to declared, but not yet
2144 // defined, constexpr functions.
2145 if (Info.CheckingPotentialConstantExpression && !Definition &&
2146 Declaration->isConstexpr())
2147 return false;
2148
Richard Smithc1c5f272011-12-13 06:39:58 +00002149 // Can we evaluate this function call?
2150 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2151 return true;
2152
2153 if (Info.getLangOpts().CPlusPlus0x) {
2154 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002155 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2156 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002157 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2158 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2159 << DiagDecl;
2160 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2161 } else {
2162 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2163 }
2164 return false;
2165}
2166
Richard Smith180f4792011-11-10 06:34:14 +00002167namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00002168typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002169}
2170
2171/// EvaluateArgs - Evaluate the arguments to a function call.
2172static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2173 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002174 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002175 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002176 I != E; ++I) {
2177 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2178 // If we're checking for a potential constant expression, evaluate all
2179 // initializers even if some of them fail.
2180 if (!Info.keepEvaluatingAfterFailure())
2181 return false;
2182 Success = false;
2183 }
2184 }
2185 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002186}
2187
Richard Smithd0dccea2011-10-28 22:34:42 +00002188/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002189static bool HandleFunctionCall(SourceLocation CallLoc,
2190 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002191 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith83587db2012-02-15 02:18:13 +00002192 EvalInfo &Info, CCValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002193 ArgVector ArgValues(Args.size());
2194 if (!EvaluateArgs(Args, ArgValues, Info))
2195 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002196
Richard Smith745f5142012-01-27 01:14:48 +00002197 if (!Info.CheckCallLimit(CallLoc))
2198 return false;
2199
2200 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002201 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2202}
2203
Richard Smith180f4792011-11-10 06:34:14 +00002204/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002205static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002206 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002207 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002208 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002209 ArgVector ArgValues(Args.size());
2210 if (!EvaluateArgs(Args, ArgValues, Info))
2211 return false;
2212
Richard Smith745f5142012-01-27 01:14:48 +00002213 if (!Info.CheckCallLimit(CallLoc))
2214 return false;
2215
Richard Smith86c3ae42012-02-13 03:54:03 +00002216 const CXXRecordDecl *RD = Definition->getParent();
2217 if (RD->getNumVBases()) {
2218 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2219 return false;
2220 }
2221
Richard Smith745f5142012-01-27 01:14:48 +00002222 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002223
2224 // If it's a delegating constructor, just delegate.
2225 if (Definition->isDelegatingConstructor()) {
2226 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002227 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002228 }
2229
Richard Smith610a60c2012-01-10 04:32:03 +00002230 // For a trivial copy or move constructor, perform an APValue copy. This is
2231 // essential for unions, where the operations performed by the constructor
2232 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002233 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002234 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2235 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002236 LValue RHS;
2237 RHS.setFrom(ArgValues[0]);
2238 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00002239 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2240 RHS, Value))
2241 return false;
2242 assert((Value.isStruct() || Value.isUnion()) &&
2243 "trivial copy/move from non-class type?");
2244 // Any CCValue of class type must already be a constant expression.
2245 Result = Value;
2246 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00002247 }
2248
2249 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002250 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002251 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2252 std::distance(RD->field_begin(), RD->field_end()));
2253
2254 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2255
Richard Smith745f5142012-01-27 01:14:48 +00002256 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002257 unsigned BasesSeen = 0;
2258#ifndef NDEBUG
2259 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2260#endif
2261 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2262 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002263 LValue Subobject = This;
2264 APValue *Value = &Result;
2265
2266 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002267 if ((*I)->isBaseInitializer()) {
2268 QualType BaseType((*I)->getBaseClass(), 0);
2269#ifndef NDEBUG
2270 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002271 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002272 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2273 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2274 "base class initializers not in expected order");
2275 ++BaseIt;
2276#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002277 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002278 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002279 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002280 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002281 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002282 if (RD->isUnion()) {
2283 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002284 Value = &Result.getUnionValue();
2285 } else {
2286 Value = &Result.getStructField(FD->getFieldIndex());
2287 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002288 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002289 // Walk the indirect field decl's chain to find the object to initialize,
2290 // and make sure we've initialized every step along it.
2291 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2292 CE = IFD->chain_end();
2293 C != CE; ++C) {
2294 FieldDecl *FD = cast<FieldDecl>(*C);
2295 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2296 // Switch the union field if it differs. This happens if we had
2297 // preceding zero-initialization, and we're now initializing a union
2298 // subobject other than the first.
2299 // FIXME: In this case, the values of the other subobjects are
2300 // specified, since zero-initialization sets all padding bits to zero.
2301 if (Value->isUninit() ||
2302 (Value->isUnion() && Value->getUnionField() != FD)) {
2303 if (CD->isUnion())
2304 *Value = APValue(FD);
2305 else
2306 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2307 std::distance(CD->field_begin(), CD->field_end()));
2308 }
Richard Smith745f5142012-01-27 01:14:48 +00002309 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002310 if (CD->isUnion())
2311 Value = &Value->getUnionValue();
2312 else
2313 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002314 }
Richard Smith180f4792011-11-10 06:34:14 +00002315 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002316 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002317 }
Richard Smith745f5142012-01-27 01:14:48 +00002318
Richard Smith83587db2012-02-15 02:18:13 +00002319 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2320 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002321 ? CCEK_Constant : CCEK_MemberInit)) {
2322 // If we're checking for a potential constant expression, evaluate all
2323 // initializers even if some of them fail.
2324 if (!Info.keepEvaluatingAfterFailure())
2325 return false;
2326 Success = false;
2327 }
Richard Smith180f4792011-11-10 06:34:14 +00002328 }
2329
Richard Smith745f5142012-01-27 01:14:48 +00002330 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002331}
2332
Richard Smithd0dccea2011-10-28 22:34:42 +00002333namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002334class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002335 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002336 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002337public:
2338
Richard Smith1e12c592011-10-16 21:26:27 +00002339 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002340
2341 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002342 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002343 return true;
2344 }
2345
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002346 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2347 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002348 return Visit(E->getResultExpr());
2349 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002350 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002351 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002352 return true;
2353 return false;
2354 }
John McCallf85e1932011-06-15 23:02:42 +00002355 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002356 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002357 return true;
2358 return false;
2359 }
2360 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002361 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002362 return true;
2363 return false;
2364 }
2365
Mike Stumpc4c90452009-10-27 22:09:17 +00002366 // We don't want to evaluate BlockExprs multiple times, as they generate
2367 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002368 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2369 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2370 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002371 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002372 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2373 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2374 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2375 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2376 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2377 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002378 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002379 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002380 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002381 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002382 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002383 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2384 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2385 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2386 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002387 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002388 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2389 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2390 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2391 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2392 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002393 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002394 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002395 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002396 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002397 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002398
2399 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002400 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002401 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2402 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002403 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002404 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002405 return false;
2406 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002407
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002408 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002409};
2410
John McCall56ca35d2011-02-17 10:25:35 +00002411class OpaqueValueEvaluation {
2412 EvalInfo &info;
2413 OpaqueValueExpr *opaqueValue;
2414
2415public:
2416 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2417 Expr *value)
2418 : info(info), opaqueValue(opaqueValue) {
2419
2420 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002421 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002422 this->opaqueValue = 0;
2423 return;
2424 }
John McCall56ca35d2011-02-17 10:25:35 +00002425 }
2426
2427 bool hasError() const { return opaqueValue == 0; }
2428
2429 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002430 // FIXME: For a recursive constexpr call, an outer stack frame might have
2431 // been using this opaque value too, and will now have to re-evaluate the
2432 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002433 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2434 }
2435};
2436
Mike Stumpc4c90452009-10-27 22:09:17 +00002437} // end anonymous namespace
2438
Eli Friedman4efaa272008-11-12 09:44:48 +00002439//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002440// Generic Evaluation
2441//===----------------------------------------------------------------------===//
2442namespace {
2443
Richard Smithf48fdb02011-12-09 22:58:01 +00002444// FIXME: RetTy is always bool. Remove it.
2445template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002446class ExprEvaluatorBase
2447 : public ConstStmtVisitor<Derived, RetTy> {
2448private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002449 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002450 return static_cast<Derived*>(this)->Success(V, E);
2451 }
Richard Smith51201882011-12-30 21:15:51 +00002452 RetTy DerivedZeroInitialization(const Expr *E) {
2453 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002454 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002455
Richard Smith74e1ad92012-02-16 02:46:34 +00002456 // Check whether a conditional operator with a non-constant condition is a
2457 // potential constant expression. If neither arm is a potential constant
2458 // expression, then the conditional operator is not either.
2459 template<typename ConditionalOperator>
2460 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2461 assert(Info.CheckingPotentialConstantExpression);
2462
2463 // Speculatively evaluate both arms.
2464 {
2465 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2466 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2467
2468 StmtVisitorTy::Visit(E->getFalseExpr());
2469 if (Diag.empty())
2470 return;
2471
2472 Diag.clear();
2473 StmtVisitorTy::Visit(E->getTrueExpr());
2474 if (Diag.empty())
2475 return;
2476 }
2477
2478 Error(E, diag::note_constexpr_conditional_never_const);
2479 }
2480
2481
2482 template<typename ConditionalOperator>
2483 bool HandleConditionalOperator(const ConditionalOperator *E) {
2484 bool BoolResult;
2485 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2486 if (Info.CheckingPotentialConstantExpression)
2487 CheckPotentialConstantConditional(E);
2488 return false;
2489 }
2490
2491 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2492 return StmtVisitorTy::Visit(EvalExpr);
2493 }
2494
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002495protected:
2496 EvalInfo &Info;
2497 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2498 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2499
Richard Smithdd1f29b2011-12-12 09:28:41 +00002500 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002501 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002502 }
2503
2504 /// Report an evaluation error. This should only be called when an error is
2505 /// first discovered. When propagating an error, just return false.
2506 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002507 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002508 return false;
2509 }
2510 bool Error(const Expr *E) {
2511 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2512 }
2513
Richard Smith51201882011-12-30 21:15:51 +00002514 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002515
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002516public:
2517 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2518
2519 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002520 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002521 }
2522 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002523 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002524 }
2525
2526 RetTy VisitParenExpr(const ParenExpr *E)
2527 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2528 RetTy VisitUnaryExtension(const UnaryOperator *E)
2529 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2530 RetTy VisitUnaryPlus(const UnaryOperator *E)
2531 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2532 RetTy VisitChooseExpr(const ChooseExpr *E)
2533 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2534 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2535 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002536 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2537 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002538 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2539 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002540 // We cannot create any objects for which cleanups are required, so there is
2541 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2542 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2543 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002544
Richard Smithc216a012011-12-12 12:46:16 +00002545 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2546 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2547 return static_cast<Derived*>(this)->VisitCastExpr(E);
2548 }
2549 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2550 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2551 return static_cast<Derived*>(this)->VisitCastExpr(E);
2552 }
2553
Richard Smithe24f5fc2011-11-17 22:56:20 +00002554 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2555 switch (E->getOpcode()) {
2556 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002557 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002558
2559 case BO_Comma:
2560 VisitIgnoredValue(E->getLHS());
2561 return StmtVisitorTy::Visit(E->getRHS());
2562
2563 case BO_PtrMemD:
2564 case BO_PtrMemI: {
2565 LValue Obj;
2566 if (!HandleMemberPointerAccess(Info, E, Obj))
2567 return false;
2568 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002569 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002570 return false;
2571 return DerivedSuccess(Result, E);
2572 }
2573 }
2574 }
2575
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002576 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002577 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002578 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2579 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002580 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002581
Richard Smith74e1ad92012-02-16 02:46:34 +00002582 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002583 }
2584
2585 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002586 bool IsBcpCall = false;
2587 // If the condition (ignoring parens) is a __builtin_constant_p call,
2588 // the result is a constant expression if it can be folded without
2589 // side-effects. This is an important GNU extension. See GCC PR38377
2590 // for discussion.
2591 if (const CallExpr *CallCE =
2592 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2593 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2594 IsBcpCall = true;
2595
2596 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2597 // constant expression; we can't check whether it's potentially foldable.
2598 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2599 return false;
2600
2601 FoldConstant Fold(Info);
2602
Richard Smith74e1ad92012-02-16 02:46:34 +00002603 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002604 return false;
2605
2606 if (IsBcpCall)
2607 Fold.Fold(Info);
2608
2609 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002610 }
2611
2612 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002613 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002614 if (!Value) {
2615 const Expr *Source = E->getSourceExpr();
2616 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002617 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002618 if (Source == E) { // sanity checking.
2619 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002620 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002621 }
2622 return StmtVisitorTy::Visit(Source);
2623 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002624 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002625 }
Richard Smithf10d9172011-10-11 21:43:33 +00002626
Richard Smithd0dccea2011-10-28 22:34:42 +00002627 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002628 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002629 QualType CalleeType = Callee->getType();
2630
Richard Smithd0dccea2011-10-28 22:34:42 +00002631 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002632 LValue *This = 0, ThisVal;
2633 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002634 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002635
Richard Smith59efe262011-11-11 04:05:33 +00002636 // Extract function decl and 'this' pointer from the callee.
2637 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002638 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002639 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2640 // Explicit bound member calls, such as x.f() or p->g();
2641 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002642 return false;
2643 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002644 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002645 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002646 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2647 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002648 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2649 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002650 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002651 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002652 return Error(Callee);
2653
2654 FD = dyn_cast<FunctionDecl>(Member);
2655 if (!FD)
2656 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002657 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002658 LValue Call;
2659 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002660 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002661
Richard Smithb4e85ed2012-01-06 16:39:00 +00002662 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002663 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002664 FD = dyn_cast_or_null<FunctionDecl>(
2665 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002666 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002667 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002668
2669 // Overloaded operator calls to member functions are represented as normal
2670 // calls with '*this' as the first argument.
2671 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2672 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002673 // FIXME: When selecting an implicit conversion for an overloaded
2674 // operator delete, we sometimes try to evaluate calls to conversion
2675 // operators without a 'this' parameter!
2676 if (Args.empty())
2677 return Error(E);
2678
Richard Smith59efe262011-11-11 04:05:33 +00002679 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2680 return false;
2681 This = &ThisVal;
2682 Args = Args.slice(1);
2683 }
2684
2685 // Don't call function pointers which have been cast to some other type.
2686 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002687 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002688 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002689 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002690
Richard Smithb04035a2012-02-01 02:39:43 +00002691 if (This && !This->checkSubobject(Info, E, CSK_This))
2692 return false;
2693
Richard Smith86c3ae42012-02-13 03:54:03 +00002694 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2695 // calls to such functions in constant expressions.
2696 if (This && !HasQualifier &&
2697 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2698 return Error(E, diag::note_constexpr_virtual_call);
2699
Richard Smithc1c5f272011-12-13 06:39:58 +00002700 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002701 Stmt *Body = FD->getBody(Definition);
Richard Smith83587db2012-02-15 02:18:13 +00002702 CCValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002703
Richard Smithc1c5f272011-12-13 06:39:58 +00002704 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002705 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2706 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002707 return false;
2708
Richard Smith83587db2012-02-15 02:18:13 +00002709 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002710 }
2711
Richard Smithc49bd112011-10-28 17:51:58 +00002712 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2713 return StmtVisitorTy::Visit(E->getInitializer());
2714 }
Richard Smithf10d9172011-10-11 21:43:33 +00002715 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002716 if (E->getNumInits() == 0)
2717 return DerivedZeroInitialization(E);
2718 if (E->getNumInits() == 1)
2719 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002720 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002721 }
2722 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002723 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002724 }
2725 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002726 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002727 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002728 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002729 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002730 }
Richard Smithf10d9172011-10-11 21:43:33 +00002731
Richard Smith180f4792011-11-10 06:34:14 +00002732 /// A member expression where the object is a prvalue is itself a prvalue.
2733 RetTy VisitMemberExpr(const MemberExpr *E) {
2734 assert(!E->isArrow() && "missing call to bound member function?");
2735
2736 CCValue Val;
2737 if (!Evaluate(Val, Info, E->getBase()))
2738 return false;
2739
2740 QualType BaseTy = E->getBase()->getType();
2741
2742 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002743 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002744 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2745 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2746 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2747
Richard Smithb4e85ed2012-01-06 16:39:00 +00002748 SubobjectDesignator Designator(BaseTy);
2749 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002750
Richard Smithf48fdb02011-12-09 22:58:01 +00002751 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002752 DerivedSuccess(Val, E);
2753 }
2754
Richard Smithc49bd112011-10-28 17:51:58 +00002755 RetTy VisitCastExpr(const CastExpr *E) {
2756 switch (E->getCastKind()) {
2757 default:
2758 break;
2759
David Chisnall7a7ee302012-01-16 17:27:18 +00002760 case CK_AtomicToNonAtomic:
2761 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002762 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002763 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002764 return StmtVisitorTy::Visit(E->getSubExpr());
2765
2766 case CK_LValueToRValue: {
2767 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002768 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2769 return false;
2770 CCValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002771 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2772 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2773 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002774 return false;
2775 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002776 }
2777 }
2778
Richard Smithf48fdb02011-12-09 22:58:01 +00002779 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002780 }
2781
Richard Smith8327fad2011-10-24 18:44:57 +00002782 /// Visit a value which is evaluated, but whose value is ignored.
2783 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002784 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002785 if (!Evaluate(Scratch, Info, E))
2786 Info.EvalStatus.HasSideEffects = true;
2787 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002788};
2789
2790}
2791
2792//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002793// Common base class for lvalue and temporary evaluation.
2794//===----------------------------------------------------------------------===//
2795namespace {
2796template<class Derived>
2797class LValueExprEvaluatorBase
2798 : public ExprEvaluatorBase<Derived, bool> {
2799protected:
2800 LValue &Result;
2801 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2802 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2803
2804 bool Success(APValue::LValueBase B) {
2805 Result.set(B);
2806 return true;
2807 }
2808
2809public:
2810 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2811 ExprEvaluatorBaseTy(Info), Result(Result) {}
2812
2813 bool Success(const CCValue &V, const Expr *E) {
2814 Result.setFrom(V);
2815 return true;
2816 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002817
Richard Smithe24f5fc2011-11-17 22:56:20 +00002818 bool VisitMemberExpr(const MemberExpr *E) {
2819 // Handle non-static data members.
2820 QualType BaseTy;
2821 if (E->isArrow()) {
2822 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2823 return false;
2824 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002825 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002826 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002827 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2828 return false;
2829 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002830 } else {
2831 if (!this->Visit(E->getBase()))
2832 return false;
2833 BaseTy = E->getBase()->getType();
2834 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002835
Richard Smithd9b02e72012-01-25 22:15:11 +00002836 const ValueDecl *MD = E->getMemberDecl();
2837 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2838 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2839 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2840 (void)BaseTy;
2841 HandleLValueMember(this->Info, E, Result, FD);
2842 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2843 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2844 } else
2845 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002846
Richard Smithd9b02e72012-01-25 22:15:11 +00002847 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002848 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002849 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002850 RefValue))
2851 return false;
2852 return Success(RefValue, E);
2853 }
2854 return true;
2855 }
2856
2857 bool VisitBinaryOperator(const BinaryOperator *E) {
2858 switch (E->getOpcode()) {
2859 default:
2860 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2861
2862 case BO_PtrMemD:
2863 case BO_PtrMemI:
2864 return HandleMemberPointerAccess(this->Info, E, Result);
2865 }
2866 }
2867
2868 bool VisitCastExpr(const CastExpr *E) {
2869 switch (E->getCastKind()) {
2870 default:
2871 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2872
2873 case CK_DerivedToBase:
2874 case CK_UncheckedDerivedToBase: {
2875 if (!this->Visit(E->getSubExpr()))
2876 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002877
2878 // Now figure out the necessary offset to add to the base LV to get from
2879 // the derived class to the base class.
2880 QualType Type = E->getSubExpr()->getType();
2881
2882 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2883 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002884 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002885 *PathI))
2886 return false;
2887 Type = (*PathI)->getType();
2888 }
2889
2890 return true;
2891 }
2892 }
2893 }
2894};
2895}
2896
2897//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002898// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002899//
2900// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2901// function designators (in C), decl references to void objects (in C), and
2902// temporaries (if building with -Wno-address-of-temporary).
2903//
2904// LValue evaluation produces values comprising a base expression of one of the
2905// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002906// - Declarations
2907// * VarDecl
2908// * FunctionDecl
2909// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002910// * CompoundLiteralExpr in C
2911// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002912// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002913// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002914// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002915// * ObjCEncodeExpr
2916// * AddrLabelExpr
2917// * BlockExpr
2918// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002919// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002920// * Any Expr, with a CallIndex indicating the function in which the temporary
2921// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002922// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002923//===----------------------------------------------------------------------===//
2924namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002925class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002926 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002927public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002928 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2929 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002930
Richard Smithc49bd112011-10-28 17:51:58 +00002931 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2932
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002933 bool VisitDeclRefExpr(const DeclRefExpr *E);
2934 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002935 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002936 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2937 bool VisitMemberExpr(const MemberExpr *E);
2938 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2939 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002940 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002941 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2942 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002943 bool VisitUnaryReal(const UnaryOperator *E);
2944 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002945
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002946 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002947 switch (E->getCastKind()) {
2948 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002949 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002950
Eli Friedmandb924222011-10-11 00:13:24 +00002951 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002952 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002953 if (!Visit(E->getSubExpr()))
2954 return false;
2955 Result.Designator.setInvalid();
2956 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002957
Richard Smithe24f5fc2011-11-17 22:56:20 +00002958 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002959 if (!Visit(E->getSubExpr()))
2960 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002961 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002962 }
2963 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002964};
2965} // end anonymous namespace
2966
Richard Smithc49bd112011-10-28 17:51:58 +00002967/// Evaluate an expression as an lvalue. This can be legitimately called on
2968/// expressions which are not glvalues, in a few cases:
2969/// * function designators in C,
2970/// * "extern void" objects,
2971/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002972static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002973 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2974 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2975 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002976 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002977}
2978
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002979bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002980 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2981 return Success(FD);
2982 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002983 return VisitVarDecl(E, VD);
2984 return Error(E);
2985}
Richard Smith436c8892011-10-24 23:14:33 +00002986
Richard Smithc49bd112011-10-28 17:51:58 +00002987bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002988 if (!VD->getType()->isReferenceType()) {
2989 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002990 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002991 return true;
2992 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002993 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002994 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002995
Richard Smith47a1eed2011-10-29 20:57:55 +00002996 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002997 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2998 return false;
2999 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00003000}
3001
Richard Smithbd552ef2011-10-31 05:52:43 +00003002bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
3003 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003004 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003005 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00003006 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
3007
Richard Smith83587db2012-02-15 02:18:13 +00003008 Result.set(E, Info.CurrentCall->Index);
3009 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3010 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003011 }
3012
3013 // Materialization of an lvalue temporary occurs when we need to force a copy
3014 // (for instance, if it's a bitfield).
3015 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
3016 if (!Visit(E->GetTemporaryExpr()))
3017 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003018 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003019 Info.CurrentCall->Temporaries[E]))
3020 return false;
Richard Smith83587db2012-02-15 02:18:13 +00003021 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003022 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00003023}
3024
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003025bool
3026LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003027 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3028 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3029 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00003030 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003031}
3032
Richard Smith47d21452011-12-27 12:18:28 +00003033bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
3034 if (E->isTypeOperand())
3035 return Success(E);
3036 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
3037 if (RD && RD->isPolymorphic()) {
3038 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
3039 << E->getExprOperand()->getType()
3040 << E->getExprOperand()->getSourceRange();
3041 return false;
3042 }
3043 return Success(E);
3044}
3045
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003046bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003047 // Handle static data members.
3048 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3049 VisitIgnoredValue(E->getBase());
3050 return VisitVarDecl(E, VD);
3051 }
3052
Richard Smithd0dccea2011-10-28 22:34:42 +00003053 // Handle static member functions.
3054 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3055 if (MD->isStatic()) {
3056 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003057 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00003058 }
3059 }
3060
Richard Smith180f4792011-11-10 06:34:14 +00003061 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00003062 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003063}
3064
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003065bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003066 // FIXME: Deal with vectors as array subscript bases.
3067 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003068 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003069
Anders Carlsson3068d112008-11-16 19:01:22 +00003070 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003071 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003072
Anders Carlsson3068d112008-11-16 19:01:22 +00003073 APSInt Index;
3074 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003075 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003076 int64_t IndexValue
3077 = Index.isSigned() ? Index.getSExtValue()
3078 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003079
Richard Smithb4e85ed2012-01-06 16:39:00 +00003080 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003081}
Eli Friedman4efaa272008-11-12 09:44:48 +00003082
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003083bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003084 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003085}
3086
Richard Smith86024012012-02-18 22:04:06 +00003087bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3088 if (!Visit(E->getSubExpr()))
3089 return false;
3090 // __real is a no-op on scalar lvalues.
3091 if (E->getSubExpr()->getType()->isAnyComplexType())
3092 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3093 return true;
3094}
3095
3096bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3097 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3098 "lvalue __imag__ on scalar?");
3099 if (!Visit(E->getSubExpr()))
3100 return false;
3101 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3102 return true;
3103}
3104
Eli Friedman4efaa272008-11-12 09:44:48 +00003105//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003106// Pointer Evaluation
3107//===----------------------------------------------------------------------===//
3108
Anders Carlssonc754aa62008-07-08 05:13:58 +00003109namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003110class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003111 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003112 LValue &Result;
3113
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003114 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003115 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003116 return true;
3117 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003118public:
Mike Stump1eb44332009-09-09 15:08:12 +00003119
John McCallefdb83e2010-05-07 21:00:08 +00003120 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003121 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003122
Richard Smith47a1eed2011-10-29 20:57:55 +00003123 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003124 Result.setFrom(V);
3125 return true;
3126 }
Richard Smith51201882011-12-30 21:15:51 +00003127 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003128 return Success((Expr*)0);
3129 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003130
John McCallefdb83e2010-05-07 21:00:08 +00003131 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003132 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003133 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003134 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003135 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003136 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003137 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003138 bool VisitCallExpr(const CallExpr *E);
3139 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003140 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003141 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003142 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003143 }
Richard Smith180f4792011-11-10 06:34:14 +00003144 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3145 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003146 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003147 Result = *Info.CurrentCall->This;
3148 return true;
3149 }
John McCall56ca35d2011-02-17 10:25:35 +00003150
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003151 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003152};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003153} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003154
John McCallefdb83e2010-05-07 21:00:08 +00003155static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003156 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003157 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003158}
3159
John McCallefdb83e2010-05-07 21:00:08 +00003160bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003161 if (E->getOpcode() != BO_Add &&
3162 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003163 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003164
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003165 const Expr *PExp = E->getLHS();
3166 const Expr *IExp = E->getRHS();
3167 if (IExp->getType()->isPointerType())
3168 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003169
Richard Smith745f5142012-01-27 01:14:48 +00003170 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3171 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003172 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003173
John McCallefdb83e2010-05-07 21:00:08 +00003174 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003175 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003176 return false;
3177 int64_t AdditionalOffset
3178 = Offset.isSigned() ? Offset.getSExtValue()
3179 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003180 if (E->getOpcode() == BO_Sub)
3181 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003182
Richard Smith180f4792011-11-10 06:34:14 +00003183 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003184 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3185 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003186}
Eli Friedman4efaa272008-11-12 09:44:48 +00003187
John McCallefdb83e2010-05-07 21:00:08 +00003188bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3189 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003190}
Mike Stump1eb44332009-09-09 15:08:12 +00003191
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003192bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3193 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003194
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003195 switch (E->getCastKind()) {
3196 default:
3197 break;
3198
John McCall2de56d12010-08-25 11:45:40 +00003199 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003200 case CK_CPointerToObjCPointerCast:
3201 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003202 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003203 if (!Visit(SubExpr))
3204 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003205 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3206 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3207 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003208 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003209 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003210 if (SubExpr->getType()->isVoidPointerType())
3211 CCEDiag(E, diag::note_constexpr_invalid_cast)
3212 << 3 << SubExpr->getType();
3213 else
3214 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3215 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003216 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003217
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003218 case CK_DerivedToBase:
3219 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003220 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003221 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003222 if (!Result.Base && Result.Offset.isZero())
3223 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003224
Richard Smith180f4792011-11-10 06:34:14 +00003225 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003226 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003227 QualType Type =
3228 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003229
Richard Smith180f4792011-11-10 06:34:14 +00003230 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003231 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003232 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3233 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003234 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003235 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003236 }
3237
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003238 return true;
3239 }
3240
Richard Smithe24f5fc2011-11-17 22:56:20 +00003241 case CK_BaseToDerived:
3242 if (!Visit(E->getSubExpr()))
3243 return false;
3244 if (!Result.Base && Result.Offset.isZero())
3245 return true;
3246 return HandleBaseToDerivedCast(Info, E, Result);
3247
Richard Smith47a1eed2011-10-29 20:57:55 +00003248 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003249 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003250
John McCall2de56d12010-08-25 11:45:40 +00003251 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003252 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3253
Richard Smith47a1eed2011-10-29 20:57:55 +00003254 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003255 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003256 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003257
John McCallefdb83e2010-05-07 21:00:08 +00003258 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003259 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3260 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003261 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003262 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003263 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003264 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003265 return true;
3266 } else {
3267 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00003268 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00003269 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003270 }
3271 }
John McCall2de56d12010-08-25 11:45:40 +00003272 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003273 if (SubExpr->isGLValue()) {
3274 if (!EvaluateLValue(SubExpr, Result, Info))
3275 return false;
3276 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003277 Result.set(SubExpr, Info.CurrentCall->Index);
3278 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3279 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003280 return false;
3281 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003282 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003283 if (const ConstantArrayType *CAT
3284 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3285 Result.addArray(Info, E, CAT);
3286 else
3287 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003288 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003289
John McCall2de56d12010-08-25 11:45:40 +00003290 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003291 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003292 }
3293
Richard Smithc49bd112011-10-28 17:51:58 +00003294 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003295}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003296
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003297bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003298 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003299 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003300
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003301 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003302}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003303
3304//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003305// Member Pointer Evaluation
3306//===----------------------------------------------------------------------===//
3307
3308namespace {
3309class MemberPointerExprEvaluator
3310 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3311 MemberPtr &Result;
3312
3313 bool Success(const ValueDecl *D) {
3314 Result = MemberPtr(D);
3315 return true;
3316 }
3317public:
3318
3319 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3320 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3321
3322 bool Success(const CCValue &V, const Expr *E) {
3323 Result.setFrom(V);
3324 return true;
3325 }
Richard Smith51201882011-12-30 21:15:51 +00003326 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003327 return Success((const ValueDecl*)0);
3328 }
3329
3330 bool VisitCastExpr(const CastExpr *E);
3331 bool VisitUnaryAddrOf(const UnaryOperator *E);
3332};
3333} // end anonymous namespace
3334
3335static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3336 EvalInfo &Info) {
3337 assert(E->isRValue() && E->getType()->isMemberPointerType());
3338 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3339}
3340
3341bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3342 switch (E->getCastKind()) {
3343 default:
3344 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3345
3346 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003347 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003348
3349 case CK_BaseToDerivedMemberPointer: {
3350 if (!Visit(E->getSubExpr()))
3351 return false;
3352 if (E->path_empty())
3353 return true;
3354 // Base-to-derived member pointer casts store the path in derived-to-base
3355 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3356 // the wrong end of the derived->base arc, so stagger the path by one class.
3357 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3358 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3359 PathI != PathE; ++PathI) {
3360 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3361 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3362 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003363 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003364 }
3365 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3366 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003367 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003368 return true;
3369 }
3370
3371 case CK_DerivedToBaseMemberPointer:
3372 if (!Visit(E->getSubExpr()))
3373 return false;
3374 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3375 PathE = E->path_end(); PathI != PathE; ++PathI) {
3376 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3377 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3378 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003379 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003380 }
3381 return true;
3382 }
3383}
3384
3385bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3386 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3387 // member can be formed.
3388 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3389}
3390
3391//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003392// Record Evaluation
3393//===----------------------------------------------------------------------===//
3394
3395namespace {
3396 class RecordExprEvaluator
3397 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3398 const LValue &This;
3399 APValue &Result;
3400 public:
3401
3402 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3403 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3404
3405 bool Success(const CCValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003406 Result = V;
3407 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003408 }
Richard Smith51201882011-12-30 21:15:51 +00003409 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003410
Richard Smith59efe262011-11-11 04:05:33 +00003411 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003412 bool VisitInitListExpr(const InitListExpr *E);
3413 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3414 };
3415}
3416
Richard Smith51201882011-12-30 21:15:51 +00003417/// Perform zero-initialization on an object of non-union class type.
3418/// C++11 [dcl.init]p5:
3419/// To zero-initialize an object or reference of type T means:
3420/// [...]
3421/// -- if T is a (possibly cv-qualified) non-union class type,
3422/// each non-static data member and each base-class subobject is
3423/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003424static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3425 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003426 const LValue &This, APValue &Result) {
3427 assert(!RD->isUnion() && "Expected non-union class type");
3428 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3429 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3430 std::distance(RD->field_begin(), RD->field_end()));
3431
3432 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3433
3434 if (CD) {
3435 unsigned Index = 0;
3436 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003437 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003438 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3439 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003440 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3441 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003442 Result.getStructBase(Index)))
3443 return false;
3444 }
3445 }
3446
Richard Smithb4e85ed2012-01-06 16:39:00 +00003447 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3448 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003449 // -- if T is a reference type, no initialization is performed.
3450 if ((*I)->getType()->isReferenceType())
3451 continue;
3452
3453 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003454 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003455
3456 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003457 if (!EvaluateInPlace(
Richard Smith51201882011-12-30 21:15:51 +00003458 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3459 return false;
3460 }
3461
3462 return true;
3463}
3464
3465bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3466 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3467 if (RD->isUnion()) {
3468 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3469 // object's first non-static named data member is zero-initialized
3470 RecordDecl::field_iterator I = RD->field_begin();
3471 if (I == RD->field_end()) {
3472 Result = APValue((const FieldDecl*)0);
3473 return true;
3474 }
3475
3476 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003477 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003478 Result = APValue(*I);
3479 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003480 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003481 }
3482
Richard Smithce582fe2012-02-17 00:44:16 +00003483 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
3484 Info.Diag(E->getExprLoc(), diag::note_constexpr_virtual_base) << RD;
3485 return false;
3486 }
3487
Richard Smithb4e85ed2012-01-06 16:39:00 +00003488 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003489}
3490
Richard Smith59efe262011-11-11 04:05:33 +00003491bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3492 switch (E->getCastKind()) {
3493 default:
3494 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3495
3496 case CK_ConstructorConversion:
3497 return Visit(E->getSubExpr());
3498
3499 case CK_DerivedToBase:
3500 case CK_UncheckedDerivedToBase: {
3501 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003502 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003503 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003504 if (!DerivedObject.isStruct())
3505 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003506
3507 // Derived-to-base rvalue conversion: just slice off the derived part.
3508 APValue *Value = &DerivedObject;
3509 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3510 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3511 PathE = E->path_end(); PathI != PathE; ++PathI) {
3512 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3513 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3514 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3515 RD = Base;
3516 }
3517 Result = *Value;
3518 return true;
3519 }
3520 }
3521}
3522
Richard Smith180f4792011-11-10 06:34:14 +00003523bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003524 // Cannot constant-evaluate std::initializer_list inits.
3525 if (E->initializesStdInitializerList())
3526 return false;
3527
Richard Smith180f4792011-11-10 06:34:14 +00003528 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3529 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3530
3531 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003532 const FieldDecl *Field = E->getInitializedFieldInUnion();
3533 Result = APValue(Field);
3534 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003535 return true;
Richard Smithec789162012-01-12 18:54:33 +00003536
3537 // If the initializer list for a union does not contain any elements, the
3538 // first element of the union is value-initialized.
3539 ImplicitValueInitExpr VIE(Field->getType());
3540 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3541
Richard Smith180f4792011-11-10 06:34:14 +00003542 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003543 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith83587db2012-02-15 02:18:13 +00003544 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003545 }
3546
3547 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3548 "initializer list for class with base classes");
3549 Result = APValue(APValue::UninitStruct(), 0,
3550 std::distance(RD->field_begin(), RD->field_end()));
3551 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003552 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003553 for (RecordDecl::field_iterator Field = RD->field_begin(),
3554 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3555 // Anonymous bit-fields are not considered members of the class for
3556 // purposes of aggregate initialization.
3557 if (Field->isUnnamedBitfield())
3558 continue;
3559
3560 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003561
Richard Smith745f5142012-01-27 01:14:48 +00003562 bool HaveInit = ElementNo < E->getNumInits();
3563
3564 // FIXME: Diagnostics here should point to the end of the initializer
3565 // list, not the start.
3566 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3567 *Field, &Layout);
3568
3569 // Perform an implicit value-initialization for members beyond the end of
3570 // the initializer list.
3571 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3572
Richard Smith83587db2012-02-15 02:18:13 +00003573 if (!EvaluateInPlace(
Richard Smith745f5142012-01-27 01:14:48 +00003574 Result.getStructField((*Field)->getFieldIndex()),
3575 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3576 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003577 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003578 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003579 }
3580 }
3581
Richard Smith745f5142012-01-27 01:14:48 +00003582 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003583}
3584
3585bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3586 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003587 bool ZeroInit = E->requiresZeroInitialization();
3588 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003589 // If we've already performed zero-initialization, we're already done.
3590 if (!Result.isUninit())
3591 return true;
3592
Richard Smith51201882011-12-30 21:15:51 +00003593 if (ZeroInit)
3594 return ZeroInitialization(E);
3595
Richard Smith61802452011-12-22 02:22:31 +00003596 const CXXRecordDecl *RD = FD->getParent();
3597 if (RD->isUnion())
3598 Result = APValue((FieldDecl*)0);
3599 else
3600 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3601 std::distance(RD->field_begin(), RD->field_end()));
3602 return true;
3603 }
3604
Richard Smith180f4792011-11-10 06:34:14 +00003605 const FunctionDecl *Definition = 0;
3606 FD->getBody(Definition);
3607
Richard Smithc1c5f272011-12-13 06:39:58 +00003608 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3609 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003610
Richard Smith610a60c2012-01-10 04:32:03 +00003611 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003612 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003613 if (const MaterializeTemporaryExpr *ME
3614 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3615 return Visit(ME->GetTemporaryExpr());
3616
Richard Smith51201882011-12-30 21:15:51 +00003617 if (ZeroInit && !ZeroInitialization(E))
3618 return false;
3619
Richard Smith180f4792011-11-10 06:34:14 +00003620 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003621 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003622 cast<CXXConstructorDecl>(Definition), Info,
3623 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003624}
3625
3626static bool EvaluateRecord(const Expr *E, const LValue &This,
3627 APValue &Result, EvalInfo &Info) {
3628 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003629 "can't evaluate expression as a record rvalue");
3630 return RecordExprEvaluator(Info, This, Result).Visit(E);
3631}
3632
3633//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003634// Temporary Evaluation
3635//
3636// Temporaries are represented in the AST as rvalues, but generally behave like
3637// lvalues. The full-object of which the temporary is a subobject is implicitly
3638// materialized so that a reference can bind to it.
3639//===----------------------------------------------------------------------===//
3640namespace {
3641class TemporaryExprEvaluator
3642 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3643public:
3644 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3645 LValueExprEvaluatorBaseTy(Info, Result) {}
3646
3647 /// Visit an expression which constructs the value of this temporary.
3648 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003649 Result.set(E, Info.CurrentCall->Index);
3650 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003651 }
3652
3653 bool VisitCastExpr(const CastExpr *E) {
3654 switch (E->getCastKind()) {
3655 default:
3656 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3657
3658 case CK_ConstructorConversion:
3659 return VisitConstructExpr(E->getSubExpr());
3660 }
3661 }
3662 bool VisitInitListExpr(const InitListExpr *E) {
3663 return VisitConstructExpr(E);
3664 }
3665 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3666 return VisitConstructExpr(E);
3667 }
3668 bool VisitCallExpr(const CallExpr *E) {
3669 return VisitConstructExpr(E);
3670 }
3671};
3672} // end anonymous namespace
3673
3674/// Evaluate an expression of record type as a temporary.
3675static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003676 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003677 return TemporaryExprEvaluator(Info, Result).Visit(E);
3678}
3679
3680//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003681// Vector Evaluation
3682//===----------------------------------------------------------------------===//
3683
3684namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003685 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003686 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3687 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003688 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003689
Richard Smith07fc6572011-10-22 21:10:00 +00003690 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3691 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003692
Richard Smith07fc6572011-10-22 21:10:00 +00003693 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3694 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3695 // FIXME: remove this APValue copy.
3696 Result = APValue(V.data(), V.size());
3697 return true;
3698 }
Richard Smith69c2c502011-11-04 05:33:44 +00003699 bool Success(const CCValue &V, const Expr *E) {
3700 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003701 Result = V;
3702 return true;
3703 }
Richard Smith51201882011-12-30 21:15:51 +00003704 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003705
Richard Smith07fc6572011-10-22 21:10:00 +00003706 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003707 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003708 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003709 bool VisitInitListExpr(const InitListExpr *E);
3710 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003711 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003712 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003713 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003714 };
3715} // end anonymous namespace
3716
3717static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003718 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003719 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003720}
3721
Richard Smith07fc6572011-10-22 21:10:00 +00003722bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3723 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003724 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003725
Richard Smithd62ca372011-12-06 22:44:34 +00003726 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003727 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003728
Eli Friedman46a52322011-03-25 00:43:55 +00003729 switch (E->getCastKind()) {
3730 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003731 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003732 if (SETy->isIntegerType()) {
3733 APSInt IntResult;
3734 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003735 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003736 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003737 } else if (SETy->isRealFloatingType()) {
3738 APFloat F(0.0);
3739 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003740 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003741 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003742 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003743 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003744 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003745
3746 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003747 SmallVector<APValue, 4> Elts(NElts, Val);
3748 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003749 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003750 case CK_BitCast: {
3751 // Evaluate the operand into an APInt we can extract from.
3752 llvm::APInt SValInt;
3753 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3754 return false;
3755 // Extract the elements
3756 QualType EltTy = VTy->getElementType();
3757 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3758 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3759 SmallVector<APValue, 4> Elts;
3760 if (EltTy->isRealFloatingType()) {
3761 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3762 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3763 unsigned FloatEltSize = EltSize;
3764 if (&Sem == &APFloat::x87DoubleExtended)
3765 FloatEltSize = 80;
3766 for (unsigned i = 0; i < NElts; i++) {
3767 llvm::APInt Elt;
3768 if (BigEndian)
3769 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3770 else
3771 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3772 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3773 }
3774 } else if (EltTy->isIntegerType()) {
3775 for (unsigned i = 0; i < NElts; i++) {
3776 llvm::APInt Elt;
3777 if (BigEndian)
3778 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3779 else
3780 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3781 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3782 }
3783 } else {
3784 return Error(E);
3785 }
3786 return Success(Elts, E);
3787 }
Eli Friedman46a52322011-03-25 00:43:55 +00003788 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003789 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003790 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003791}
3792
Richard Smith07fc6572011-10-22 21:10:00 +00003793bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003794VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003795 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003796 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003797 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003798
Nate Begeman59b5da62009-01-18 03:20:47 +00003799 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003800 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003801
Eli Friedman3edd5a92012-01-03 23:24:20 +00003802 // The number of initializers can be less than the number of
3803 // vector elements. For OpenCL, this can be due to nested vector
3804 // initialization. For GCC compatibility, missing trailing elements
3805 // should be initialized with zeroes.
3806 unsigned CountInits = 0, CountElts = 0;
3807 while (CountElts < NumElements) {
3808 // Handle nested vector initialization.
3809 if (CountInits < NumInits
3810 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3811 APValue v;
3812 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3813 return Error(E);
3814 unsigned vlen = v.getVectorLength();
3815 for (unsigned j = 0; j < vlen; j++)
3816 Elements.push_back(v.getVectorElt(j));
3817 CountElts += vlen;
3818 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003819 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003820 if (CountInits < NumInits) {
3821 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3822 return Error(E);
3823 } else // trailing integer zero.
3824 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3825 Elements.push_back(APValue(sInt));
3826 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003827 } else {
3828 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003829 if (CountInits < NumInits) {
3830 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3831 return Error(E);
3832 } else // trailing float zero.
3833 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3834 Elements.push_back(APValue(f));
3835 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003836 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003837 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003838 }
Richard Smith07fc6572011-10-22 21:10:00 +00003839 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003840}
3841
Richard Smith07fc6572011-10-22 21:10:00 +00003842bool
Richard Smith51201882011-12-30 21:15:51 +00003843VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003844 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003845 QualType EltTy = VT->getElementType();
3846 APValue ZeroElement;
3847 if (EltTy->isIntegerType())
3848 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3849 else
3850 ZeroElement =
3851 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3852
Chris Lattner5f9e2722011-07-23 10:55:15 +00003853 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003854 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003855}
3856
Richard Smith07fc6572011-10-22 21:10:00 +00003857bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003858 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003859 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003860}
3861
Nate Begeman59b5da62009-01-18 03:20:47 +00003862//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003863// Array Evaluation
3864//===----------------------------------------------------------------------===//
3865
3866namespace {
3867 class ArrayExprEvaluator
3868 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003869 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003870 APValue &Result;
3871 public:
3872
Richard Smith180f4792011-11-10 06:34:14 +00003873 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3874 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003875
3876 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003877 assert((V.isArray() || V.isLValue()) &&
3878 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003879 Result = V;
3880 return true;
3881 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003882
Richard Smith51201882011-12-30 21:15:51 +00003883 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003884 const ConstantArrayType *CAT =
3885 Info.Ctx.getAsConstantArrayType(E->getType());
3886 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003887 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003888
3889 Result = APValue(APValue::UninitArray(), 0,
3890 CAT->getSize().getZExtValue());
3891 if (!Result.hasArrayFiller()) return true;
3892
Richard Smith51201882011-12-30 21:15:51 +00003893 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003894 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003895 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003896 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003897 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003898 }
3899
Richard Smithcc5d4f62011-11-07 09:22:26 +00003900 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003901 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003902 };
3903} // end anonymous namespace
3904
Richard Smith180f4792011-11-10 06:34:14 +00003905static bool EvaluateArray(const Expr *E, const LValue &This,
3906 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003907 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003908 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003909}
3910
3911bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3912 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3913 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003914 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003915
Richard Smith974c5f92011-12-22 01:07:19 +00003916 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3917 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003918 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003919 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3920 LValue LV;
3921 if (!EvaluateLValue(E->getInit(0), LV, Info))
3922 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00003923 CCValue Val;
3924 LV.moveInto(Val);
3925 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003926 }
3927
Richard Smith745f5142012-01-27 01:14:48 +00003928 bool Success = true;
3929
Richard Smithcc5d4f62011-11-07 09:22:26 +00003930 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3931 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003932 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003933 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003934 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003935 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003936 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003937 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3938 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003939 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3940 CAT->getElementType(), 1)) {
3941 if (!Info.keepEvaluatingAfterFailure())
3942 return false;
3943 Success = false;
3944 }
Richard Smith180f4792011-11-10 06:34:14 +00003945 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003946
Richard Smith745f5142012-01-27 01:14:48 +00003947 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003948 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003949 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3950 // but sometimes does:
3951 // struct S { constexpr S() : p(&p) {} void *p; };
3952 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003953 return EvaluateInPlace(Result.getArrayFiller(), Info,
3954 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003955}
3956
Richard Smithe24f5fc2011-11-17 22:56:20 +00003957bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3958 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3959 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003960 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003961
Richard Smithec789162012-01-12 18:54:33 +00003962 bool HadZeroInit = !Result.isUninit();
3963 if (!HadZeroInit)
3964 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003965 if (!Result.hasArrayFiller())
3966 return true;
3967
3968 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003969
Richard Smith51201882011-12-30 21:15:51 +00003970 bool ZeroInit = E->requiresZeroInitialization();
3971 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003972 if (HadZeroInit)
3973 return true;
3974
Richard Smith51201882011-12-30 21:15:51 +00003975 if (ZeroInit) {
3976 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003977 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003978 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003979 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003980 }
3981
Richard Smith61802452011-12-22 02:22:31 +00003982 const CXXRecordDecl *RD = FD->getParent();
3983 if (RD->isUnion())
3984 Result.getArrayFiller() = APValue((FieldDecl*)0);
3985 else
3986 Result.getArrayFiller() =
3987 APValue(APValue::UninitStruct(), RD->getNumBases(),
3988 std::distance(RD->field_begin(), RD->field_end()));
3989 return true;
3990 }
3991
Richard Smithe24f5fc2011-11-17 22:56:20 +00003992 const FunctionDecl *Definition = 0;
3993 FD->getBody(Definition);
3994
Richard Smithc1c5f272011-12-13 06:39:58 +00003995 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3996 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003997
3998 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3999 // but sometimes does:
4000 // struct S { constexpr S() : p(&p) {} void *p; };
4001 // S s[10];
4002 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00004003 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00004004
Richard Smithec789162012-01-12 18:54:33 +00004005 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00004006 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00004007 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00004008 return false;
4009 }
4010
Richard Smithe24f5fc2011-11-17 22:56:20 +00004011 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00004012 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00004013 cast<CXXConstructorDecl>(Definition),
4014 Info, Result.getArrayFiller());
4015}
4016
Richard Smithcc5d4f62011-11-07 09:22:26 +00004017//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004018// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00004019//
4020// As a GNU extension, we support casting pointers to sufficiently-wide integer
4021// types and back in constant folding. Integer values are thus represented
4022// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004023//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004024
4025namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004026class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004027 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00004028 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00004029public:
Richard Smith47a1eed2011-10-29 20:57:55 +00004030 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004031 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004032
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004033 bool Success(const llvm::APSInt &SI, const Expr *E) {
4034 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004035 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004036 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004037 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004038 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004039 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00004040 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004041 return true;
4042 }
4043
Daniel Dunbar131eb432009-02-19 09:06:44 +00004044 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004045 assert(E->getType()->isIntegralOrEnumerationType() &&
4046 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004047 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004048 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00004049 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00004050 Result.getInt().setIsUnsigned(
4051 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00004052 return true;
4053 }
4054
4055 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004056 assert(E->getType()->isIntegralOrEnumerationType() &&
4057 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00004058 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00004059 return true;
4060 }
4061
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004062 bool Success(CharUnits Size, const Expr *E) {
4063 return Success(Size.getQuantity(), E);
4064 }
4065
Richard Smith47a1eed2011-10-29 20:57:55 +00004066 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00004067 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00004068 Result = V;
4069 return true;
4070 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004071 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00004072 }
Mike Stump1eb44332009-09-09 15:08:12 +00004073
Richard Smith51201882011-12-30 21:15:51 +00004074 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00004075
Argyrios Kyrtzidisc1b66e62012-02-27 23:18:37 +00004076 // FIXME: See EvalInfo::IntExprEvaluatorDepth.
4077 bool Visit(const Expr *E) {
4078 SaveAndRestore<unsigned> Depth(Info.IntExprEvaluatorDepth,
4079 Info.IntExprEvaluatorDepth+1);
4080 const unsigned MaxDepth = 512;
4081 if (Depth.get() > MaxDepth) {
4082 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
4083 diag::err_intexpr_depth_limit_exceeded);
4084 return false;
4085 }
4086
4087 return ExprEvaluatorBaseTy::Visit(E);
4088 }
4089
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004090 //===--------------------------------------------------------------------===//
4091 // Visitor Methods
4092 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004093
Chris Lattner4c4867e2008-07-12 00:38:25 +00004094 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004095 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004096 }
4097 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004098 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004099 }
Eli Friedman04309752009-11-24 05:28:59 +00004100
4101 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4102 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004103 if (CheckReferencedDecl(E, E->getDecl()))
4104 return true;
4105
4106 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004107 }
4108 bool VisitMemberExpr(const MemberExpr *E) {
4109 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004110 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004111 return true;
4112 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004113
4114 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004115 }
4116
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004117 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004118 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004119 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004120 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004121
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004122 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004123 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004124
Anders Carlsson3068d112008-11-16 19:01:22 +00004125 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004126 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004127 }
Mike Stump1eb44332009-09-09 15:08:12 +00004128
Richard Smithf10d9172011-10-11 21:43:33 +00004129 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004130 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004131 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004132 }
4133
Sebastian Redl64b45f72009-01-05 20:52:13 +00004134 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004135 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004136 }
4137
Francois Pichet6ad6f282010-12-07 00:08:36 +00004138 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4139 return Success(E->getValue(), E);
4140 }
4141
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004142 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4143 return Success(E->getValue(), E);
4144 }
4145
John Wiegley21ff2e52011-04-28 00:16:57 +00004146 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4147 return Success(E->getValue(), E);
4148 }
4149
John Wiegley55262202011-04-25 06:54:41 +00004150 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4151 return Success(E->getValue(), E);
4152 }
4153
Eli Friedman722c7172009-02-28 03:59:05 +00004154 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004155 bool VisitUnaryImag(const UnaryOperator *E);
4156
Sebastian Redl295995c2010-09-10 20:55:47 +00004157 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004158 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004159
Chris Lattnerfcee0012008-07-11 21:24:13 +00004160private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004161 CharUnits GetAlignOfExpr(const Expr *E);
4162 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004163 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004164 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004165 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004166};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004167} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004168
Richard Smithc49bd112011-10-28 17:51:58 +00004169/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4170/// produce either the integer value or a pointer.
4171///
4172/// GCC has a heinous extension which folds casts between pointer types and
4173/// pointer-sized integral types. We support this by allowing the evaluation of
4174/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4175/// Some simple arithmetic on such values is supported (they are treated much
4176/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00004177static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004178 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004179 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004180 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004181}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004182
Richard Smithf48fdb02011-12-09 22:58:01 +00004183static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004184 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004185 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004186 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004187 if (!Val.isInt()) {
4188 // FIXME: It would be better to produce the diagnostic for casting
4189 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00004190 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004191 return false;
4192 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004193 Result = Val.getInt();
4194 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004195}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004196
Richard Smithf48fdb02011-12-09 22:58:01 +00004197/// Check whether the given declaration can be directly converted to an integral
4198/// rvalue. If not, no diagnostic is produced; there are other things we can
4199/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004200bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004201 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004202 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004203 // Check for signedness/width mismatches between E type and ECD value.
4204 bool SameSign = (ECD->getInitVal().isSigned()
4205 == E->getType()->isSignedIntegerOrEnumerationType());
4206 bool SameWidth = (ECD->getInitVal().getBitWidth()
4207 == Info.Ctx.getIntWidth(E->getType()));
4208 if (SameSign && SameWidth)
4209 return Success(ECD->getInitVal(), E);
4210 else {
4211 // Get rid of mismatch (otherwise Success assertions will fail)
4212 // by computing a new value matching the type of E.
4213 llvm::APSInt Val = ECD->getInitVal();
4214 if (!SameSign)
4215 Val.setIsSigned(!ECD->getInitVal().isSigned());
4216 if (!SameWidth)
4217 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4218 return Success(Val, E);
4219 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004220 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004221 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004222}
4223
Chris Lattnera4d55d82008-10-06 06:40:35 +00004224/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4225/// as GCC.
4226static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4227 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004228 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004229 enum gcc_type_class {
4230 no_type_class = -1,
4231 void_type_class, integer_type_class, char_type_class,
4232 enumeral_type_class, boolean_type_class,
4233 pointer_type_class, reference_type_class, offset_type_class,
4234 real_type_class, complex_type_class,
4235 function_type_class, method_type_class,
4236 record_type_class, union_type_class,
4237 array_type_class, string_type_class,
4238 lang_type_class
4239 };
Mike Stump1eb44332009-09-09 15:08:12 +00004240
4241 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004242 // ideal, however it is what gcc does.
4243 if (E->getNumArgs() == 0)
4244 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004245
Chris Lattnera4d55d82008-10-06 06:40:35 +00004246 QualType ArgTy = E->getArg(0)->getType();
4247 if (ArgTy->isVoidType())
4248 return void_type_class;
4249 else if (ArgTy->isEnumeralType())
4250 return enumeral_type_class;
4251 else if (ArgTy->isBooleanType())
4252 return boolean_type_class;
4253 else if (ArgTy->isCharType())
4254 return string_type_class; // gcc doesn't appear to use char_type_class
4255 else if (ArgTy->isIntegerType())
4256 return integer_type_class;
4257 else if (ArgTy->isPointerType())
4258 return pointer_type_class;
4259 else if (ArgTy->isReferenceType())
4260 return reference_type_class;
4261 else if (ArgTy->isRealType())
4262 return real_type_class;
4263 else if (ArgTy->isComplexType())
4264 return complex_type_class;
4265 else if (ArgTy->isFunctionType())
4266 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004267 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004268 return record_type_class;
4269 else if (ArgTy->isUnionType())
4270 return union_type_class;
4271 else if (ArgTy->isArrayType())
4272 return array_type_class;
4273 else if (ArgTy->isUnionType())
4274 return union_type_class;
4275 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004276 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004277}
4278
Richard Smith80d4b552011-12-28 19:48:30 +00004279/// EvaluateBuiltinConstantPForLValue - Determine the result of
4280/// __builtin_constant_p when applied to the given lvalue.
4281///
4282/// An lvalue is only "constant" if it is a pointer or reference to the first
4283/// character of a string literal.
4284template<typename LValue>
4285static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4286 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
4287 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4288}
4289
4290/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4291/// GCC as we can manage.
4292static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4293 QualType ArgType = Arg->getType();
4294
4295 // __builtin_constant_p always has one operand. The rules which gcc follows
4296 // are not precisely documented, but are as follows:
4297 //
4298 // - If the operand is of integral, floating, complex or enumeration type,
4299 // and can be folded to a known value of that type, it returns 1.
4300 // - If the operand and can be folded to a pointer to the first character
4301 // of a string literal (or such a pointer cast to an integral type), it
4302 // returns 1.
4303 //
4304 // Otherwise, it returns 0.
4305 //
4306 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4307 // its support for this does not currently work.
4308 if (ArgType->isIntegralOrEnumerationType()) {
4309 Expr::EvalResult Result;
4310 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4311 return false;
4312
4313 APValue &V = Result.Val;
4314 if (V.getKind() == APValue::Int)
4315 return true;
4316
4317 return EvaluateBuiltinConstantPForLValue(V);
4318 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4319 return Arg->isEvaluatable(Ctx);
4320 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4321 LValue LV;
4322 Expr::EvalStatus Status;
4323 EvalInfo Info(Ctx, Status);
4324 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4325 : EvaluatePointer(Arg, LV, Info)) &&
4326 !Status.HasSideEffects)
4327 return EvaluateBuiltinConstantPForLValue(LV);
4328 }
4329
4330 // Anything else isn't considered to be sufficiently constant.
4331 return false;
4332}
4333
John McCall42c8f872010-05-10 23:27:23 +00004334/// Retrieves the "underlying object type" of the given expression,
4335/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004336QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4337 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4338 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004339 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004340 } else if (const Expr *E = B.get<const Expr*>()) {
4341 if (isa<CompoundLiteralExpr>(E))
4342 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004343 }
4344
4345 return QualType();
4346}
4347
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004348bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004349 // TODO: Perhaps we should let LLVM lower this?
4350 LValue Base;
4351 if (!EvaluatePointer(E->getArg(0), Base, Info))
4352 return false;
4353
4354 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004355 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004356
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004357 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004358 if (T.isNull() ||
4359 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004360 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004361 T->isVariablyModifiedType() ||
4362 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004363 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004364
4365 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4366 CharUnits Offset = Base.getLValueOffset();
4367
4368 if (!Offset.isNegative() && Offset <= Size)
4369 Size -= Offset;
4370 else
4371 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004372 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004373}
4374
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004375bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004376 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004377 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004378 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004379
4380 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004381 if (TryEvaluateBuiltinObjectSize(E))
4382 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004383
Eric Christopherb2aaf512010-01-19 22:58:35 +00004384 // If evaluating the argument has side-effects we can't determine
4385 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004386 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004387 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004388 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004389 return Success(0, E);
4390 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004391
Richard Smithf48fdb02011-12-09 22:58:01 +00004392 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004393 }
4394
Chris Lattner019f4e82008-10-06 05:28:25 +00004395 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004396 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004397
Richard Smith80d4b552011-12-28 19:48:30 +00004398 case Builtin::BI__builtin_constant_p:
4399 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004400
Chris Lattner21fb98e2009-09-23 06:06:36 +00004401 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004402 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004403 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004404 return Success(Operand, E);
4405 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004406
4407 case Builtin::BI__builtin_expect:
4408 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004409
Douglas Gregor5726d402010-09-10 06:27:15 +00004410 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004411 // A call to strlen is not a constant expression.
4412 if (Info.getLangOpts().CPlusPlus0x)
4413 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4414 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4415 else
4416 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4417 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004418 case Builtin::BI__builtin_strlen:
4419 // As an extension, we support strlen() and __builtin_strlen() as constant
4420 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004421 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004422 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4423 // The string literal may have embedded null characters. Find the first
4424 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004425 StringRef Str = S->getString();
4426 StringRef::size_type Pos = Str.find(0);
4427 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004428 Str = Str.substr(0, Pos);
4429
4430 return Success(Str.size(), E);
4431 }
4432
Richard Smithf48fdb02011-12-09 22:58:01 +00004433 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004434
4435 case Builtin::BI__atomic_is_lock_free: {
4436 APSInt SizeVal;
4437 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4438 return false;
4439
4440 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4441 // of two less than the maximum inline atomic width, we know it is
4442 // lock-free. If the size isn't a power of two, or greater than the
4443 // maximum alignment where we promote atomics, we know it is not lock-free
4444 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4445 // the answer can only be determined at runtime; for example, 16-byte
4446 // atomics have lock-free implementations on some, but not all,
4447 // x86-64 processors.
4448
4449 // Check power-of-two.
4450 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4451 if (!Size.isPowerOfTwo())
4452#if 0
4453 // FIXME: Suppress this folding until the ABI for the promotion width
4454 // settles.
4455 return Success(0, E);
4456#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004457 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004458#endif
4459
4460#if 0
4461 // Check against promotion width.
4462 // FIXME: Suppress this folding until the ABI for the promotion width
4463 // settles.
4464 unsigned PromoteWidthBits =
4465 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4466 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4467 return Success(0, E);
4468#endif
4469
4470 // Check against inlining width.
4471 unsigned InlineWidthBits =
4472 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4473 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4474 return Success(1, E);
4475
Richard Smithf48fdb02011-12-09 22:58:01 +00004476 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004477 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004478 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004479}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004480
Richard Smith625b8072011-10-31 01:37:14 +00004481static bool HasSameBase(const LValue &A, const LValue &B) {
4482 if (!A.getLValueBase())
4483 return !B.getLValueBase();
4484 if (!B.getLValueBase())
4485 return false;
4486
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004487 if (A.getLValueBase().getOpaqueValue() !=
4488 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004489 const Decl *ADecl = GetLValueBaseDecl(A);
4490 if (!ADecl)
4491 return false;
4492 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004493 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004494 return false;
4495 }
4496
4497 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004498 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004499}
4500
Richard Smith7b48a292012-02-01 05:53:12 +00004501/// Perform the given integer operation, which is known to need at most BitWidth
4502/// bits, and check for overflow in the original type (if that type was not an
4503/// unsigned type).
4504template<typename Operation>
4505static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4506 const APSInt &LHS, const APSInt &RHS,
4507 unsigned BitWidth, Operation Op) {
4508 if (LHS.isUnsigned())
4509 return Op(LHS, RHS);
4510
4511 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4512 APSInt Result = Value.trunc(LHS.getBitWidth());
4513 if (Result.extend(BitWidth) != Value)
4514 HandleOverflow(Info, E, Value, E->getType());
4515 return Result;
4516}
4517
Chris Lattnerb542afe2008-07-11 19:10:17 +00004518bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004519 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004520 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004521
John McCall2de56d12010-08-25 11:45:40 +00004522 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004523 VisitIgnoredValue(E->getLHS());
4524 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004525 }
4526
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004527 if (E->isLogicalOp()) {
4528 // These need to be handled specially because the operands aren't
4529 // necessarily integral nor evaluated.
4530 bool lhsResult, rhsResult;
4531
4532 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
4533 // We were able to evaluate the LHS, see if we can get away with not
4534 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
4535 if (lhsResult == (E->getOpcode() == BO_LOr))
4536 return Success(lhsResult, E);
4537
4538 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4539 if (E->getOpcode() == BO_LOr)
4540 return Success(lhsResult || rhsResult, E);
4541 else
4542 return Success(lhsResult && rhsResult, E);
4543 }
4544 } else {
4545 // Since we weren't able to evaluate the left hand side, it
4546 // must have had side effects.
4547 Info.EvalStatus.HasSideEffects = true;
4548
4549 // Suppress diagnostics from this arm.
4550 SpeculativeEvaluationRAII Speculative(Info);
4551 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4552 // We can't evaluate the LHS; however, sometimes the result
4553 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4554 if (rhsResult == (E->getOpcode() == BO_LOr))
4555 return Success(rhsResult, E);
4556 }
4557 }
4558
4559 return false;
4560 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004561
Anders Carlsson286f85e2008-11-16 07:17:21 +00004562 QualType LHSTy = E->getLHS()->getType();
4563 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004564
4565 if (LHSTy->isAnyComplexType()) {
4566 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004567 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004568
Richard Smith745f5142012-01-27 01:14:48 +00004569 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4570 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004571 return false;
4572
Richard Smith745f5142012-01-27 01:14:48 +00004573 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004574 return false;
4575
4576 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004577 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004578 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004579 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004580 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4581
John McCall2de56d12010-08-25 11:45:40 +00004582 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004583 return Success((CR_r == APFloat::cmpEqual &&
4584 CR_i == APFloat::cmpEqual), E);
4585 else {
John McCall2de56d12010-08-25 11:45:40 +00004586 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004587 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004588 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004589 CR_r == APFloat::cmpLessThan ||
4590 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004591 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004592 CR_i == APFloat::cmpLessThan ||
4593 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004594 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004595 } else {
John McCall2de56d12010-08-25 11:45:40 +00004596 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004597 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4598 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4599 else {
John McCall2de56d12010-08-25 11:45:40 +00004600 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004601 "Invalid compex comparison.");
4602 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4603 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4604 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004605 }
4606 }
Mike Stump1eb44332009-09-09 15:08:12 +00004607
Anders Carlsson286f85e2008-11-16 07:17:21 +00004608 if (LHSTy->isRealFloatingType() &&
4609 RHSTy->isRealFloatingType()) {
4610 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004611
Richard Smith745f5142012-01-27 01:14:48 +00004612 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4613 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004614 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004615
Richard Smith745f5142012-01-27 01:14:48 +00004616 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004617 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004618
Anders Carlsson286f85e2008-11-16 07:17:21 +00004619 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004620
Anders Carlsson286f85e2008-11-16 07:17:21 +00004621 switch (E->getOpcode()) {
4622 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004623 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004624 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004625 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004626 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004627 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004628 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004629 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004630 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004631 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004632 E);
John McCall2de56d12010-08-25 11:45:40 +00004633 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004634 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004635 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004636 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004637 || CR == APFloat::cmpLessThan
4638 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004639 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004640 }
Mike Stump1eb44332009-09-09 15:08:12 +00004641
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004642 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004643 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004644 LValue LHSValue, RHSValue;
4645
4646 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4647 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004648 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004649
Richard Smith745f5142012-01-27 01:14:48 +00004650 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004651 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004652
Richard Smith625b8072011-10-31 01:37:14 +00004653 // Reject differing bases from the normal codepath; we special-case
4654 // comparisons to null.
4655 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004656 if (E->getOpcode() == BO_Sub) {
4657 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004658 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4659 return false;
4660 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4661 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4662 if (!LHSExpr || !RHSExpr)
4663 return false;
4664 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4665 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4666 if (!LHSAddrExpr || !RHSAddrExpr)
4667 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004668 // Make sure both labels come from the same function.
4669 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4670 RHSAddrExpr->getLabel()->getDeclContext())
4671 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004672 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4673 return true;
4674 }
Richard Smith9e36b532011-10-31 05:11:32 +00004675 // Inequalities and subtractions between unrelated pointers have
4676 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004677 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004678 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004679 // A constant address may compare equal to the address of a symbol.
4680 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004681 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004682 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4683 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004684 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004685 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004686 // distinct addresses. In clang, the result of such a comparison is
4687 // unspecified, so it is not a constant expression. However, we do know
4688 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004689 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4690 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004691 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004692 // We can't tell whether weak symbols will end up pointing to the same
4693 // object.
4694 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004695 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004696 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004697 // (Note that clang defaults to -fmerge-all-constants, which can
4698 // lead to inconsistent results for comparisons involving the address
4699 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004700 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004701 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004702
Richard Smith15efc4d2012-02-01 08:10:20 +00004703 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4704 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4705
Richard Smithf15fda02012-02-02 01:16:57 +00004706 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4707 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4708
John McCall2de56d12010-08-25 11:45:40 +00004709 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004710 // C++11 [expr.add]p6:
4711 // Unless both pointers point to elements of the same array object, or
4712 // one past the last element of the array object, the behavior is
4713 // undefined.
4714 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4715 !AreElementsOfSameArray(getType(LHSValue.Base),
4716 LHSDesignator, RHSDesignator))
4717 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4718
Chris Lattner4992bdd2010-04-20 17:13:14 +00004719 QualType Type = E->getLHS()->getType();
4720 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004721
Richard Smith180f4792011-11-10 06:34:14 +00004722 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004723 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004724 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004725
Richard Smith15efc4d2012-02-01 08:10:20 +00004726 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4727 // and produce incorrect results when it overflows. Such behavior
4728 // appears to be non-conforming, but is common, so perhaps we should
4729 // assume the standard intended for such cases to be undefined behavior
4730 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004731
Richard Smith15efc4d2012-02-01 08:10:20 +00004732 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4733 // overflow in the final conversion to ptrdiff_t.
4734 APSInt LHS(
4735 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4736 APSInt RHS(
4737 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4738 APSInt ElemSize(
4739 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4740 APSInt TrueResult = (LHS - RHS) / ElemSize;
4741 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4742
4743 if (Result.extend(65) != TrueResult)
4744 HandleOverflow(Info, E, TrueResult, E->getType());
4745 return Success(Result, E);
4746 }
Richard Smith82f28582012-01-31 06:41:30 +00004747
4748 // C++11 [expr.rel]p3:
4749 // Pointers to void (after pointer conversions) can be compared, with a
4750 // result defined as follows: If both pointers represent the same
4751 // address or are both the null pointer value, the result is true if the
4752 // operator is <= or >= and false otherwise; otherwise the result is
4753 // unspecified.
4754 // We interpret this as applying to pointers to *cv* void.
4755 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004756 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004757 CCEDiag(E, diag::note_constexpr_void_comparison);
4758
Richard Smithf15fda02012-02-02 01:16:57 +00004759 // C++11 [expr.rel]p2:
4760 // - If two pointers point to non-static data members of the same object,
4761 // or to subobjects or array elements fo such members, recursively, the
4762 // pointer to the later declared member compares greater provided the
4763 // two members have the same access control and provided their class is
4764 // not a union.
4765 // [...]
4766 // - Otherwise pointer comparisons are unspecified.
4767 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4768 E->isRelationalOp()) {
4769 bool WasArrayIndex;
4770 unsigned Mismatch =
4771 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4772 RHSDesignator, WasArrayIndex);
4773 // At the point where the designators diverge, the comparison has a
4774 // specified value if:
4775 // - we are comparing array indices
4776 // - we are comparing fields of a union, or fields with the same access
4777 // Otherwise, the result is unspecified and thus the comparison is not a
4778 // constant expression.
4779 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4780 Mismatch < RHSDesignator.Entries.size()) {
4781 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4782 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4783 if (!LF && !RF)
4784 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4785 else if (!LF)
4786 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4787 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4788 << RF->getParent() << RF;
4789 else if (!RF)
4790 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4791 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4792 << LF->getParent() << LF;
4793 else if (!LF->getParent()->isUnion() &&
4794 LF->getAccess() != RF->getAccess())
4795 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4796 << LF << LF->getAccess() << RF << RF->getAccess()
4797 << LF->getParent();
4798 }
4799 }
4800
Richard Smith625b8072011-10-31 01:37:14 +00004801 switch (E->getOpcode()) {
4802 default: llvm_unreachable("missing comparison operator");
4803 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4804 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4805 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4806 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4807 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4808 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004809 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004810 }
4811 }
Richard Smithb02e4622012-02-01 01:42:44 +00004812
4813 if (LHSTy->isMemberPointerType()) {
4814 assert(E->isEqualityOp() && "unexpected member pointer operation");
4815 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4816
4817 MemberPtr LHSValue, RHSValue;
4818
4819 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4820 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4821 return false;
4822
4823 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4824 return false;
4825
4826 // C++11 [expr.eq]p2:
4827 // If both operands are null, they compare equal. Otherwise if only one is
4828 // null, they compare unequal.
4829 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4830 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4831 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4832 }
4833
4834 // Otherwise if either is a pointer to a virtual member function, the
4835 // result is unspecified.
4836 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4837 if (MD->isVirtual())
4838 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4839 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4840 if (MD->isVirtual())
4841 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4842
4843 // Otherwise they compare equal if and only if they would refer to the
4844 // same member of the same most derived object or the same subobject if
4845 // they were dereferenced with a hypothetical object of the associated
4846 // class type.
4847 bool Equal = LHSValue == RHSValue;
4848 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4849 }
4850
Richard Smith26f2cac2012-02-14 22:35:28 +00004851 if (LHSTy->isNullPtrType()) {
4852 assert(E->isComparisonOp() && "unexpected nullptr operation");
4853 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
4854 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
4855 // are compared, the result is true of the operator is <=, >= or ==, and
4856 // false otherwise.
4857 BinaryOperator::Opcode Opcode = E->getOpcode();
4858 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
4859 }
4860
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004861 if (!LHSTy->isIntegralOrEnumerationType() ||
4862 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004863 // We can't continue from here for non-integral types.
4864 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004865 }
4866
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004867 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004868 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004869
4870 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4871 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004872 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004873
Richard Smith745f5142012-01-27 01:14:48 +00004874 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004875 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004876
Richard Smith47a1eed2011-10-29 20:57:55 +00004877 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004878
4879 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004880 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004881 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4882 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004883 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004884 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004885 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004886 LHSVal.getLValueOffset() -= AdditionalOffset;
4887 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004888 return true;
4889 }
4890
4891 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004892 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004893 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004894 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4895 LHSVal.getInt().getZExtValue());
4896 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004897 return true;
4898 }
4899
Eli Friedman65639282012-01-04 23:13:47 +00004900 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4901 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004902 if (!LHSVal.getLValueOffset().isZero() ||
4903 !RHSVal.getLValueOffset().isZero())
4904 return false;
4905 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4906 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4907 if (!LHSExpr || !RHSExpr)
4908 return false;
4909 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4910 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4911 if (!LHSAddrExpr || !RHSAddrExpr)
4912 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004913 // Make sure both labels come from the same function.
4914 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4915 RHSAddrExpr->getLabel()->getDeclContext())
4916 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004917 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4918 return true;
4919 }
4920
Eli Friedman42edd0d2009-03-24 01:14:50 +00004921 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004922 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004923 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004924
Richard Smithc49bd112011-10-28 17:51:58 +00004925 APSInt &LHS = LHSVal.getInt();
4926 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004927
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004928 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004929 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004930 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004931 case BO_Mul:
4932 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4933 LHS.getBitWidth() * 2,
4934 std::multiplies<APSInt>()), E);
4935 case BO_Add:
4936 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4937 LHS.getBitWidth() + 1,
4938 std::plus<APSInt>()), E);
4939 case BO_Sub:
4940 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4941 LHS.getBitWidth() + 1,
4942 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004943 case BO_And: return Success(LHS & RHS, E);
4944 case BO_Xor: return Success(LHS ^ RHS, E);
4945 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004946 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004947 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004948 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004949 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004950 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4951 // actually undefined behavior in C++11 due to a language defect.
4952 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4953 LHS.isSigned() && LHS.isMinSignedValue())
4954 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4955 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004956 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004957 // During constant-folding, a negative shift is an opposite shift. Such a
4958 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004959 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004960 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004961 RHS = -RHS;
4962 goto shift_right;
4963 }
4964
4965 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004966 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4967 // shifted type.
4968 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4969 if (SA != RHS) {
4970 CCEDiag(E, diag::note_constexpr_large_shift)
4971 << RHS << E->getType() << LHS.getBitWidth();
4972 } else if (LHS.isSigned()) {
4973 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
Richard Smith925d8e72012-02-08 06:14:53 +00004974 // operand, and must not overflow the corresponding unsigned type.
Richard Smith789f9b62012-01-31 04:08:20 +00004975 if (LHS.isNegative())
4976 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
Richard Smith925d8e72012-02-08 06:14:53 +00004977 else if (LHS.countLeadingZeros() < SA)
4978 CCEDiag(E, diag::note_constexpr_lshift_discards);
Richard Smith789f9b62012-01-31 04:08:20 +00004979 }
4980
Richard Smithc49bd112011-10-28 17:51:58 +00004981 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004982 }
John McCall2de56d12010-08-25 11:45:40 +00004983 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004984 // During constant-folding, a negative shift is an opposite shift. Such a
4985 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004986 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004987 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004988 RHS = -RHS;
4989 goto shift_left;
4990 }
4991
4992 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004993 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4994 // shifted type.
4995 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4996 if (SA != RHS)
4997 CCEDiag(E, diag::note_constexpr_large_shift)
4998 << RHS << E->getType() << LHS.getBitWidth();
4999
Richard Smithc49bd112011-10-28 17:51:58 +00005000 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00005001 }
Mike Stump1eb44332009-09-09 15:08:12 +00005002
Richard Smithc49bd112011-10-28 17:51:58 +00005003 case BO_LT: return Success(LHS < RHS, E);
5004 case BO_GT: return Success(LHS > RHS, E);
5005 case BO_LE: return Success(LHS <= RHS, E);
5006 case BO_GE: return Success(LHS >= RHS, E);
5007 case BO_EQ: return Success(LHS == RHS, E);
5008 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00005009 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005010}
5011
Ken Dyck8b752f12010-01-27 17:10:57 +00005012CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005013 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5014 // result shall be the alignment of the referenced type."
5015 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5016 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005017
5018 // __alignof is defined to return the preferred alignment.
5019 return Info.Ctx.toCharUnitsFromBits(
5020 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005021}
5022
Ken Dyck8b752f12010-01-27 17:10:57 +00005023CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005024 E = E->IgnoreParens();
5025
5026 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005027 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005028 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005029 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5030 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005031
Chris Lattneraf707ab2009-01-24 21:53:27 +00005032 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005033 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5034 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005035
Chris Lattnere9feb472009-01-24 21:09:06 +00005036 return GetAlignOfType(E->getType());
5037}
5038
5039
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005040/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5041/// a result as the expression's type.
5042bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5043 const UnaryExprOrTypeTraitExpr *E) {
5044 switch(E->getKind()) {
5045 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005046 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005047 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005048 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005049 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005050 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005051
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005052 case UETT_VecStep: {
5053 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005054
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005055 if (Ty->isVectorType()) {
5056 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005057
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005058 // The vec_step built-in functions that take a 3-component
5059 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5060 if (n == 3)
5061 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005062
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005063 return Success(n, E);
5064 } else
5065 return Success(1, E);
5066 }
5067
5068 case UETT_SizeOf: {
5069 QualType SrcTy = E->getTypeOfArgument();
5070 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5071 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005072 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5073 SrcTy = Ref->getPointeeType();
5074
Richard Smith180f4792011-11-10 06:34:14 +00005075 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005076 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005077 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005078 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005079 }
5080 }
5081
5082 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005083}
5084
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005085bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005086 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005087 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005088 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005089 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005090 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005091 for (unsigned i = 0; i != n; ++i) {
5092 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5093 switch (ON.getKind()) {
5094 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005095 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005096 APSInt IdxResult;
5097 if (!EvaluateInteger(Idx, IdxResult, Info))
5098 return false;
5099 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5100 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005101 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005102 CurrentType = AT->getElementType();
5103 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5104 Result += IdxResult.getSExtValue() * ElementSize;
5105 break;
5106 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005107
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005108 case OffsetOfExpr::OffsetOfNode::Field: {
5109 FieldDecl *MemberDecl = ON.getField();
5110 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005111 if (!RT)
5112 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005113 RecordDecl *RD = RT->getDecl();
5114 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005115 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005116 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005117 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005118 CurrentType = MemberDecl->getType().getNonReferenceType();
5119 break;
5120 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005121
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005122 case OffsetOfExpr::OffsetOfNode::Identifier:
5123 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005124
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005125 case OffsetOfExpr::OffsetOfNode::Base: {
5126 CXXBaseSpecifier *BaseSpec = ON.getBase();
5127 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005128 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005129
5130 // Find the layout of the class whose base we are looking into.
5131 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005132 if (!RT)
5133 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005134 RecordDecl *RD = RT->getDecl();
5135 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5136
5137 // Find the base class itself.
5138 CurrentType = BaseSpec->getType();
5139 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5140 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005141 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005142
5143 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005144 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005145 break;
5146 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005147 }
5148 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005149 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005150}
5151
Chris Lattnerb542afe2008-07-11 19:10:17 +00005152bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005153 switch (E->getOpcode()) {
5154 default:
5155 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5156 // See C99 6.6p3.
5157 return Error(E);
5158 case UO_Extension:
5159 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5160 // If so, we could clear the diagnostic ID.
5161 return Visit(E->getSubExpr());
5162 case UO_Plus:
5163 // The result is just the value.
5164 return Visit(E->getSubExpr());
5165 case UO_Minus: {
5166 if (!Visit(E->getSubExpr()))
5167 return false;
5168 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005169 const APSInt &Value = Result.getInt();
5170 if (Value.isSigned() && Value.isMinSignedValue())
5171 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5172 E->getType());
5173 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005174 }
5175 case UO_Not: {
5176 if (!Visit(E->getSubExpr()))
5177 return false;
5178 if (!Result.isInt()) return Error(E);
5179 return Success(~Result.getInt(), E);
5180 }
5181 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005182 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005183 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005184 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005185 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005186 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005187 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005188}
Mike Stump1eb44332009-09-09 15:08:12 +00005189
Chris Lattner732b2232008-07-12 01:15:53 +00005190/// HandleCast - This is used to evaluate implicit or explicit casts where the
5191/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005192bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5193 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005194 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005195 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005196
Eli Friedman46a52322011-03-25 00:43:55 +00005197 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005198 case CK_BaseToDerived:
5199 case CK_DerivedToBase:
5200 case CK_UncheckedDerivedToBase:
5201 case CK_Dynamic:
5202 case CK_ToUnion:
5203 case CK_ArrayToPointerDecay:
5204 case CK_FunctionToPointerDecay:
5205 case CK_NullToPointer:
5206 case CK_NullToMemberPointer:
5207 case CK_BaseToDerivedMemberPointer:
5208 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005209 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005210 case CK_ConstructorConversion:
5211 case CK_IntegralToPointer:
5212 case CK_ToVoid:
5213 case CK_VectorSplat:
5214 case CK_IntegralToFloating:
5215 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005216 case CK_CPointerToObjCPointerCast:
5217 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005218 case CK_AnyPointerToBlockPointerCast:
5219 case CK_ObjCObjectLValueCast:
5220 case CK_FloatingRealToComplex:
5221 case CK_FloatingComplexToReal:
5222 case CK_FloatingComplexCast:
5223 case CK_FloatingComplexToIntegralComplex:
5224 case CK_IntegralRealToComplex:
5225 case CK_IntegralComplexCast:
5226 case CK_IntegralComplexToFloatingComplex:
5227 llvm_unreachable("invalid cast kind for integral value");
5228
Eli Friedmane50c2972011-03-25 19:07:11 +00005229 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005230 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005231 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005232 case CK_ARCProduceObject:
5233 case CK_ARCConsumeObject:
5234 case CK_ARCReclaimReturnedObject:
5235 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005236 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005237 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005238
Richard Smith7d580a42012-01-17 21:17:26 +00005239 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005240 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005241 case CK_AtomicToNonAtomic:
5242 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005243 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005244 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005245
5246 case CK_MemberPointerToBoolean:
5247 case CK_PointerToBoolean:
5248 case CK_IntegralToBoolean:
5249 case CK_FloatingToBoolean:
5250 case CK_FloatingComplexToBoolean:
5251 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005252 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005253 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005254 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005255 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005256 }
5257
Eli Friedman46a52322011-03-25 00:43:55 +00005258 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005259 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005260 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005261
Eli Friedmanbe265702009-02-20 01:15:07 +00005262 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005263 // Allow casts of address-of-label differences if they are no-ops
5264 // or narrowing. (The narrowing case isn't actually guaranteed to
5265 // be constant-evaluatable except in some narrow cases which are hard
5266 // to detect here. We let it through on the assumption the user knows
5267 // what they are doing.)
5268 if (Result.isAddrLabelDiff())
5269 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005270 // Only allow casts of lvalues if they are lossless.
5271 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5272 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005273
Richard Smithf72fccf2012-01-30 22:27:01 +00005274 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5275 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005276 }
Mike Stump1eb44332009-09-09 15:08:12 +00005277
Eli Friedman46a52322011-03-25 00:43:55 +00005278 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005279 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5280
John McCallefdb83e2010-05-07 21:00:08 +00005281 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005282 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005283 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005284
Daniel Dunbardd211642009-02-19 22:24:01 +00005285 if (LV.getLValueBase()) {
5286 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005287 // FIXME: Allow a larger integer size than the pointer size, and allow
5288 // narrowing back down to pointer width in subsequent integral casts.
5289 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005290 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005291 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005292
Richard Smithb755a9d2011-11-16 07:18:12 +00005293 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005294 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005295 return true;
5296 }
5297
Ken Dycka7305832010-01-15 12:37:54 +00005298 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5299 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005300 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005301 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005302
Eli Friedman46a52322011-03-25 00:43:55 +00005303 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005304 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005305 if (!EvaluateComplex(SubExpr, C, Info))
5306 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005307 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005308 }
Eli Friedman2217c872009-02-22 11:46:18 +00005309
Eli Friedman46a52322011-03-25 00:43:55 +00005310 case CK_FloatingToIntegral: {
5311 APFloat F(0.0);
5312 if (!EvaluateFloat(SubExpr, F, Info))
5313 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005314
Richard Smithc1c5f272011-12-13 06:39:58 +00005315 APSInt Value;
5316 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5317 return false;
5318 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005319 }
5320 }
Mike Stump1eb44332009-09-09 15:08:12 +00005321
Eli Friedman46a52322011-03-25 00:43:55 +00005322 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005323}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005324
Eli Friedman722c7172009-02-28 03:59:05 +00005325bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5326 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005327 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005328 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5329 return false;
5330 if (!LV.isComplexInt())
5331 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005332 return Success(LV.getComplexIntReal(), E);
5333 }
5334
5335 return Visit(E->getSubExpr());
5336}
5337
Eli Friedman664a1042009-02-27 04:45:43 +00005338bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005339 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005340 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005341 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5342 return false;
5343 if (!LV.isComplexInt())
5344 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005345 return Success(LV.getComplexIntImag(), E);
5346 }
5347
Richard Smith8327fad2011-10-24 18:44:57 +00005348 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005349 return Success(0, E);
5350}
5351
Douglas Gregoree8aff02011-01-04 17:33:58 +00005352bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5353 return Success(E->getPackLength(), E);
5354}
5355
Sebastian Redl295995c2010-09-10 20:55:47 +00005356bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5357 return Success(E->getValue(), E);
5358}
5359
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005360//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005361// Float Evaluation
5362//===----------------------------------------------------------------------===//
5363
5364namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005365class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005366 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005367 APFloat &Result;
5368public:
5369 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005370 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005371
Richard Smith47a1eed2011-10-29 20:57:55 +00005372 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005373 Result = V.getFloat();
5374 return true;
5375 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005376
Richard Smith51201882011-12-30 21:15:51 +00005377 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005378 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5379 return true;
5380 }
5381
Chris Lattner019f4e82008-10-06 05:28:25 +00005382 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005383
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005384 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005385 bool VisitBinaryOperator(const BinaryOperator *E);
5386 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005387 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005388
John McCallabd3a852010-05-07 22:08:54 +00005389 bool VisitUnaryReal(const UnaryOperator *E);
5390 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005391
Richard Smith51201882011-12-30 21:15:51 +00005392 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005393};
5394} // end anonymous namespace
5395
5396static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005397 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005398 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005399}
5400
Jay Foad4ba2a172011-01-12 09:06:06 +00005401static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005402 QualType ResultTy,
5403 const Expr *Arg,
5404 bool SNaN,
5405 llvm::APFloat &Result) {
5406 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5407 if (!S) return false;
5408
5409 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5410
5411 llvm::APInt fill;
5412
5413 // Treat empty strings as if they were zero.
5414 if (S->getString().empty())
5415 fill = llvm::APInt(32, 0);
5416 else if (S->getString().getAsInteger(0, fill))
5417 return false;
5418
5419 if (SNaN)
5420 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5421 else
5422 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5423 return true;
5424}
5425
Chris Lattner019f4e82008-10-06 05:28:25 +00005426bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005427 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005428 default:
5429 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5430
Chris Lattner019f4e82008-10-06 05:28:25 +00005431 case Builtin::BI__builtin_huge_val:
5432 case Builtin::BI__builtin_huge_valf:
5433 case Builtin::BI__builtin_huge_vall:
5434 case Builtin::BI__builtin_inf:
5435 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005436 case Builtin::BI__builtin_infl: {
5437 const llvm::fltSemantics &Sem =
5438 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005439 Result = llvm::APFloat::getInf(Sem);
5440 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005441 }
Mike Stump1eb44332009-09-09 15:08:12 +00005442
John McCalldb7b72a2010-02-28 13:00:19 +00005443 case Builtin::BI__builtin_nans:
5444 case Builtin::BI__builtin_nansf:
5445 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005446 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5447 true, Result))
5448 return Error(E);
5449 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005450
Chris Lattner9e621712008-10-06 06:31:58 +00005451 case Builtin::BI__builtin_nan:
5452 case Builtin::BI__builtin_nanf:
5453 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005454 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005455 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005456 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5457 false, Result))
5458 return Error(E);
5459 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005460
5461 case Builtin::BI__builtin_fabs:
5462 case Builtin::BI__builtin_fabsf:
5463 case Builtin::BI__builtin_fabsl:
5464 if (!EvaluateFloat(E->getArg(0), Result, Info))
5465 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005466
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005467 if (Result.isNegative())
5468 Result.changeSign();
5469 return true;
5470
Mike Stump1eb44332009-09-09 15:08:12 +00005471 case Builtin::BI__builtin_copysign:
5472 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005473 case Builtin::BI__builtin_copysignl: {
5474 APFloat RHS(0.);
5475 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5476 !EvaluateFloat(E->getArg(1), RHS, Info))
5477 return false;
5478 Result.copySign(RHS);
5479 return true;
5480 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005481 }
5482}
5483
John McCallabd3a852010-05-07 22:08:54 +00005484bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005485 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5486 ComplexValue CV;
5487 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5488 return false;
5489 Result = CV.FloatReal;
5490 return true;
5491 }
5492
5493 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005494}
5495
5496bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005497 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5498 ComplexValue CV;
5499 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5500 return false;
5501 Result = CV.FloatImag;
5502 return true;
5503 }
5504
Richard Smith8327fad2011-10-24 18:44:57 +00005505 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005506 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5507 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005508 return true;
5509}
5510
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005511bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005512 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005513 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005514 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005515 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005516 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005517 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5518 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005519 Result.changeSign();
5520 return true;
5521 }
5522}
Chris Lattner019f4e82008-10-06 05:28:25 +00005523
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005524bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005525 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5526 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005527
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005528 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005529 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5530 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005531 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005532 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005533 return false;
5534
5535 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005536 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005537 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005538 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005539 break;
John McCall2de56d12010-08-25 11:45:40 +00005540 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005541 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005542 break;
John McCall2de56d12010-08-25 11:45:40 +00005543 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005544 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005545 break;
John McCall2de56d12010-08-25 11:45:40 +00005546 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005547 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005548 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005549 }
Richard Smith7b48a292012-02-01 05:53:12 +00005550
5551 if (Result.isInfinity() || Result.isNaN())
5552 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5553 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005554}
5555
5556bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5557 Result = E->getValue();
5558 return true;
5559}
5560
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005561bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5562 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005563
Eli Friedman2a523ee2011-03-25 00:54:52 +00005564 switch (E->getCastKind()) {
5565 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005566 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005567
5568 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005569 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005570 return EvaluateInteger(SubExpr, IntResult, Info) &&
5571 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5572 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005573 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005574
5575 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005576 if (!Visit(SubExpr))
5577 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005578 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5579 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005580 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005581
Eli Friedman2a523ee2011-03-25 00:54:52 +00005582 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005583 ComplexValue V;
5584 if (!EvaluateComplex(SubExpr, V, Info))
5585 return false;
5586 Result = V.getComplexFloatReal();
5587 return true;
5588 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005589 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005590}
5591
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005592//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005593// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005594//===----------------------------------------------------------------------===//
5595
5596namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005597class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005598 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005599 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005600
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005601public:
John McCallf4cf1a12010-05-07 17:22:02 +00005602 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005603 : ExprEvaluatorBaseTy(info), Result(Result) {}
5604
Richard Smith47a1eed2011-10-29 20:57:55 +00005605 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005606 Result.setFrom(V);
5607 return true;
5608 }
Mike Stump1eb44332009-09-09 15:08:12 +00005609
Eli Friedman7ead5c72012-01-10 04:58:17 +00005610 bool ZeroInitialization(const Expr *E);
5611
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005612 //===--------------------------------------------------------------------===//
5613 // Visitor Methods
5614 //===--------------------------------------------------------------------===//
5615
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005616 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005617 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005618 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005619 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005620 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005621};
5622} // end anonymous namespace
5623
John McCallf4cf1a12010-05-07 17:22:02 +00005624static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5625 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005626 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005627 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005628}
5629
Eli Friedman7ead5c72012-01-10 04:58:17 +00005630bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005631 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005632 if (ElemTy->isRealFloatingType()) {
5633 Result.makeComplexFloat();
5634 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5635 Result.FloatReal = Zero;
5636 Result.FloatImag = Zero;
5637 } else {
5638 Result.makeComplexInt();
5639 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5640 Result.IntReal = Zero;
5641 Result.IntImag = Zero;
5642 }
5643 return true;
5644}
5645
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005646bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5647 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005648
5649 if (SubExpr->getType()->isRealFloatingType()) {
5650 Result.makeComplexFloat();
5651 APFloat &Imag = Result.FloatImag;
5652 if (!EvaluateFloat(SubExpr, Imag, Info))
5653 return false;
5654
5655 Result.FloatReal = APFloat(Imag.getSemantics());
5656 return true;
5657 } else {
5658 assert(SubExpr->getType()->isIntegerType() &&
5659 "Unexpected imaginary literal.");
5660
5661 Result.makeComplexInt();
5662 APSInt &Imag = Result.IntImag;
5663 if (!EvaluateInteger(SubExpr, Imag, Info))
5664 return false;
5665
5666 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5667 return true;
5668 }
5669}
5670
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005671bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005672
John McCall8786da72010-12-14 17:51:41 +00005673 switch (E->getCastKind()) {
5674 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005675 case CK_BaseToDerived:
5676 case CK_DerivedToBase:
5677 case CK_UncheckedDerivedToBase:
5678 case CK_Dynamic:
5679 case CK_ToUnion:
5680 case CK_ArrayToPointerDecay:
5681 case CK_FunctionToPointerDecay:
5682 case CK_NullToPointer:
5683 case CK_NullToMemberPointer:
5684 case CK_BaseToDerivedMemberPointer:
5685 case CK_DerivedToBaseMemberPointer:
5686 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005687 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005688 case CK_ConstructorConversion:
5689 case CK_IntegralToPointer:
5690 case CK_PointerToIntegral:
5691 case CK_PointerToBoolean:
5692 case CK_ToVoid:
5693 case CK_VectorSplat:
5694 case CK_IntegralCast:
5695 case CK_IntegralToBoolean:
5696 case CK_IntegralToFloating:
5697 case CK_FloatingToIntegral:
5698 case CK_FloatingToBoolean:
5699 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005700 case CK_CPointerToObjCPointerCast:
5701 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005702 case CK_AnyPointerToBlockPointerCast:
5703 case CK_ObjCObjectLValueCast:
5704 case CK_FloatingComplexToReal:
5705 case CK_FloatingComplexToBoolean:
5706 case CK_IntegralComplexToReal:
5707 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005708 case CK_ARCProduceObject:
5709 case CK_ARCConsumeObject:
5710 case CK_ARCReclaimReturnedObject:
5711 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005712 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005713 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005714
John McCall8786da72010-12-14 17:51:41 +00005715 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005716 case CK_AtomicToNonAtomic:
5717 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005718 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005719 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005720
5721 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005722 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005723 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005724 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005725
5726 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005727 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005728 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005729 return false;
5730
John McCall8786da72010-12-14 17:51:41 +00005731 Result.makeComplexFloat();
5732 Result.FloatImag = APFloat(Real.getSemantics());
5733 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005734 }
5735
John McCall8786da72010-12-14 17:51:41 +00005736 case CK_FloatingComplexCast: {
5737 if (!Visit(E->getSubExpr()))
5738 return false;
5739
5740 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5741 QualType From
5742 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5743
Richard Smithc1c5f272011-12-13 06:39:58 +00005744 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5745 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005746 }
5747
5748 case CK_FloatingComplexToIntegralComplex: {
5749 if (!Visit(E->getSubExpr()))
5750 return false;
5751
5752 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5753 QualType From
5754 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5755 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005756 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5757 To, Result.IntReal) &&
5758 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5759 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005760 }
5761
5762 case CK_IntegralRealToComplex: {
5763 APSInt &Real = Result.IntReal;
5764 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5765 return false;
5766
5767 Result.makeComplexInt();
5768 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5769 return true;
5770 }
5771
5772 case CK_IntegralComplexCast: {
5773 if (!Visit(E->getSubExpr()))
5774 return false;
5775
5776 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5777 QualType From
5778 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5779
Richard Smithf72fccf2012-01-30 22:27:01 +00005780 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5781 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005782 return true;
5783 }
5784
5785 case CK_IntegralComplexToFloatingComplex: {
5786 if (!Visit(E->getSubExpr()))
5787 return false;
5788
5789 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5790 QualType From
5791 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5792 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005793 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5794 To, Result.FloatReal) &&
5795 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5796 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005797 }
5798 }
5799
5800 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005801}
5802
John McCallf4cf1a12010-05-07 17:22:02 +00005803bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005804 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005805 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5806
Richard Smith745f5142012-01-27 01:14:48 +00005807 bool LHSOK = Visit(E->getLHS());
5808 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005809 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005810
John McCallf4cf1a12010-05-07 17:22:02 +00005811 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005812 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005813 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005814
Daniel Dunbar3f279872009-01-29 01:32:56 +00005815 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5816 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005817 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005818 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005819 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005820 if (Result.isComplexFloat()) {
5821 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5822 APFloat::rmNearestTiesToEven);
5823 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5824 APFloat::rmNearestTiesToEven);
5825 } else {
5826 Result.getComplexIntReal() += RHS.getComplexIntReal();
5827 Result.getComplexIntImag() += RHS.getComplexIntImag();
5828 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005829 break;
John McCall2de56d12010-08-25 11:45:40 +00005830 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005831 if (Result.isComplexFloat()) {
5832 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5833 APFloat::rmNearestTiesToEven);
5834 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5835 APFloat::rmNearestTiesToEven);
5836 } else {
5837 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5838 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5839 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005840 break;
John McCall2de56d12010-08-25 11:45:40 +00005841 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005842 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005843 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005844 APFloat &LHS_r = LHS.getComplexFloatReal();
5845 APFloat &LHS_i = LHS.getComplexFloatImag();
5846 APFloat &RHS_r = RHS.getComplexFloatReal();
5847 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005848
Daniel Dunbar3f279872009-01-29 01:32:56 +00005849 APFloat Tmp = LHS_r;
5850 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5851 Result.getComplexFloatReal() = Tmp;
5852 Tmp = LHS_i;
5853 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5854 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5855
5856 Tmp = LHS_r;
5857 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5858 Result.getComplexFloatImag() = Tmp;
5859 Tmp = LHS_i;
5860 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5861 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5862 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005863 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005864 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005865 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5866 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005867 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005868 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5869 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5870 }
5871 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005872 case BO_Div:
5873 if (Result.isComplexFloat()) {
5874 ComplexValue LHS = Result;
5875 APFloat &LHS_r = LHS.getComplexFloatReal();
5876 APFloat &LHS_i = LHS.getComplexFloatImag();
5877 APFloat &RHS_r = RHS.getComplexFloatReal();
5878 APFloat &RHS_i = RHS.getComplexFloatImag();
5879 APFloat &Res_r = Result.getComplexFloatReal();
5880 APFloat &Res_i = Result.getComplexFloatImag();
5881
5882 APFloat Den = RHS_r;
5883 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5884 APFloat Tmp = RHS_i;
5885 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5886 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5887
5888 Res_r = LHS_r;
5889 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5890 Tmp = LHS_i;
5891 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5892 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5893 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5894
5895 Res_i = LHS_i;
5896 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5897 Tmp = LHS_r;
5898 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5899 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5900 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5901 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005902 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5903 return Error(E, diag::note_expr_divide_by_zero);
5904
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005905 ComplexValue LHS = Result;
5906 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5907 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5908 Result.getComplexIntReal() =
5909 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5910 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5911 Result.getComplexIntImag() =
5912 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5913 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5914 }
5915 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005916 }
5917
John McCallf4cf1a12010-05-07 17:22:02 +00005918 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005919}
5920
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005921bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5922 // Get the operand value into 'Result'.
5923 if (!Visit(E->getSubExpr()))
5924 return false;
5925
5926 switch (E->getOpcode()) {
5927 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005928 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005929 case UO_Extension:
5930 return true;
5931 case UO_Plus:
5932 // The result is always just the subexpr.
5933 return true;
5934 case UO_Minus:
5935 if (Result.isComplexFloat()) {
5936 Result.getComplexFloatReal().changeSign();
5937 Result.getComplexFloatImag().changeSign();
5938 }
5939 else {
5940 Result.getComplexIntReal() = -Result.getComplexIntReal();
5941 Result.getComplexIntImag() = -Result.getComplexIntImag();
5942 }
5943 return true;
5944 case UO_Not:
5945 if (Result.isComplexFloat())
5946 Result.getComplexFloatImag().changeSign();
5947 else
5948 Result.getComplexIntImag() = -Result.getComplexIntImag();
5949 return true;
5950 }
5951}
5952
Eli Friedman7ead5c72012-01-10 04:58:17 +00005953bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5954 if (E->getNumInits() == 2) {
5955 if (E->getType()->isComplexType()) {
5956 Result.makeComplexFloat();
5957 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5958 return false;
5959 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5960 return false;
5961 } else {
5962 Result.makeComplexInt();
5963 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5964 return false;
5965 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5966 return false;
5967 }
5968 return true;
5969 }
5970 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5971}
5972
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005973//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005974// Void expression evaluation, primarily for a cast to void on the LHS of a
5975// comma operator
5976//===----------------------------------------------------------------------===//
5977
5978namespace {
5979class VoidExprEvaluator
5980 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5981public:
5982 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5983
5984 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005985
5986 bool VisitCastExpr(const CastExpr *E) {
5987 switch (E->getCastKind()) {
5988 default:
5989 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5990 case CK_ToVoid:
5991 VisitIgnoredValue(E->getSubExpr());
5992 return true;
5993 }
5994 }
5995};
5996} // end anonymous namespace
5997
5998static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5999 assert(E->isRValue() && E->getType()->isVoidType());
6000 return VoidExprEvaluator(Info).Visit(E);
6001}
6002
6003//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006004// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006005//===----------------------------------------------------------------------===//
6006
Richard Smith47a1eed2011-10-29 20:57:55 +00006007static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006008 // In C, function designators are not lvalues, but we evaluate them as if they
6009 // are.
6010 if (E->isGLValue() || E->getType()->isFunctionType()) {
6011 LValue LV;
6012 if (!EvaluateLValue(E, LV, Info))
6013 return false;
6014 LV.moveInto(Result);
6015 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006016 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006017 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006018 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006019 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006020 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006021 } else if (E->getType()->hasPointerRepresentation()) {
6022 LValue LV;
6023 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006024 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006025 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006026 } else if (E->getType()->isRealFloatingType()) {
6027 llvm::APFloat F(0.0);
6028 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006029 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00006030 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006031 } else if (E->getType()->isAnyComplexType()) {
6032 ComplexValue C;
6033 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006034 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006035 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006036 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006037 MemberPtr P;
6038 if (!EvaluateMemberPointer(E, P, Info))
6039 return false;
6040 P.moveInto(Result);
6041 return true;
Richard Smith51201882011-12-30 21:15:51 +00006042 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006043 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006044 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006045 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006046 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006047 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006048 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006049 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006050 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006051 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6052 return false;
6053 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006054 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00006055 if (Info.getLangOpts().CPlusPlus0x)
6056 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
6057 << E->getType();
6058 else
6059 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00006060 if (!EvaluateVoid(E, Info))
6061 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006062 } else if (Info.getLangOpts().CPlusPlus0x) {
6063 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
6064 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006065 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00006066 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006067 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006068 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006069
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006070 return true;
6071}
6072
Richard Smith83587db2012-02-15 02:18:13 +00006073/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6074/// cases, the in-place evaluation is essential, since later initializers for
6075/// an object can indirectly refer to subobjects which were initialized earlier.
6076static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6077 const Expr *E, CheckConstantExpressionKind CCEK,
6078 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006079 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006080 return false;
6081
6082 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006083 // Evaluate arrays and record types in-place, so that later initializers can
6084 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006085 if (E->getType()->isArrayType())
6086 return EvaluateArray(E, This, Result, Info);
6087 else if (E->getType()->isRecordType())
6088 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006089 }
6090
6091 // For any other type, in-place evaluation is unimportant.
6092 CCValue CoreConstResult;
Richard Smith83587db2012-02-15 02:18:13 +00006093 if (!Evaluate(CoreConstResult, Info, E))
6094 return false;
6095 Result = CoreConstResult.toAPValue();
6096 return true;
Richard Smith69c2c502011-11-04 05:33:44 +00006097}
6098
Richard Smithf48fdb02011-12-09 22:58:01 +00006099/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6100/// lvalue-to-rvalue cast if it is an lvalue.
6101static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006102 if (!CheckLiteralType(Info, E))
6103 return false;
6104
Richard Smithf48fdb02011-12-09 22:58:01 +00006105 CCValue Value;
6106 if (!::Evaluate(Value, Info, E))
6107 return false;
6108
6109 if (E->isGLValue()) {
6110 LValue LV;
6111 LV.setFrom(Value);
6112 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
6113 return false;
6114 }
6115
6116 // Check this core constant expression is a constant expression, and if so,
6117 // convert it to one.
Richard Smith83587db2012-02-15 02:18:13 +00006118 Result = Value.toAPValue();
6119 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006120}
Richard Smithc49bd112011-10-28 17:51:58 +00006121
Richard Smith51f47082011-10-29 00:50:52 +00006122/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006123/// any crazy technique (that has nothing to do with language standards) that
6124/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006125/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6126/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006127bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006128 // Fast-path evaluations of integer literals, since we sometimes see files
6129 // containing vast quantities of these.
6130 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6131 Result.Val = APValue(APSInt(L->getValue(),
6132 L->getType()->isUnsignedIntegerType()));
6133 return true;
6134 }
6135
Richard Smith2d6a5672012-01-14 04:30:29 +00006136 // FIXME: Evaluating values of large array and record types can cause
6137 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006138 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6139 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006140 return false;
6141
Richard Smithf48fdb02011-12-09 22:58:01 +00006142 EvalInfo Info(Ctx, Result);
6143 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006144}
6145
Jay Foad4ba2a172011-01-12 09:06:06 +00006146bool Expr::EvaluateAsBooleanCondition(bool &Result,
6147 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006148 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006149 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00006150 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
6151 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00006152 Result);
John McCallcd7a4452010-01-05 23:42:56 +00006153}
6154
Richard Smith80d4b552011-12-28 19:48:30 +00006155bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6156 SideEffectsKind AllowSideEffects) const {
6157 if (!getType()->isIntegralOrEnumerationType())
6158 return false;
6159
Richard Smithc49bd112011-10-28 17:51:58 +00006160 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006161 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6162 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006163 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006164
Richard Smithc49bd112011-10-28 17:51:58 +00006165 Result = ExprResult.Val.getInt();
6166 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006167}
6168
Jay Foad4ba2a172011-01-12 09:06:06 +00006169bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006170 EvalInfo Info(Ctx, Result);
6171
John McCallefdb83e2010-05-07 21:00:08 +00006172 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006173 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6174 !CheckLValueConstantExpression(Info, getExprLoc(),
6175 Ctx.getLValueReferenceType(getType()), LV))
6176 return false;
6177
6178 CCValue Tmp;
6179 LV.moveInto(Tmp);
6180 Result.Val = Tmp.toAPValue();
6181 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006182}
6183
Richard Smith099e7f62011-12-19 06:19:21 +00006184bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6185 const VarDecl *VD,
6186 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006187 // FIXME: Evaluating initializers for large array and record types can cause
6188 // performance problems. Only do so in C++11 for now.
6189 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6190 !Ctx.getLangOptions().CPlusPlus0x)
6191 return false;
6192
Richard Smith099e7f62011-12-19 06:19:21 +00006193 Expr::EvalStatus EStatus;
6194 EStatus.Diag = &Notes;
6195
6196 EvalInfo InitInfo(Ctx, EStatus);
6197 InitInfo.setEvaluatingDecl(VD, Value);
6198
6199 LValue LVal;
6200 LVal.set(VD);
6201
Richard Smith51201882011-12-30 21:15:51 +00006202 // C++11 [basic.start.init]p2:
6203 // Variables with static storage duration or thread storage duration shall be
6204 // zero-initialized before any other initialization takes place.
6205 // This behavior is not present in C.
6206 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
6207 !VD->getType()->isReferenceType()) {
6208 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006209 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6210 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006211 return false;
6212 }
6213
Richard Smith83587db2012-02-15 02:18:13 +00006214 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6215 /*AllowNonLiteralTypes=*/true) ||
6216 EStatus.HasSideEffects)
6217 return false;
6218
6219 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6220 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006221}
6222
Richard Smith51f47082011-10-29 00:50:52 +00006223/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6224/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006225bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006226 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006227 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006228}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006229
Jay Foad4ba2a172011-01-12 09:06:06 +00006230bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006231 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006232}
6233
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006234APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006235 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006236 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006237 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006238 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006239 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006240
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006241 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006242}
John McCalld905f5a2010-05-07 05:32:02 +00006243
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006244 bool Expr::EvalResult::isGlobalLValue() const {
6245 assert(Val.isLValue());
6246 return IsGlobalLValue(Val.getLValueBase());
6247 }
6248
6249
John McCalld905f5a2010-05-07 05:32:02 +00006250/// isIntegerConstantExpr - this recursive routine will test if an expression is
6251/// an integer constant expression.
6252
6253/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6254/// comma, etc
6255///
6256/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6257/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6258/// cast+dereference.
6259
6260// CheckICE - This function does the fundamental ICE checking: the returned
6261// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6262// Note that to reduce code duplication, this helper does no evaluation
6263// itself; the caller checks whether the expression is evaluatable, and
6264// in the rare cases where CheckICE actually cares about the evaluated
6265// value, it calls into Evalute.
6266//
6267// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006268// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006269// 1: This expression is not an ICE, but if it isn't evaluated, it's
6270// a legal subexpression for an ICE. This return value is used to handle
6271// the comma operator in C99 mode.
6272// 2: This expression is not an ICE, and is not a legal subexpression for one.
6273
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006274namespace {
6275
John McCalld905f5a2010-05-07 05:32:02 +00006276struct ICEDiag {
6277 unsigned Val;
6278 SourceLocation Loc;
6279
6280 public:
6281 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6282 ICEDiag() : Val(0) {}
6283};
6284
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006285}
6286
6287static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006288
6289static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6290 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006291 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006292 !EVResult.Val.isInt()) {
6293 return ICEDiag(2, E->getLocStart());
6294 }
6295 return NoDiag();
6296}
6297
6298static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6299 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006300 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006301 return ICEDiag(2, E->getLocStart());
6302 }
6303
6304 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006305#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006306#define STMT(Node, Base) case Expr::Node##Class:
6307#define EXPR(Node, Base)
6308#include "clang/AST/StmtNodes.inc"
6309 case Expr::PredefinedExprClass:
6310 case Expr::FloatingLiteralClass:
6311 case Expr::ImaginaryLiteralClass:
6312 case Expr::StringLiteralClass:
6313 case Expr::ArraySubscriptExprClass:
6314 case Expr::MemberExprClass:
6315 case Expr::CompoundAssignOperatorClass:
6316 case Expr::CompoundLiteralExprClass:
6317 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006318 case Expr::DesignatedInitExprClass:
6319 case Expr::ImplicitValueInitExprClass:
6320 case Expr::ParenListExprClass:
6321 case Expr::VAArgExprClass:
6322 case Expr::AddrLabelExprClass:
6323 case Expr::StmtExprClass:
6324 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006325 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006326 case Expr::CXXDynamicCastExprClass:
6327 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006328 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006329 case Expr::CXXNullPtrLiteralExprClass:
6330 case Expr::CXXThisExprClass:
6331 case Expr::CXXThrowExprClass:
6332 case Expr::CXXNewExprClass:
6333 case Expr::CXXDeleteExprClass:
6334 case Expr::CXXPseudoDestructorExprClass:
6335 case Expr::UnresolvedLookupExprClass:
6336 case Expr::DependentScopeDeclRefExprClass:
6337 case Expr::CXXConstructExprClass:
6338 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006339 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006340 case Expr::CXXTemporaryObjectExprClass:
6341 case Expr::CXXUnresolvedConstructExprClass:
6342 case Expr::CXXDependentScopeMemberExprClass:
6343 case Expr::UnresolvedMemberExprClass:
6344 case Expr::ObjCStringLiteralClass:
6345 case Expr::ObjCEncodeExprClass:
6346 case Expr::ObjCMessageExprClass:
6347 case Expr::ObjCSelectorExprClass:
6348 case Expr::ObjCProtocolExprClass:
6349 case Expr::ObjCIvarRefExprClass:
6350 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006351 case Expr::ObjCIsaExprClass:
6352 case Expr::ShuffleVectorExprClass:
6353 case Expr::BlockExprClass:
6354 case Expr::BlockDeclRefExprClass:
6355 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006356 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006357 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006358 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006359 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006360 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006361 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006362 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006363 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006364 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006365 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006366 return ICEDiag(2, E->getLocStart());
6367
Douglas Gregoree8aff02011-01-04 17:33:58 +00006368 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006369 case Expr::GNUNullExprClass:
6370 // GCC considers the GNU __null value to be an integral constant expression.
6371 return NoDiag();
6372
John McCall91a57552011-07-15 05:09:51 +00006373 case Expr::SubstNonTypeTemplateParmExprClass:
6374 return
6375 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6376
John McCalld905f5a2010-05-07 05:32:02 +00006377 case Expr::ParenExprClass:
6378 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006379 case Expr::GenericSelectionExprClass:
6380 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006381 case Expr::IntegerLiteralClass:
6382 case Expr::CharacterLiteralClass:
6383 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006384 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006385 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006386 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006387 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006388 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006389 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006390 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006391 return NoDiag();
6392 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006393 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006394 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6395 // constant expressions, but they can never be ICEs because an ICE cannot
6396 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006397 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006398 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006399 return CheckEvalInICE(E, Ctx);
6400 return ICEDiag(2, E->getLocStart());
6401 }
Richard Smith359c89d2012-02-24 22:12:32 +00006402 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006403 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6404 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006405 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
6406 if (Ctx.getLangOptions().CPlusPlus &&
6407 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006408 // Parameter variables are never constants. Without this check,
6409 // getAnyInitializer() can find a default argument, which leads
6410 // to chaos.
6411 if (isa<ParmVarDecl>(D))
6412 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6413
6414 // C++ 7.1.5.1p2
6415 // A variable of non-volatile const-qualified integral or enumeration
6416 // type initialized by an ICE can be used in ICEs.
6417 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006418 if (!Dcl->getType()->isIntegralOrEnumerationType())
6419 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6420
Richard Smith099e7f62011-12-19 06:19:21 +00006421 const VarDecl *VD;
6422 // Look for a declaration of this variable that has an initializer, and
6423 // check whether it is an ICE.
6424 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6425 return NoDiag();
6426 else
6427 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006428 }
6429 }
6430 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006431 }
John McCalld905f5a2010-05-07 05:32:02 +00006432 case Expr::UnaryOperatorClass: {
6433 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6434 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006435 case UO_PostInc:
6436 case UO_PostDec:
6437 case UO_PreInc:
6438 case UO_PreDec:
6439 case UO_AddrOf:
6440 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006441 // C99 6.6/3 allows increment and decrement within unevaluated
6442 // subexpressions of constant expressions, but they can never be ICEs
6443 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006444 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006445 case UO_Extension:
6446 case UO_LNot:
6447 case UO_Plus:
6448 case UO_Minus:
6449 case UO_Not:
6450 case UO_Real:
6451 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006452 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006453 }
6454
6455 // OffsetOf falls through here.
6456 }
6457 case Expr::OffsetOfExprClass: {
6458 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006459 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006460 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006461 // compliance: we should warn earlier for offsetof expressions with
6462 // array subscripts that aren't ICEs, and if the array subscripts
6463 // are ICEs, the value of the offsetof must be an integer constant.
6464 return CheckEvalInICE(E, Ctx);
6465 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006466 case Expr::UnaryExprOrTypeTraitExprClass: {
6467 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6468 if ((Exp->getKind() == UETT_SizeOf) &&
6469 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006470 return ICEDiag(2, E->getLocStart());
6471 return NoDiag();
6472 }
6473 case Expr::BinaryOperatorClass: {
6474 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6475 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006476 case BO_PtrMemD:
6477 case BO_PtrMemI:
6478 case BO_Assign:
6479 case BO_MulAssign:
6480 case BO_DivAssign:
6481 case BO_RemAssign:
6482 case BO_AddAssign:
6483 case BO_SubAssign:
6484 case BO_ShlAssign:
6485 case BO_ShrAssign:
6486 case BO_AndAssign:
6487 case BO_XorAssign:
6488 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006489 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6490 // constant expressions, but they can never be ICEs because an ICE cannot
6491 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006492 return ICEDiag(2, E->getLocStart());
6493
John McCall2de56d12010-08-25 11:45:40 +00006494 case BO_Mul:
6495 case BO_Div:
6496 case BO_Rem:
6497 case BO_Add:
6498 case BO_Sub:
6499 case BO_Shl:
6500 case BO_Shr:
6501 case BO_LT:
6502 case BO_GT:
6503 case BO_LE:
6504 case BO_GE:
6505 case BO_EQ:
6506 case BO_NE:
6507 case BO_And:
6508 case BO_Xor:
6509 case BO_Or:
6510 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006511 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6512 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006513 if (Exp->getOpcode() == BO_Div ||
6514 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006515 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006516 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006517 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006518 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006519 if (REval == 0)
6520 return ICEDiag(1, E->getLocStart());
6521 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006522 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006523 if (LEval.isMinSignedValue())
6524 return ICEDiag(1, E->getLocStart());
6525 }
6526 }
6527 }
John McCall2de56d12010-08-25 11:45:40 +00006528 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006529 if (Ctx.getLangOptions().C99) {
6530 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6531 // if it isn't evaluated.
6532 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6533 return ICEDiag(1, E->getLocStart());
6534 } else {
6535 // In both C89 and C++, commas in ICEs are illegal.
6536 return ICEDiag(2, E->getLocStart());
6537 }
6538 }
6539 if (LHSResult.Val >= RHSResult.Val)
6540 return LHSResult;
6541 return RHSResult;
6542 }
John McCall2de56d12010-08-25 11:45:40 +00006543 case BO_LAnd:
6544 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006545 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6546 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6547 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6548 // Rare case where the RHS has a comma "side-effect"; we need
6549 // to actually check the condition to see whether the side
6550 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006551 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006552 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006553 return RHSResult;
6554 return NoDiag();
6555 }
6556
6557 if (LHSResult.Val >= RHSResult.Val)
6558 return LHSResult;
6559 return RHSResult;
6560 }
6561 }
6562 }
6563 case Expr::ImplicitCastExprClass:
6564 case Expr::CStyleCastExprClass:
6565 case Expr::CXXFunctionalCastExprClass:
6566 case Expr::CXXStaticCastExprClass:
6567 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006568 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006569 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006570 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006571 if (isa<ExplicitCastExpr>(E)) {
6572 if (const FloatingLiteral *FL
6573 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6574 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6575 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6576 APSInt IgnoredVal(DestWidth, !DestSigned);
6577 bool Ignored;
6578 // If the value does not fit in the destination type, the behavior is
6579 // undefined, so we are not required to treat it as a constant
6580 // expression.
6581 if (FL->getValue().convertToInteger(IgnoredVal,
6582 llvm::APFloat::rmTowardZero,
6583 &Ignored) & APFloat::opInvalidOp)
6584 return ICEDiag(2, E->getLocStart());
6585 return NoDiag();
6586 }
6587 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006588 switch (cast<CastExpr>(E)->getCastKind()) {
6589 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006590 case CK_AtomicToNonAtomic:
6591 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006592 case CK_NoOp:
6593 case CK_IntegralToBoolean:
6594 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006595 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006596 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006597 return ICEDiag(2, E->getLocStart());
6598 }
John McCalld905f5a2010-05-07 05:32:02 +00006599 }
John McCall56ca35d2011-02-17 10:25:35 +00006600 case Expr::BinaryConditionalOperatorClass: {
6601 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6602 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6603 if (CommonResult.Val == 2) return CommonResult;
6604 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6605 if (FalseResult.Val == 2) return FalseResult;
6606 if (CommonResult.Val == 1) return CommonResult;
6607 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006608 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006609 return FalseResult;
6610 }
John McCalld905f5a2010-05-07 05:32:02 +00006611 case Expr::ConditionalOperatorClass: {
6612 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6613 // If the condition (ignoring parens) is a __builtin_constant_p call,
6614 // then only the true side is actually considered in an integer constant
6615 // expression, and it is fully evaluated. This is an important GNU
6616 // extension. See GCC PR38377 for discussion.
6617 if (const CallExpr *CallCE
6618 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006619 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6620 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006621 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006622 if (CondResult.Val == 2)
6623 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006624
Richard Smithf48fdb02011-12-09 22:58:01 +00006625 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6626 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006627
John McCalld905f5a2010-05-07 05:32:02 +00006628 if (TrueResult.Val == 2)
6629 return TrueResult;
6630 if (FalseResult.Val == 2)
6631 return FalseResult;
6632 if (CondResult.Val == 1)
6633 return CondResult;
6634 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6635 return NoDiag();
6636 // Rare case where the diagnostics depend on which side is evaluated
6637 // Note that if we get here, CondResult is 0, and at least one of
6638 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006639 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006640 return FalseResult;
6641 }
6642 return TrueResult;
6643 }
6644 case Expr::CXXDefaultArgExprClass:
6645 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6646 case Expr::ChooseExprClass: {
6647 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6648 }
6649 }
6650
David Blaikie30263482012-01-20 21:50:17 +00006651 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006652}
6653
Richard Smithf48fdb02011-12-09 22:58:01 +00006654/// Evaluate an expression as a C++11 integral constant expression.
6655static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6656 const Expr *E,
6657 llvm::APSInt *Value,
6658 SourceLocation *Loc) {
6659 if (!E->getType()->isIntegralOrEnumerationType()) {
6660 if (Loc) *Loc = E->getExprLoc();
6661 return false;
6662 }
6663
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006664 APValue Result;
6665 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006666 return false;
6667
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006668 assert(Result.isInt() && "pointer cast to int is not an ICE");
6669 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006670 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006671}
6672
Richard Smithdd1f29b2011-12-12 09:28:41 +00006673bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006674 if (Ctx.getLangOptions().CPlusPlus0x)
6675 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6676
John McCalld905f5a2010-05-07 05:32:02 +00006677 ICEDiag d = CheckICE(this, Ctx);
6678 if (d.Val != 0) {
6679 if (Loc) *Loc = d.Loc;
6680 return false;
6681 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006682 return true;
6683}
6684
6685bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6686 SourceLocation *Loc, bool isEvaluated) const {
6687 if (Ctx.getLangOptions().CPlusPlus0x)
6688 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6689
6690 if (!isIntegerConstantExpr(Ctx, Loc))
6691 return false;
6692 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006693 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006694 return true;
6695}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006696
Richard Smith70488e22012-02-14 21:38:30 +00006697bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6698 return CheckICE(this, Ctx).Val == 0;
6699}
6700
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006701bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6702 SourceLocation *Loc) const {
6703 // We support this checking in C++98 mode in order to diagnose compatibility
6704 // issues.
6705 assert(Ctx.getLangOptions().CPlusPlus);
6706
Richard Smith70488e22012-02-14 21:38:30 +00006707 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006708 Expr::EvalStatus Status;
6709 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6710 Status.Diag = &Diags;
6711 EvalInfo Info(Ctx, Status);
6712
6713 APValue Scratch;
6714 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6715
6716 if (!Diags.empty()) {
6717 IsConstExpr = false;
6718 if (Loc) *Loc = Diags[0].first;
6719 } else if (!IsConstExpr) {
6720 // FIXME: This shouldn't happen.
6721 if (Loc) *Loc = getExprLoc();
6722 }
6723
6724 return IsConstExpr;
6725}
Richard Smith745f5142012-01-27 01:14:48 +00006726
6727bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6728 llvm::SmallVectorImpl<
6729 PartialDiagnosticAt> &Diags) {
6730 // FIXME: It would be useful to check constexpr function templates, but at the
6731 // moment the constant expression evaluator cannot cope with the non-rigorous
6732 // ASTs which we build for dependent expressions.
6733 if (FD->isDependentContext())
6734 return true;
6735
6736 Expr::EvalStatus Status;
6737 Status.Diag = &Diags;
6738
6739 EvalInfo Info(FD->getASTContext(), Status);
6740 Info.CheckingPotentialConstantExpression = true;
6741
6742 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6743 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6744
6745 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6746 // is a temporary being used as the 'this' pointer.
6747 LValue This;
6748 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006749 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006750
Richard Smith745f5142012-01-27 01:14:48 +00006751 ArrayRef<const Expr*> Args;
6752
6753 SourceLocation Loc = FD->getLocation();
6754
6755 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Richard Smith83587db2012-02-15 02:18:13 +00006756 APValue Scratch;
Richard Smith745f5142012-01-27 01:14:48 +00006757 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith83587db2012-02-15 02:18:13 +00006758 } else {
6759 CCValue Scratch;
Richard Smith745f5142012-01-27 01:14:48 +00006760 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6761 Args, FD->getBody(), Info, Scratch);
Richard Smith83587db2012-02-15 02:18:13 +00006762 }
Richard Smith745f5142012-01-27 01:14:48 +00006763
6764 return Diags.empty();
6765}