blob: 0f8de63bba1d0858d6683da9b03bb504b8af5b3d [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith745f5142012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlssonc44eec62008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000038#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000039#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000040#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000041#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000042#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000047#include <cstring>
48
Anders Carlssonc44eec62008-07-03 04:20:39 +000049using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000050using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000051using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000052
Chris Lattner87eae5e2008-07-11 22:52:41 +000053/// EvalInfo - This is a private struct used by the evaluator to capture
54/// information about a subexpression as it is folded. It retains information
55/// about the AST context, but also maintains information about the folded
56/// expression.
57///
58/// If an expression could be evaluated, it is still possible it is not a C
59/// "integer constant expression" or constant expression. If not, this struct
60/// captures information about how and why not.
61///
62/// One bit of information passed *into* the request for constant folding
63/// indicates whether the subexpression is "evaluated" or not according to C
64/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
65/// evaluate the expression regardless of what the RHS is, but C only allows
66/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000067namespace {
Richard Smith180f4792011-11-10 06:34:14 +000068 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000069 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000070 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000071
Richard Smith1bf9a9e2011-11-12 22:28:03 +000072 QualType getType(APValue::LValueBase B) {
73 if (!B) return QualType();
74 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
75 return D->getType();
76 return B.get<const Expr*>()->getType();
77 }
78
Richard Smith180f4792011-11-10 06:34:14 +000079 /// Get an LValue path entry, which is known to not be an array index, as a
80 /// field declaration.
81 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
82 APValue::BaseOrMemberType Value;
83 Value.setFromOpaqueValue(E.BaseOrMember);
84 return dyn_cast<FieldDecl>(Value.getPointer());
85 }
86 /// Get an LValue path entry, which is known to not be an array index, as a
87 /// base class declaration.
88 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
89 APValue::BaseOrMemberType Value;
90 Value.setFromOpaqueValue(E.BaseOrMember);
91 return dyn_cast<CXXRecordDecl>(Value.getPointer());
92 }
93 /// Determine whether this LValue path entry for a base class names a virtual
94 /// base class.
95 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
96 APValue::BaseOrMemberType Value;
97 Value.setFromOpaqueValue(E.BaseOrMember);
98 return Value.getInt();
99 }
100
Richard Smithb4e85ed2012-01-06 16:39:00 +0000101 /// Find the path length and type of the most-derived subobject in the given
102 /// path, and find the size of the containing array, if any.
103 static
104 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
105 ArrayRef<APValue::LValuePathEntry> Path,
106 uint64_t &ArraySize, QualType &Type) {
107 unsigned MostDerivedLength = 0;
108 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000109 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000110 if (Type->isArrayType()) {
111 const ConstantArrayType *CAT =
112 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
113 Type = CAT->getElementType();
114 ArraySize = CAT->getSize().getZExtValue();
115 MostDerivedLength = I + 1;
116 } else if (const FieldDecl *FD = getAsField(Path[I])) {
117 Type = FD->getType();
118 ArraySize = 0;
119 MostDerivedLength = I + 1;
120 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000121 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000122 ArraySize = 0;
123 }
Richard Smith9a17a682011-11-07 05:07:52 +0000124 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000125 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000126 }
127
Richard Smithb4e85ed2012-01-06 16:39:00 +0000128 // The order of this enum is important for diagnostics.
129 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000130 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
131 CSK_This
Richard Smithb4e85ed2012-01-06 16:39:00 +0000132 };
133
Richard Smith0a3bdb62011-11-04 02:25:55 +0000134 /// A path from a glvalue to a subobject of that glvalue.
135 struct SubobjectDesignator {
136 /// True if the subobject was named in a manner not supported by C++11. Such
137 /// lvalues can still be folded, but they are not core constant expressions
138 /// and we cannot perform lvalue-to-rvalue conversions on them.
139 bool Invalid : 1;
140
Richard Smithb4e85ed2012-01-06 16:39:00 +0000141 /// Is this a pointer one past the end of an object?
142 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000143
Richard Smithb4e85ed2012-01-06 16:39:00 +0000144 /// The length of the path to the most-derived object of which this is a
145 /// subobject.
146 unsigned MostDerivedPathLength : 30;
147
148 /// The size of the array of which the most-derived object is an element, or
149 /// 0 if the most-derived object is not an array element.
150 uint64_t MostDerivedArraySize;
151
152 /// The type of the most derived object referred to by this address.
153 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000154
Richard Smith9a17a682011-11-07 05:07:52 +0000155 typedef APValue::LValuePathEntry PathEntry;
156
Richard Smith0a3bdb62011-11-04 02:25:55 +0000157 /// The entries on the path from the glvalue to the designated subobject.
158 SmallVector<PathEntry, 8> Entries;
159
Richard Smithb4e85ed2012-01-06 16:39:00 +0000160 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000161
Richard Smithb4e85ed2012-01-06 16:39:00 +0000162 explicit SubobjectDesignator(QualType T)
163 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
164 MostDerivedArraySize(0), MostDerivedType(T) {}
165
166 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
167 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
168 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000169 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000170 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000171 ArrayRef<PathEntry> VEntries = V.getLValuePath();
172 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
173 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000174 MostDerivedPathLength =
175 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
176 V.getLValuePath(), MostDerivedArraySize,
177 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000178 }
179 }
180
Richard Smith0a3bdb62011-11-04 02:25:55 +0000181 void setInvalid() {
182 Invalid = true;
183 Entries.clear();
184 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000185
186 /// Determine whether this is a one-past-the-end pointer.
187 bool isOnePastTheEnd() const {
188 if (IsOnePastTheEnd)
189 return true;
190 if (MostDerivedArraySize &&
191 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
192 return true;
193 return false;
194 }
195
196 /// Check that this refers to a valid subobject.
197 bool isValidSubobject() const {
198 if (Invalid)
199 return false;
200 return !isOnePastTheEnd();
201 }
202 /// Check that this refers to a valid subobject, and if not, produce a
203 /// relevant diagnostic and set the designator as invalid.
204 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
205
206 /// Update this designator to refer to the first element within this array.
207 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000208 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000209 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000210 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000211
212 // This is a most-derived object.
213 MostDerivedType = CAT->getElementType();
214 MostDerivedArraySize = CAT->getSize().getZExtValue();
215 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000216 }
217 /// Update this designator to refer to the given base or member of this
218 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000219 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000220 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000221 APValue::BaseOrMemberType Value(D, Virtual);
222 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000223 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000224
225 // If this isn't a base class, it's a new most-derived object.
226 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
227 MostDerivedType = FD->getType();
228 MostDerivedArraySize = 0;
229 MostDerivedPathLength = Entries.size();
230 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000231 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000232 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000233 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000234 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000235 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000236 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000237 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000238 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
239 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
240 setInvalid();
241 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000242 return;
243 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000244 // [expr.add]p4: For the purposes of these operators, a pointer to a
245 // nonarray object behaves the same as a pointer to the first element of
246 // an array of length one with the type of the object as its element type.
247 if (IsOnePastTheEnd && N == (uint64_t)-1)
248 IsOnePastTheEnd = false;
249 else if (!IsOnePastTheEnd && N == 1)
250 IsOnePastTheEnd = true;
251 else if (N != 0) {
252 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000253 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000254 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000255 }
256 };
257
Richard Smith47a1eed2011-10-29 20:57:55 +0000258 /// A core constant value. This can be the value of any constant expression,
259 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000260 ///
261 /// For an LValue, the base and offset are stored in the APValue subobject,
262 /// but the other information is stored in the SubobjectDesignator. For all
263 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000264 class CCValue : public APValue {
265 typedef llvm::APSInt APSInt;
266 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000267 /// If the value is a reference or pointer into a parameter or temporary,
268 /// this is the corresponding call stack frame.
269 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000270 /// If the value is a reference or pointer, this is a description of how the
271 /// subobject was specified.
272 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000273 public:
Richard Smith177dce72011-11-01 16:57:24 +0000274 struct GlobalValue {};
275
Richard Smith47a1eed2011-10-29 20:57:55 +0000276 CCValue() {}
277 explicit CCValue(const APSInt &I) : APValue(I) {}
278 explicit CCValue(const APFloat &F) : APValue(F) {}
279 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
280 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
281 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000282 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000283 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000284 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000285 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000286 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
287 APValue(V), CallFrame(0), Designator(Ctx, V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000288 CCValue(const ValueDecl *D, bool IsDerivedMember,
289 ArrayRef<const CXXRecordDecl*> Path) :
290 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000291 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
292 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000293
Richard Smith177dce72011-11-01 16:57:24 +0000294 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000295 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000296 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000297 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000298 SubobjectDesignator &getLValueDesignator() {
299 assert(getKind() == LValue);
300 return Designator;
301 }
302 const SubobjectDesignator &getLValueDesignator() const {
303 return const_cast<CCValue*>(this)->getLValueDesignator();
304 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000305 };
306
Richard Smithd0dccea2011-10-28 22:34:42 +0000307 /// A stack frame in the constexpr call stack.
308 struct CallStackFrame {
309 EvalInfo &Info;
310
311 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000312 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000313
Richard Smith08d6e032011-12-16 19:06:07 +0000314 /// CallLoc - The location of the call expression for this call.
315 SourceLocation CallLoc;
316
317 /// Callee - The function which was called.
318 const FunctionDecl *Callee;
319
Richard Smith180f4792011-11-10 06:34:14 +0000320 /// This - The binding for the this pointer in this call, if any.
321 const LValue *This;
322
Richard Smithd0dccea2011-10-28 22:34:42 +0000323 /// ParmBindings - Parameter bindings for this function call, indexed by
324 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000325 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000326
Richard Smithbd552ef2011-10-31 05:52:43 +0000327 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
328 typedef MapTy::const_iterator temp_iterator;
329 /// Temporaries - Temporary lvalues materialized within this stack frame.
330 MapTy Temporaries;
331
Richard Smith08d6e032011-12-16 19:06:07 +0000332 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
333 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000334 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000335 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000336 };
337
Richard Smithdd1f29b2011-12-12 09:28:41 +0000338 /// A partial diagnostic which we might know in advance that we are not going
339 /// to emit.
340 class OptionalDiagnostic {
341 PartialDiagnostic *Diag;
342
343 public:
344 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
345
346 template<typename T>
347 OptionalDiagnostic &operator<<(const T &v) {
348 if (Diag)
349 *Diag << v;
350 return *this;
351 }
Richard Smith789f9b62012-01-31 04:08:20 +0000352
353 OptionalDiagnostic &operator<<(const APSInt &I) {
354 if (Diag) {
355 llvm::SmallVector<char, 32> Buffer;
356 I.toString(Buffer);
357 *Diag << StringRef(Buffer.data(), Buffer.size());
358 }
359 return *this;
360 }
361
362 OptionalDiagnostic &operator<<(const APFloat &F) {
363 if (Diag) {
364 llvm::SmallVector<char, 32> Buffer;
365 F.toString(Buffer);
366 *Diag << StringRef(Buffer.data(), Buffer.size());
367 }
368 return *this;
369 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000370 };
371
Richard Smithbd552ef2011-10-31 05:52:43 +0000372 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000373 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000374
375 /// EvalStatus - Contains information about the evaluation.
376 Expr::EvalStatus &EvalStatus;
377
378 /// CurrentCall - The top of the constexpr call stack.
379 CallStackFrame *CurrentCall;
380
Richard Smithbd552ef2011-10-31 05:52:43 +0000381 /// CallStackDepth - The number of calls in the call stack right now.
382 unsigned CallStackDepth;
383
384 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
385 /// OpaqueValues - Values used as the common expression in a
386 /// BinaryConditionalOperator.
387 MapTy OpaqueValues;
388
389 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000390 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000391 CallStackFrame BottomFrame;
392
Richard Smith180f4792011-11-10 06:34:14 +0000393 /// EvaluatingDecl - This is the declaration whose initializer is being
394 /// evaluated, if any.
395 const VarDecl *EvaluatingDecl;
396
397 /// EvaluatingDeclValue - This is the value being constructed for the
398 /// declaration whose initializer is being evaluated, if any.
399 APValue *EvaluatingDeclValue;
400
Richard Smithc1c5f272011-12-13 06:39:58 +0000401 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
402 /// notes attached to it will also be stored, otherwise they will not be.
403 bool HasActiveDiagnostic;
404
Richard Smith745f5142012-01-27 01:14:48 +0000405 /// CheckingPotentialConstantExpression - Are we checking whether the
406 /// expression is a potential constant expression? If so, some diagnostics
407 /// are suppressed.
408 bool CheckingPotentialConstantExpression;
409
Richard Smithbd552ef2011-10-31 05:52:43 +0000410
411 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000412 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith08d6e032011-12-16 19:06:07 +0000413 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000414 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
415 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000416
Richard Smithbd552ef2011-10-31 05:52:43 +0000417 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
418 MapTy::const_iterator i = OpaqueValues.find(e);
419 if (i == OpaqueValues.end()) return 0;
420 return &i->second;
421 }
422
Richard Smith180f4792011-11-10 06:34:14 +0000423 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
424 EvaluatingDecl = VD;
425 EvaluatingDeclValue = &Value;
426 }
427
Richard Smithc18c4232011-11-21 19:36:32 +0000428 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
429
Richard Smithc1c5f272011-12-13 06:39:58 +0000430 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000431 // Don't perform any constexpr calls (other than the call we're checking)
432 // when checking a potential constant expression.
433 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
434 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +0000435 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
436 return true;
437 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
438 << getLangOpts().ConstexprCallDepth;
439 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000440 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000441
Richard Smithc1c5f272011-12-13 06:39:58 +0000442 private:
443 /// Add a diagnostic to the diagnostics list.
444 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
445 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
446 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
447 return EvalStatus.Diag->back().second;
448 }
449
Richard Smith08d6e032011-12-16 19:06:07 +0000450 /// Add notes containing a call stack to the current point of evaluation.
451 void addCallStack(unsigned Limit);
452
Richard Smithc1c5f272011-12-13 06:39:58 +0000453 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000454 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000455 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
456 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000457 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000458 // If we have a prior diagnostic, it will be noting that the expression
459 // isn't a constant expression. This diagnostic is more important.
460 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000461 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000462 unsigned CallStackNotes = CallStackDepth - 1;
463 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
464 if (Limit)
465 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000466 if (CheckingPotentialConstantExpression)
467 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000468
Richard Smithc1c5f272011-12-13 06:39:58 +0000469 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000470 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000471 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
472 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000473 if (!CheckingPotentialConstantExpression)
474 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000475 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000476 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000477 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000478 return OptionalDiagnostic();
479 }
480
481 /// Diagnose that the evaluation does not produce a C++11 core constant
482 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000483 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
484 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000485 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000486 // Don't override a previous diagnostic.
487 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
488 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000489 return Diag(Loc, DiagId, ExtraNotes);
490 }
491
492 /// Add a note to a prior diagnostic.
493 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
494 if (!HasActiveDiagnostic)
495 return OptionalDiagnostic();
496 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000497 }
Richard Smith099e7f62011-12-19 06:19:21 +0000498
499 /// Add a stack of notes to a prior diagnostic.
500 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
501 if (HasActiveDiagnostic) {
502 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
503 Diags.begin(), Diags.end());
504 }
505 }
Richard Smith745f5142012-01-27 01:14:48 +0000506
507 /// Should we continue evaluation as much as possible after encountering a
508 /// construct which can't be folded?
509 bool keepEvaluatingAfterFailure() {
510 return CheckingPotentialConstantExpression && EvalStatus.Diag->empty();
511 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000512 };
Richard Smith08d6e032011-12-16 19:06:07 +0000513}
Richard Smithbd552ef2011-10-31 05:52:43 +0000514
Richard Smithb4e85ed2012-01-06 16:39:00 +0000515bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
516 CheckSubobjectKind CSK) {
517 if (Invalid)
518 return false;
519 if (isOnePastTheEnd()) {
520 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
521 << CSK;
522 setInvalid();
523 return false;
524 }
525 return true;
526}
527
528void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
529 const Expr *E, uint64_t N) {
530 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
531 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
532 << static_cast<int>(N) << /*array*/ 0
533 << static_cast<unsigned>(MostDerivedArraySize);
534 else
535 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
536 << static_cast<int>(N) << /*non-array*/ 1;
537 setInvalid();
538}
539
Richard Smith08d6e032011-12-16 19:06:07 +0000540CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
541 const FunctionDecl *Callee, const LValue *This,
542 const CCValue *Arguments)
543 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
544 This(This), Arguments(Arguments) {
545 Info.CurrentCall = this;
546 ++Info.CallStackDepth;
547}
548
549CallStackFrame::~CallStackFrame() {
550 assert(Info.CurrentCall == this && "calls retired out of order");
551 --Info.CallStackDepth;
552 Info.CurrentCall = Caller;
553}
554
555/// Produce a string describing the given constexpr call.
556static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
557 unsigned ArgIndex = 0;
558 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
559 !isa<CXXConstructorDecl>(Frame->Callee);
560
561 if (!IsMemberCall)
562 Out << *Frame->Callee << '(';
563
564 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
565 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000566 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000567 Out << ", ";
568
569 const ParmVarDecl *Param = *I;
570 const CCValue &Arg = Frame->Arguments[ArgIndex];
571 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
572 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
573 else {
574 // Deliberately slice off the frame to form an APValue we can print.
575 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
576 Arg.getLValueDesignator().Entries,
Richard Smithb4e85ed2012-01-06 16:39:00 +0000577 Arg.getLValueDesignator().IsOnePastTheEnd);
Richard Smith08d6e032011-12-16 19:06:07 +0000578 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
579 }
580
581 if (ArgIndex == 0 && IsMemberCall)
582 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000583 }
584
Richard Smith08d6e032011-12-16 19:06:07 +0000585 Out << ')';
586}
587
588void EvalInfo::addCallStack(unsigned Limit) {
589 // Determine which calls to skip, if any.
590 unsigned ActiveCalls = CallStackDepth - 1;
591 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
592 if (Limit && Limit < ActiveCalls) {
593 SkipStart = Limit / 2 + Limit % 2;
594 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000595 }
596
Richard Smith08d6e032011-12-16 19:06:07 +0000597 // Walk the call stack and add the diagnostics.
598 unsigned CallIdx = 0;
599 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
600 Frame = Frame->Caller, ++CallIdx) {
601 // Skip this call?
602 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
603 if (CallIdx == SkipStart) {
604 // Note that we're skipping calls.
605 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
606 << unsigned(ActiveCalls - Limit);
607 }
608 continue;
609 }
610
611 llvm::SmallVector<char, 128> Buffer;
612 llvm::raw_svector_ostream Out(Buffer);
613 describeCall(Frame, Out);
614 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
615 }
616}
617
618namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000619 struct ComplexValue {
620 private:
621 bool IsInt;
622
623 public:
624 APSInt IntReal, IntImag;
625 APFloat FloatReal, FloatImag;
626
627 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
628
629 void makeComplexFloat() { IsInt = false; }
630 bool isComplexFloat() const { return !IsInt; }
631 APFloat &getComplexFloatReal() { return FloatReal; }
632 APFloat &getComplexFloatImag() { return FloatImag; }
633
634 void makeComplexInt() { IsInt = true; }
635 bool isComplexInt() const { return IsInt; }
636 APSInt &getComplexIntReal() { return IntReal; }
637 APSInt &getComplexIntImag() { return IntImag; }
638
Richard Smith47a1eed2011-10-29 20:57:55 +0000639 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000640 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000641 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000642 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000643 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000644 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000645 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000646 assert(v.isComplexFloat() || v.isComplexInt());
647 if (v.isComplexFloat()) {
648 makeComplexFloat();
649 FloatReal = v.getComplexFloatReal();
650 FloatImag = v.getComplexFloatImag();
651 } else {
652 makeComplexInt();
653 IntReal = v.getComplexIntReal();
654 IntImag = v.getComplexIntImag();
655 }
656 }
John McCallf4cf1a12010-05-07 17:22:02 +0000657 };
John McCallefdb83e2010-05-07 21:00:08 +0000658
659 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000660 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000661 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000662 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000663 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000664
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000665 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000666 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000667 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000668 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000669 SubobjectDesignator &getLValueDesignator() { return Designator; }
670 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000671
Richard Smith47a1eed2011-10-29 20:57:55 +0000672 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000673 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000674 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000675 void setFrom(const CCValue &V) {
676 assert(V.isLValue());
677 Base = V.getLValueBase();
678 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000679 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000680 Designator = V.getLValueDesignator();
681 }
682
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000683 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
684 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000685 Offset = CharUnits::Zero();
686 Frame = F;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000687 Designator = SubobjectDesignator(getType(B));
688 }
689
690 // Check that this LValue is not based on a null pointer. If it is, produce
691 // a diagnostic and mark the designator as invalid.
692 bool checkNullPointer(EvalInfo &Info, const Expr *E,
693 CheckSubobjectKind CSK) {
694 if (Designator.Invalid)
695 return false;
696 if (!Base) {
697 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
698 << CSK;
699 Designator.setInvalid();
700 return false;
701 }
702 return true;
703 }
704
705 // Check this LValue refers to an object. If not, set the designator to be
706 // invalid and emit a diagnostic.
707 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
708 return checkNullPointer(Info, E, CSK) &&
709 Designator.checkSubobject(Info, E, CSK);
710 }
711
712 void addDecl(EvalInfo &Info, const Expr *E,
713 const Decl *D, bool Virtual = false) {
714 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
715 Designator.addDeclUnchecked(D, Virtual);
716 }
717 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
718 checkSubobject(Info, E, CSK_ArrayToPointer);
719 Designator.addArrayUnchecked(CAT);
720 }
721 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
722 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
723 return;
724 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000725 }
John McCallefdb83e2010-05-07 21:00:08 +0000726 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000727
728 struct MemberPtr {
729 MemberPtr() {}
730 explicit MemberPtr(const ValueDecl *Decl) :
731 DeclAndIsDerivedMember(Decl, false), Path() {}
732
733 /// The member or (direct or indirect) field referred to by this member
734 /// pointer, or 0 if this is a null member pointer.
735 const ValueDecl *getDecl() const {
736 return DeclAndIsDerivedMember.getPointer();
737 }
738 /// Is this actually a member of some type derived from the relevant class?
739 bool isDerivedMember() const {
740 return DeclAndIsDerivedMember.getInt();
741 }
742 /// Get the class which the declaration actually lives in.
743 const CXXRecordDecl *getContainingRecord() const {
744 return cast<CXXRecordDecl>(
745 DeclAndIsDerivedMember.getPointer()->getDeclContext());
746 }
747
748 void moveInto(CCValue &V) const {
749 V = CCValue(getDecl(), isDerivedMember(), Path);
750 }
751 void setFrom(const CCValue &V) {
752 assert(V.isMemberPointer());
753 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
754 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
755 Path.clear();
756 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
757 Path.insert(Path.end(), P.begin(), P.end());
758 }
759
760 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
761 /// whether the member is a member of some class derived from the class type
762 /// of the member pointer.
763 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
764 /// Path - The path of base/derived classes from the member declaration's
765 /// class (exclusive) to the class type of the member pointer (inclusive).
766 SmallVector<const CXXRecordDecl*, 4> Path;
767
768 /// Perform a cast towards the class of the Decl (either up or down the
769 /// hierarchy).
770 bool castBack(const CXXRecordDecl *Class) {
771 assert(!Path.empty());
772 const CXXRecordDecl *Expected;
773 if (Path.size() >= 2)
774 Expected = Path[Path.size() - 2];
775 else
776 Expected = getContainingRecord();
777 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
778 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
779 // if B does not contain the original member and is not a base or
780 // derived class of the class containing the original member, the result
781 // of the cast is undefined.
782 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
783 // (D::*). We consider that to be a language defect.
784 return false;
785 }
786 Path.pop_back();
787 return true;
788 }
789 /// Perform a base-to-derived member pointer cast.
790 bool castToDerived(const CXXRecordDecl *Derived) {
791 if (!getDecl())
792 return true;
793 if (!isDerivedMember()) {
794 Path.push_back(Derived);
795 return true;
796 }
797 if (!castBack(Derived))
798 return false;
799 if (Path.empty())
800 DeclAndIsDerivedMember.setInt(false);
801 return true;
802 }
803 /// Perform a derived-to-base member pointer cast.
804 bool castToBase(const CXXRecordDecl *Base) {
805 if (!getDecl())
806 return true;
807 if (Path.empty())
808 DeclAndIsDerivedMember.setInt(true);
809 if (isDerivedMember()) {
810 Path.push_back(Base);
811 return true;
812 }
813 return castBack(Base);
814 }
815 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000816
Richard Smithb02e4622012-02-01 01:42:44 +0000817 /// Compare two member pointers, which are assumed to be of the same type.
818 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
819 if (!LHS.getDecl() || !RHS.getDecl())
820 return !LHS.getDecl() && !RHS.getDecl();
821 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
822 return false;
823 return LHS.Path == RHS.Path;
824 }
825
Richard Smithc1c5f272011-12-13 06:39:58 +0000826 /// Kinds of constant expression checking, for diagnostics.
827 enum CheckConstantExpressionKind {
828 CCEK_Constant, ///< A normal constant.
829 CCEK_ReturnValue, ///< A constexpr function return value.
830 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
831 };
John McCallf4cf1a12010-05-07 17:22:02 +0000832}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000833
Richard Smith47a1eed2011-10-29 20:57:55 +0000834static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000835static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000836 const LValue &This, const Expr *E,
837 CheckConstantExpressionKind CCEK
838 = CCEK_Constant);
John McCallefdb83e2010-05-07 21:00:08 +0000839static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
840static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000841static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
842 EvalInfo &Info);
843static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000844static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000845static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000846 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000847static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000848static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000849
850//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000851// Misc utilities
852//===----------------------------------------------------------------------===//
853
Richard Smith180f4792011-11-10 06:34:14 +0000854/// Should this call expression be treated as a string literal?
855static bool IsStringLiteralCall(const CallExpr *E) {
856 unsigned Builtin = E->isBuiltinCall();
857 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
858 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
859}
860
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000861static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000862 // C++11 [expr.const]p3 An address constant expression is a prvalue core
863 // constant expression of pointer type that evaluates to...
864
865 // ... a null pointer value, or a prvalue core constant expression of type
866 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000867 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000868
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000869 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
870 // ... the address of an object with static storage duration,
871 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
872 return VD->hasGlobalStorage();
873 // ... the address of a function,
874 return isa<FunctionDecl>(D);
875 }
876
877 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000878 switch (E->getStmtClass()) {
879 default:
880 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000881 case Expr::CompoundLiteralExprClass:
882 return cast<CompoundLiteralExpr>(E)->isFileScope();
883 // A string literal has static storage duration.
884 case Expr::StringLiteralClass:
885 case Expr::PredefinedExprClass:
886 case Expr::ObjCStringLiteralClass:
887 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000888 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000889 return true;
890 case Expr::CallExprClass:
891 return IsStringLiteralCall(cast<CallExpr>(E));
892 // For GCC compatibility, &&label has static storage duration.
893 case Expr::AddrLabelExprClass:
894 return true;
895 // A Block literal expression may be used as the initialization value for
896 // Block variables at global or local static scope.
897 case Expr::BlockExprClass:
898 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000899 case Expr::ImplicitValueInitExprClass:
900 // FIXME:
901 // We can never form an lvalue with an implicit value initialization as its
902 // base through expression evaluation, so these only appear in one case: the
903 // implicit variable declaration we invent when checking whether a constexpr
904 // constructor can produce a constant expression. We must assume that such
905 // an expression might be a global lvalue.
906 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000907 }
John McCall42c8f872010-05-10 23:27:23 +0000908}
909
Richard Smith9a17a682011-11-07 05:07:52 +0000910/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000911/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000912/// either LValue or CCValue. Return true if we can fold this expression,
913/// whether or not it's a constant expression.
Richard Smith9a17a682011-11-07 05:07:52 +0000914template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000915static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000916 const T &LVal, APValue &Value,
917 CheckConstantExpressionKind CCEK) {
918 APValue::LValueBase Base = LVal.getLValueBase();
919 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
920
921 if (!IsGlobalLValue(Base)) {
922 if (Info.getLangOpts().CPlusPlus0x) {
923 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
924 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
925 << E->isGLValue() << !Designator.Entries.empty()
926 << !!VD << CCEK << VD;
927 if (VD)
928 Info.Note(VD->getLocation(), diag::note_declared_at);
929 else
930 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
931 diag::note_constexpr_temporary_here);
932 } else {
Richard Smith7098cbd2011-12-21 05:04:46 +0000933 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000934 }
Richard Smith61e61622012-01-12 06:08:57 +0000935 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000936 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000937 }
Richard Smith9a17a682011-11-07 05:07:52 +0000938
Richard Smithb4e85ed2012-01-06 16:39:00 +0000939 bool IsReferenceType = E->isGLValue();
940
941 if (Designator.Invalid) {
Richard Smith61e61622012-01-12 06:08:57 +0000942 // This is not a core constant expression. An appropriate diagnostic will
943 // have already been produced.
Richard Smith9a17a682011-11-07 05:07:52 +0000944 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
945 APValue::NoLValuePath());
946 return true;
947 }
948
Richard Smithb4e85ed2012-01-06 16:39:00 +0000949 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
950 Designator.Entries, Designator.IsOnePastTheEnd);
951
952 // Allow address constant expressions to be past-the-end pointers. This is
953 // an extension: the standard requires them to point to an object.
954 if (!IsReferenceType)
955 return true;
956
957 // A reference constant expression must refer to an object.
958 if (!Base) {
959 // FIXME: diagnostic
960 Info.CCEDiag(E->getExprLoc());
Richard Smith61e61622012-01-12 06:08:57 +0000961 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000962 }
963
Richard Smithc1c5f272011-12-13 06:39:58 +0000964 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +0000965 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000966 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
967 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
968 << !Designator.Entries.empty() << !!VD << VD;
969 if (VD)
970 Info.Note(VD->getLocation(), diag::note_declared_at);
971 else
972 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
973 diag::note_constexpr_temporary_here);
Richard Smithc1c5f272011-12-13 06:39:58 +0000974 }
975
Richard Smith9a17a682011-11-07 05:07:52 +0000976 return true;
977}
978
Richard Smith51201882011-12-30 21:15:51 +0000979/// Check that this core constant expression is of literal type, and if not,
980/// produce an appropriate diagnostic.
981static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
982 if (!E->isRValue() || E->getType()->isLiteralType())
983 return true;
984
985 // Prvalue constant expressions must be of literal types.
986 if (Info.getLangOpts().CPlusPlus0x)
987 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
988 << E->getType();
989 else
990 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
991 return false;
992}
993
Richard Smith47a1eed2011-10-29 20:57:55 +0000994/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000995/// constant expression, and if it is, produce the corresponding constant value.
Richard Smith51201882011-12-30 21:15:51 +0000996/// If not, report an appropriate diagnostic. Does not check that the expression
997/// is of literal type.
Richard Smithf48fdb02011-12-09 22:58:01 +0000998static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000999 const CCValue &CCValue, APValue &Value,
1000 CheckConstantExpressionKind CCEK
1001 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +00001002 if (!CCValue.isLValue()) {
1003 Value = CCValue;
1004 return true;
1005 }
Richard Smithc1c5f272011-12-13 06:39:58 +00001006 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +00001007}
1008
Richard Smith9e36b532011-10-31 05:11:32 +00001009const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001010 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001011}
1012
1013static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001014 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +00001015}
1016
Richard Smith65ac5982011-11-01 21:06:14 +00001017static bool IsWeakLValue(const LValue &Value) {
1018 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001019 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001020}
1021
Richard Smithe24f5fc2011-11-17 22:56:20 +00001022static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001023 // A null base expression indicates a null pointer. These are always
1024 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001025 if (!Value.getLValueBase()) {
1026 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001027 return true;
1028 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001029
Richard Smithe24f5fc2011-11-17 22:56:20 +00001030 // We have a non-null base. These are generally known to be true, but if it's
1031 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001032 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001033 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001034 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001035}
1036
Richard Smith47a1eed2011-10-29 20:57:55 +00001037static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001038 switch (Val.getKind()) {
1039 case APValue::Uninitialized:
1040 return false;
1041 case APValue::Int:
1042 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001043 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001044 case APValue::Float:
1045 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001046 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001047 case APValue::ComplexInt:
1048 Result = Val.getComplexIntReal().getBoolValue() ||
1049 Val.getComplexIntImag().getBoolValue();
1050 return true;
1051 case APValue::ComplexFloat:
1052 Result = !Val.getComplexFloatReal().isZero() ||
1053 !Val.getComplexFloatImag().isZero();
1054 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001055 case APValue::LValue:
1056 return EvalPointerValueAsBool(Val, Result);
1057 case APValue::MemberPointer:
1058 Result = Val.getMemberPointerDecl();
1059 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001060 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001061 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001062 case APValue::Struct:
1063 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001064 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001065 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001066 }
1067
Richard Smithc49bd112011-10-28 17:51:58 +00001068 llvm_unreachable("unknown APValue kind");
1069}
1070
1071static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1072 EvalInfo &Info) {
1073 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001074 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001075 if (!Evaluate(Val, Info, E))
1076 return false;
1077 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001078}
1079
Richard Smithc1c5f272011-12-13 06:39:58 +00001080template<typename T>
1081static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1082 const T &SrcValue, QualType DestType) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001083 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001084 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001085 return false;
1086}
1087
1088static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1089 QualType SrcType, const APFloat &Value,
1090 QualType DestType, APSInt &Result) {
1091 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001092 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001093 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Richard Smithc1c5f272011-12-13 06:39:58 +00001095 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001096 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001097 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1098 & APFloat::opInvalidOp)
1099 return HandleOverflow(Info, E, Value, DestType);
1100 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001101}
1102
Richard Smithc1c5f272011-12-13 06:39:58 +00001103static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1104 QualType SrcType, QualType DestType,
1105 APFloat &Result) {
1106 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001107 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001108 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1109 APFloat::rmNearestTiesToEven, &ignored)
1110 & APFloat::opOverflow)
1111 return HandleOverflow(Info, E, Value, DestType);
1112 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001113}
1114
Richard Smithf72fccf2012-01-30 22:27:01 +00001115static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1116 QualType DestType, QualType SrcType,
1117 APSInt &Value) {
1118 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001119 APSInt Result = Value;
1120 // Figure out if this is a truncate, extend or noop cast.
1121 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001122 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001123 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001124 return Result;
1125}
1126
Richard Smithc1c5f272011-12-13 06:39:58 +00001127static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1128 QualType SrcType, const APSInt &Value,
1129 QualType DestType, APFloat &Result) {
1130 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1131 if (Result.convertFromAPInt(Value, Value.isSigned(),
1132 APFloat::rmNearestTiesToEven)
1133 & APFloat::opOverflow)
1134 return HandleOverflow(Info, E, Value, DestType);
1135 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001136}
1137
Eli Friedmane6a24e82011-12-22 03:51:45 +00001138static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1139 llvm::APInt &Res) {
1140 CCValue SVal;
1141 if (!Evaluate(SVal, Info, E))
1142 return false;
1143 if (SVal.isInt()) {
1144 Res = SVal.getInt();
1145 return true;
1146 }
1147 if (SVal.isFloat()) {
1148 Res = SVal.getFloat().bitcastToAPInt();
1149 return true;
1150 }
1151 if (SVal.isVector()) {
1152 QualType VecTy = E->getType();
1153 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1154 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1155 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1156 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1157 Res = llvm::APInt::getNullValue(VecSize);
1158 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1159 APValue &Elt = SVal.getVectorElt(i);
1160 llvm::APInt EltAsInt;
1161 if (Elt.isInt()) {
1162 EltAsInt = Elt.getInt();
1163 } else if (Elt.isFloat()) {
1164 EltAsInt = Elt.getFloat().bitcastToAPInt();
1165 } else {
1166 // Don't try to handle vectors of anything other than int or float
1167 // (not sure if it's possible to hit this case).
1168 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1169 return false;
1170 }
1171 unsigned BaseEltSize = EltAsInt.getBitWidth();
1172 if (BigEndian)
1173 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1174 else
1175 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1176 }
1177 return true;
1178 }
1179 // Give up if the input isn't an int, float, or vector. For example, we
1180 // reject "(v4i16)(intptr_t)&a".
1181 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1182 return false;
1183}
1184
Richard Smithb4e85ed2012-01-06 16:39:00 +00001185/// Cast an lvalue referring to a base subobject to a derived class, by
1186/// truncating the lvalue's path to the given length.
1187static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1188 const RecordDecl *TruncatedType,
1189 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001190 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001191
1192 // Check we actually point to a derived class object.
1193 if (TruncatedElements == D.Entries.size())
1194 return true;
1195 assert(TruncatedElements >= D.MostDerivedPathLength &&
1196 "not casting to a derived class");
1197 if (!Result.checkSubobject(Info, E, CSK_Derived))
1198 return false;
1199
1200 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001201 const RecordDecl *RD = TruncatedType;
1202 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001203 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1204 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001205 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001206 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001207 else
Richard Smith180f4792011-11-10 06:34:14 +00001208 Result.Offset -= Layout.getBaseClassOffset(Base);
1209 RD = Base;
1210 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001211 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001212 return true;
1213}
1214
Richard Smithb4e85ed2012-01-06 16:39:00 +00001215static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001216 const CXXRecordDecl *Derived,
1217 const CXXRecordDecl *Base,
1218 const ASTRecordLayout *RL = 0) {
1219 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1220 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001221 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001222}
1223
Richard Smithb4e85ed2012-01-06 16:39:00 +00001224static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001225 const CXXRecordDecl *DerivedDecl,
1226 const CXXBaseSpecifier *Base) {
1227 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1228
1229 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001230 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001231 return true;
1232 }
1233
Richard Smithb4e85ed2012-01-06 16:39:00 +00001234 SubobjectDesignator &D = Obj.Designator;
1235 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001236 return false;
1237
Richard Smithb4e85ed2012-01-06 16:39:00 +00001238 // Extract most-derived object and corresponding type.
1239 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1240 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1241 return false;
1242
1243 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001244 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1245 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001246 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001247 return true;
1248}
1249
1250/// Update LVal to refer to the given field, which must be a member of the type
1251/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001252static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001253 const FieldDecl *FD,
1254 const ASTRecordLayout *RL = 0) {
1255 if (!RL)
1256 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1257
1258 unsigned I = FD->getFieldIndex();
1259 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001260 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001261}
1262
Richard Smithd9b02e72012-01-25 22:15:11 +00001263/// Update LVal to refer to the given indirect field.
1264static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1265 LValue &LVal,
1266 const IndirectFieldDecl *IFD) {
1267 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1268 CE = IFD->chain_end(); C != CE; ++C)
1269 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1270}
1271
Richard Smith180f4792011-11-10 06:34:14 +00001272/// Get the size of the given type in char units.
1273static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1274 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1275 // extension.
1276 if (Type->isVoidType() || Type->isFunctionType()) {
1277 Size = CharUnits::One();
1278 return true;
1279 }
1280
1281 if (!Type->isConstantSizeType()) {
1282 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001283 // FIXME: Diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001284 return false;
1285 }
1286
1287 Size = Info.Ctx.getTypeSizeInChars(Type);
1288 return true;
1289}
1290
1291/// Update a pointer value to model pointer arithmetic.
1292/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001293/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001294/// \param LVal - The pointer value to be updated.
1295/// \param EltTy - The pointee type represented by LVal.
1296/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001297static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1298 LValue &LVal, QualType EltTy,
1299 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001300 CharUnits SizeOfPointee;
1301 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1302 return false;
1303
1304 // Compute the new offset in the appropriate width.
1305 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001306 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001307 return true;
1308}
1309
Richard Smith03f96112011-10-24 17:54:18 +00001310/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001311static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1312 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001313 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001314 // If this is a parameter to an active constexpr function call, perform
1315 // argument substitution.
1316 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001317 // Assume arguments of a potential constant expression are unknown
1318 // constant expressions.
1319 if (Info.CheckingPotentialConstantExpression)
1320 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001321 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001322 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001323 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001324 }
Richard Smith177dce72011-11-01 16:57:24 +00001325 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1326 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001327 }
Richard Smith03f96112011-10-24 17:54:18 +00001328
Richard Smith099e7f62011-12-19 06:19:21 +00001329 // Dig out the initializer, and use the declaration which it's attached to.
1330 const Expr *Init = VD->getAnyInitializer(VD);
1331 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001332 // If we're checking a potential constant expression, the variable could be
1333 // initialized later.
1334 if (!Info.CheckingPotentialConstantExpression)
1335 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001336 return false;
1337 }
1338
Richard Smith180f4792011-11-10 06:34:14 +00001339 // If we're currently evaluating the initializer of this declaration, use that
1340 // in-flight value.
1341 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001342 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1343 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001344 return !Result.isUninit();
1345 }
1346
Richard Smith65ac5982011-11-01 21:06:14 +00001347 // Never evaluate the initializer of a weak variable. We can't be sure that
1348 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001349 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001350 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001351 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001352 }
Richard Smith65ac5982011-11-01 21:06:14 +00001353
Richard Smith099e7f62011-12-19 06:19:21 +00001354 // Check that we can fold the initializer. In C++, we will have already done
1355 // this in the cases where it matters for conformance.
1356 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1357 if (!VD->evaluateValue(Notes)) {
1358 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1359 Notes.size() + 1) << VD;
1360 Info.Note(VD->getLocation(), diag::note_declared_at);
1361 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001362 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001363 } else if (!VD->checkInitIsICE()) {
1364 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1365 Notes.size() + 1) << VD;
1366 Info.Note(VD->getLocation(), diag::note_declared_at);
1367 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001368 }
Richard Smith03f96112011-10-24 17:54:18 +00001369
Richard Smithb4e85ed2012-01-06 16:39:00 +00001370 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001371 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001372}
1373
Richard Smithc49bd112011-10-28 17:51:58 +00001374static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001375 Qualifiers Quals = T.getQualifiers();
1376 return Quals.hasConst() && !Quals.hasVolatile();
1377}
1378
Richard Smith59efe262011-11-11 04:05:33 +00001379/// Get the base index of the given base class within an APValue representing
1380/// the given derived class.
1381static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1382 const CXXRecordDecl *Base) {
1383 Base = Base->getCanonicalDecl();
1384 unsigned Index = 0;
1385 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1386 E = Derived->bases_end(); I != E; ++I, ++Index) {
1387 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1388 return Index;
1389 }
1390
1391 llvm_unreachable("base class missing from derived class's bases list");
1392}
1393
Richard Smithcc5d4f62011-11-07 09:22:26 +00001394/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001395static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1396 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001397 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001398 if (Sub.Invalid)
1399 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001400 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001401 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001402 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001403 (unsigned)diag::note_constexpr_read_past_end :
1404 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001405 return false;
1406 }
Richard Smithf64699e2011-11-11 08:28:03 +00001407 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001408 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001409 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1410 // This object might be initialized later.
1411 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001412
1413 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1414 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001415 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001416 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001417 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001418 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001419 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001420 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001421 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001422 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001423 // Note, it should not be possible to form a pointer with a valid
1424 // designator which points more than one past the end of the array.
1425 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001426 (unsigned)diag::note_constexpr_read_past_end :
1427 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001428 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001429 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001430 if (O->getArrayInitializedElts() > Index)
1431 O = &O->getArrayInitializedElt(Index);
1432 else
1433 O = &O->getArrayFiller();
1434 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001435 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1436 // Next subobject is a class, struct or union field.
1437 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1438 if (RD->isUnion()) {
1439 const FieldDecl *UnionField = O->getUnionField();
1440 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001441 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001442 Info.Diag(E->getExprLoc(),
1443 diag::note_constexpr_read_inactive_union_member)
1444 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001445 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001446 }
Richard Smith180f4792011-11-10 06:34:14 +00001447 O = &O->getUnionValue();
1448 } else
1449 O = &O->getStructField(Field->getFieldIndex());
1450 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001451
1452 if (ObjType.isVolatileQualified()) {
1453 if (Info.getLangOpts().CPlusPlus) {
1454 // FIXME: Include a description of the path to the volatile subobject.
1455 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1456 << 2 << Field;
1457 Info.Note(Field->getLocation(), diag::note_declared_at);
1458 } else {
1459 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1460 }
1461 return false;
1462 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001463 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001464 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001465 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1466 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1467 O = &O->getStructBase(getBaseIndex(Derived, Base));
1468 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001469 }
Richard Smith180f4792011-11-10 06:34:14 +00001470
Richard Smithf48fdb02011-12-09 22:58:01 +00001471 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001472 if (!Info.CheckingPotentialConstantExpression)
1473 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001474 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001475 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001476 }
1477
Richard Smithb4e85ed2012-01-06 16:39:00 +00001478 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001479 return true;
1480}
1481
Richard Smith180f4792011-11-10 06:34:14 +00001482/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1483/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1484/// for looking up the glvalue referred to by an entity of reference type.
1485///
1486/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001487/// \param Conv - The expression for which we are performing the conversion.
1488/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001489/// \param Type - The type we expect this conversion to produce.
1490/// \param LVal - The glvalue on which we are attempting to perform this action.
1491/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001492static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1493 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001494 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001495 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1496 if (!Info.getLangOpts().CPlusPlus)
1497 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1498
Richard Smithb4e85ed2012-01-06 16:39:00 +00001499 if (LVal.Designator.Invalid)
1500 // A diagnostic will have already been produced.
1501 return false;
1502
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001503 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001504 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001505 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001506
Richard Smithf48fdb02011-12-09 22:58:01 +00001507 if (!LVal.Base) {
1508 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001509 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1510 return false;
1511 }
1512
1513 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1514 // is not a constant expression (even if the object is non-volatile). We also
1515 // apply this rule to C++98, in order to conform to the expected 'volatile'
1516 // semantics.
1517 if (Type.isVolatileQualified()) {
1518 if (Info.getLangOpts().CPlusPlus)
1519 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1520 else
1521 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001522 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001523 }
Richard Smithc49bd112011-10-28 17:51:58 +00001524
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001525 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001526 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1527 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001528 // expressions are constant expressions too. Inside constexpr functions,
1529 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001530 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001531 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001532 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001533 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001534 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001535 }
1536
Richard Smith7098cbd2011-12-21 05:04:46 +00001537 // DR1313: If the object is volatile-qualified but the glvalue was not,
1538 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001539 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001540 if (VT.isVolatileQualified()) {
1541 if (Info.getLangOpts().CPlusPlus) {
1542 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1543 Info.Note(VD->getLocation(), diag::note_declared_at);
1544 } else {
1545 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001546 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001547 return false;
1548 }
1549
1550 if (!isa<ParmVarDecl>(VD)) {
1551 if (VD->isConstexpr()) {
1552 // OK, we can read this variable.
1553 } else if (VT->isIntegralOrEnumerationType()) {
1554 if (!VT.isConstQualified()) {
1555 if (Info.getLangOpts().CPlusPlus) {
1556 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1557 Info.Note(VD->getLocation(), diag::note_declared_at);
1558 } else {
1559 Info.Diag(Loc);
1560 }
1561 return false;
1562 }
1563 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1564 // We support folding of const floating-point types, in order to make
1565 // static const data members of such types (supported as an extension)
1566 // more useful.
1567 if (Info.getLangOpts().CPlusPlus0x) {
1568 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1569 Info.Note(VD->getLocation(), diag::note_declared_at);
1570 } else {
1571 Info.CCEDiag(Loc);
1572 }
1573 } else {
1574 // FIXME: Allow folding of values of any literal type in all languages.
1575 if (Info.getLangOpts().CPlusPlus0x) {
1576 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1577 Info.Note(VD->getLocation(), diag::note_declared_at);
1578 } else {
1579 Info.Diag(Loc);
1580 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001581 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001582 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001583 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001584
Richard Smithf48fdb02011-12-09 22:58:01 +00001585 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001586 return false;
1587
Richard Smith47a1eed2011-10-29 20:57:55 +00001588 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001589 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001590
1591 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1592 // conversion. This happens when the declaration and the lvalue should be
1593 // considered synonymous, for instance when initializing an array of char
1594 // from a string literal. Continue as if the initializer lvalue was the
1595 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001596 assert(RVal.getLValueOffset().isZero() &&
1597 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001598 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001599 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001600 }
1601
Richard Smith7098cbd2011-12-21 05:04:46 +00001602 // Volatile temporary objects cannot be read in constant expressions.
1603 if (Base->getType().isVolatileQualified()) {
1604 if (Info.getLangOpts().CPlusPlus) {
1605 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1606 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1607 } else {
1608 Info.Diag(Loc);
1609 }
1610 return false;
1611 }
1612
Richard Smith0a3bdb62011-11-04 02:25:55 +00001613 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1614 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1615 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001616 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001617 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001618 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001619 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001620
1621 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001622 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001623 const ConstantArrayType *CAT =
1624 Info.Ctx.getAsConstantArrayType(S->getType());
1625 if (Index >= CAT->getSize().getZExtValue()) {
1626 // Note, it should not be possible to form a pointer which points more
1627 // than one past the end of the array without producing a prior const expr
1628 // diagnostic.
1629 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001630 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001631 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001632 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1633 Type->isUnsignedIntegerType());
1634 if (Index < S->getLength())
1635 Value = S->getCodeUnit(Index);
1636 RVal = CCValue(Value);
1637 return true;
1638 }
1639
Richard Smithcc5d4f62011-11-07 09:22:26 +00001640 if (Frame) {
1641 // If this is a temporary expression with a nontrivial initializer, grab the
1642 // value from the relevant stack frame.
1643 RVal = Frame->Temporaries[Base];
1644 } else if (const CompoundLiteralExpr *CLE
1645 = dyn_cast<CompoundLiteralExpr>(Base)) {
1646 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1647 // initializer until now for such expressions. Such an expression can't be
1648 // an ICE in C, so this only matters for fold.
1649 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1650 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1651 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001652 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001653 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001654 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001655 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001656
Richard Smithf48fdb02011-12-09 22:58:01 +00001657 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1658 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001659}
1660
Richard Smith59efe262011-11-11 04:05:33 +00001661/// Build an lvalue for the object argument of a member function call.
1662static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1663 LValue &This) {
1664 if (Object->getType()->isPointerType())
1665 return EvaluatePointer(Object, This, Info);
1666
1667 if (Object->isGLValue())
1668 return EvaluateLValue(Object, This, Info);
1669
Richard Smithe24f5fc2011-11-17 22:56:20 +00001670 if (Object->getType()->isLiteralType())
1671 return EvaluateTemporary(Object, This, Info);
1672
1673 return false;
1674}
1675
1676/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1677/// lvalue referring to the result.
1678///
1679/// \param Info - Information about the ongoing evaluation.
1680/// \param BO - The member pointer access operation.
1681/// \param LV - Filled in with a reference to the resulting object.
1682/// \param IncludeMember - Specifies whether the member itself is included in
1683/// the resulting LValue subobject designator. This is not possible when
1684/// creating a bound member function.
1685/// \return The field or method declaration to which the member pointer refers,
1686/// or 0 if evaluation fails.
1687static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1688 const BinaryOperator *BO,
1689 LValue &LV,
1690 bool IncludeMember = true) {
1691 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1692
Richard Smith745f5142012-01-27 01:14:48 +00001693 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1694 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001695 return 0;
1696
1697 MemberPtr MemPtr;
1698 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1699 return 0;
1700
1701 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1702 // member value, the behavior is undefined.
1703 if (!MemPtr.getDecl())
1704 return 0;
1705
Richard Smith745f5142012-01-27 01:14:48 +00001706 if (!EvalObjOK)
1707 return 0;
1708
Richard Smithe24f5fc2011-11-17 22:56:20 +00001709 if (MemPtr.isDerivedMember()) {
1710 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001711 // The end of the derived-to-base path for the base object must match the
1712 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001713 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001714 LV.Designator.Entries.size())
1715 return 0;
1716 unsigned PathLengthToMember =
1717 LV.Designator.Entries.size() - MemPtr.Path.size();
1718 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1719 const CXXRecordDecl *LVDecl = getAsBaseClass(
1720 LV.Designator.Entries[PathLengthToMember + I]);
1721 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1722 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1723 return 0;
1724 }
1725
1726 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001727 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1728 PathLengthToMember))
1729 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001730 } else if (!MemPtr.Path.empty()) {
1731 // Extend the LValue path with the member pointer's path.
1732 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1733 MemPtr.Path.size() + IncludeMember);
1734
1735 // Walk down to the appropriate base class.
1736 QualType LVType = BO->getLHS()->getType();
1737 if (const PointerType *PT = LVType->getAs<PointerType>())
1738 LVType = PT->getPointeeType();
1739 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1740 assert(RD && "member pointer access on non-class-type expression");
1741 // The first class in the path is that of the lvalue.
1742 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1743 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001744 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001745 RD = Base;
1746 }
1747 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001748 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001749 }
1750
1751 // Add the member. Note that we cannot build bound member functions here.
1752 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001753 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1754 HandleLValueMember(Info, BO, LV, FD);
1755 else if (const IndirectFieldDecl *IFD =
1756 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1757 HandleLValueIndirectMember(Info, BO, LV, IFD);
1758 else
1759 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001760 }
1761
1762 return MemPtr.getDecl();
1763}
1764
1765/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1766/// the provided lvalue, which currently refers to the base object.
1767static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1768 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001769 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001770 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001771 return false;
1772
Richard Smithb4e85ed2012-01-06 16:39:00 +00001773 QualType TargetQT = E->getType();
1774 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1775 TargetQT = PT->getPointeeType();
1776
1777 // Check this cast lands within the final derived-to-base subobject path.
1778 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1779 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1780 << D.MostDerivedType << TargetQT;
1781 return false;
1782 }
1783
Richard Smithe24f5fc2011-11-17 22:56:20 +00001784 // Check the type of the final cast. We don't need to check the path,
1785 // since a cast can only be formed if the path is unique.
1786 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001787 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1788 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001789 if (NewEntriesSize == D.MostDerivedPathLength)
1790 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1791 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001792 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001793 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1794 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1795 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001796 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001797 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001798
1799 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001800 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001801}
1802
Mike Stumpc4c90452009-10-27 22:09:17 +00001803namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001804enum EvalStmtResult {
1805 /// Evaluation failed.
1806 ESR_Failed,
1807 /// Hit a 'return' statement.
1808 ESR_Returned,
1809 /// Evaluation succeeded.
1810 ESR_Succeeded
1811};
1812}
1813
1814// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001815static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001816 const Stmt *S) {
1817 switch (S->getStmtClass()) {
1818 default:
1819 return ESR_Failed;
1820
1821 case Stmt::NullStmtClass:
1822 case Stmt::DeclStmtClass:
1823 return ESR_Succeeded;
1824
Richard Smithc1c5f272011-12-13 06:39:58 +00001825 case Stmt::ReturnStmtClass: {
1826 CCValue CCResult;
1827 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1828 if (!Evaluate(CCResult, Info, RetExpr) ||
1829 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1830 CCEK_ReturnValue))
1831 return ESR_Failed;
1832 return ESR_Returned;
1833 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001834
1835 case Stmt::CompoundStmtClass: {
1836 const CompoundStmt *CS = cast<CompoundStmt>(S);
1837 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1838 BE = CS->body_end(); BI != BE; ++BI) {
1839 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1840 if (ESR != ESR_Succeeded)
1841 return ESR;
1842 }
1843 return ESR_Succeeded;
1844 }
1845 }
1846}
1847
Richard Smith61802452011-12-22 02:22:31 +00001848/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1849/// default constructor. If so, we'll fold it whether or not it's marked as
1850/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1851/// so we need special handling.
1852static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00001853 const CXXConstructorDecl *CD,
1854 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001855 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1856 return false;
1857
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001858 // Value-initialization does not call a trivial default constructor, so such a
1859 // call is a core constant expression whether or not the constructor is
1860 // constexpr.
1861 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001862 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001863 // FIXME: If DiagDecl is an implicitly-declared special member function,
1864 // we should be much more explicit about why it's not constexpr.
1865 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1866 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1867 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00001868 } else {
1869 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1870 }
1871 }
1872 return true;
1873}
1874
Richard Smithc1c5f272011-12-13 06:39:58 +00001875/// CheckConstexprFunction - Check that a function can be called in a constant
1876/// expression.
1877static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1878 const FunctionDecl *Declaration,
1879 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00001880 // Potential constant expressions can contain calls to declared, but not yet
1881 // defined, constexpr functions.
1882 if (Info.CheckingPotentialConstantExpression && !Definition &&
1883 Declaration->isConstexpr())
1884 return false;
1885
Richard Smithc1c5f272011-12-13 06:39:58 +00001886 // Can we evaluate this function call?
1887 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1888 return true;
1889
1890 if (Info.getLangOpts().CPlusPlus0x) {
1891 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001892 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1893 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001894 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1895 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1896 << DiagDecl;
1897 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1898 } else {
1899 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1900 }
1901 return false;
1902}
1903
Richard Smith180f4792011-11-10 06:34:14 +00001904namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001905typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001906}
1907
1908/// EvaluateArgs - Evaluate the arguments to a function call.
1909static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1910 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00001911 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001912 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00001913 I != E; ++I) {
1914 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
1915 // If we're checking for a potential constant expression, evaluate all
1916 // initializers even if some of them fail.
1917 if (!Info.keepEvaluatingAfterFailure())
1918 return false;
1919 Success = false;
1920 }
1921 }
1922 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00001923}
1924
Richard Smithd0dccea2011-10-28 22:34:42 +00001925/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00001926static bool HandleFunctionCall(SourceLocation CallLoc,
1927 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00001928 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001929 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00001930 ArgVector ArgValues(Args.size());
1931 if (!EvaluateArgs(Args, ArgValues, Info))
1932 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001933
Richard Smith745f5142012-01-27 01:14:48 +00001934 if (!Info.CheckCallLimit(CallLoc))
1935 return false;
1936
1937 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001938 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1939}
1940
Richard Smith180f4792011-11-10 06:34:14 +00001941/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00001942static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001943 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001944 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00001945 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00001946 ArgVector ArgValues(Args.size());
1947 if (!EvaluateArgs(Args, ArgValues, Info))
1948 return false;
1949
Richard Smith745f5142012-01-27 01:14:48 +00001950 if (!Info.CheckCallLimit(CallLoc))
1951 return false;
1952
1953 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00001954
1955 // If it's a delegating constructor, just delegate.
1956 if (Definition->isDelegatingConstructor()) {
1957 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1958 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1959 }
1960
Richard Smith610a60c2012-01-10 04:32:03 +00001961 // For a trivial copy or move constructor, perform an APValue copy. This is
1962 // essential for unions, where the operations performed by the constructor
1963 // cannot be represented by ctor-initializers.
Richard Smith180f4792011-11-10 06:34:14 +00001964 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith610a60c2012-01-10 04:32:03 +00001965 if (Definition->isDefaulted() &&
1966 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
1967 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
1968 LValue RHS;
1969 RHS.setFrom(ArgValues[0]);
1970 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00001971 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
1972 RHS, Value))
1973 return false;
1974 assert((Value.isStruct() || Value.isUnion()) &&
1975 "trivial copy/move from non-class type?");
1976 // Any CCValue of class type must already be a constant expression.
1977 Result = Value;
1978 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00001979 }
1980
1981 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00001982 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00001983 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1984 std::distance(RD->field_begin(), RD->field_end()));
1985
1986 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1987
Richard Smith745f5142012-01-27 01:14:48 +00001988 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001989 unsigned BasesSeen = 0;
1990#ifndef NDEBUG
1991 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1992#endif
1993 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1994 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00001995 LValue Subobject = This;
1996 APValue *Value = &Result;
1997
1998 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00001999 if ((*I)->isBaseInitializer()) {
2000 QualType BaseType((*I)->getBaseClass(), 0);
2001#ifndef NDEBUG
2002 // Non-virtual base classes are initialized in the order in the class
2003 // definition. We cannot have a virtual base class for a literal type.
2004 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2005 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2006 "base class initializers not in expected order");
2007 ++BaseIt;
2008#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002009 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002010 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002011 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002012 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002013 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002014 if (RD->isUnion()) {
2015 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002016 Value = &Result.getUnionValue();
2017 } else {
2018 Value = &Result.getStructField(FD->getFieldIndex());
2019 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002020 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002021 // Walk the indirect field decl's chain to find the object to initialize,
2022 // and make sure we've initialized every step along it.
2023 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2024 CE = IFD->chain_end();
2025 C != CE; ++C) {
2026 FieldDecl *FD = cast<FieldDecl>(*C);
2027 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2028 // Switch the union field if it differs. This happens if we had
2029 // preceding zero-initialization, and we're now initializing a union
2030 // subobject other than the first.
2031 // FIXME: In this case, the values of the other subobjects are
2032 // specified, since zero-initialization sets all padding bits to zero.
2033 if (Value->isUninit() ||
2034 (Value->isUnion() && Value->getUnionField() != FD)) {
2035 if (CD->isUnion())
2036 *Value = APValue(FD);
2037 else
2038 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2039 std::distance(CD->field_begin(), CD->field_end()));
2040 }
Richard Smith745f5142012-01-27 01:14:48 +00002041 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002042 if (CD->isUnion())
2043 Value = &Value->getUnionValue();
2044 else
2045 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002046 }
Richard Smith180f4792011-11-10 06:34:14 +00002047 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002048 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002049 }
Richard Smith745f5142012-01-27 01:14:48 +00002050
2051 if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
2052 (*I)->isBaseInitializer()
2053 ? CCEK_Constant : CCEK_MemberInit)) {
2054 // If we're checking for a potential constant expression, evaluate all
2055 // initializers even if some of them fail.
2056 if (!Info.keepEvaluatingAfterFailure())
2057 return false;
2058 Success = false;
2059 }
Richard Smith180f4792011-11-10 06:34:14 +00002060 }
2061
Richard Smith745f5142012-01-27 01:14:48 +00002062 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002063}
2064
Richard Smithd0dccea2011-10-28 22:34:42 +00002065namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002066class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002067 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002068 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002069public:
2070
Richard Smith1e12c592011-10-16 21:26:27 +00002071 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002072
2073 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002074 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002075 return true;
2076 }
2077
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002078 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2079 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002080 return Visit(E->getResultExpr());
2081 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002082 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002083 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002084 return true;
2085 return false;
2086 }
John McCallf85e1932011-06-15 23:02:42 +00002087 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002088 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002089 return true;
2090 return false;
2091 }
2092 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002093 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002094 return true;
2095 return false;
2096 }
2097
Mike Stumpc4c90452009-10-27 22:09:17 +00002098 // We don't want to evaluate BlockExprs multiple times, as they generate
2099 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002100 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2101 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2102 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002103 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002104 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2105 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2106 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2107 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2108 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2109 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002110 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002111 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002112 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002113 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002114 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002115 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2116 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2117 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2118 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002119 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002120 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2121 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2122 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2123 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2124 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002125 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002126 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002127 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002128 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002129 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002130
2131 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002132 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002133 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2134 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002135 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002136 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002137 return false;
2138 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002139
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002140 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002141};
2142
John McCall56ca35d2011-02-17 10:25:35 +00002143class OpaqueValueEvaluation {
2144 EvalInfo &info;
2145 OpaqueValueExpr *opaqueValue;
2146
2147public:
2148 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2149 Expr *value)
2150 : info(info), opaqueValue(opaqueValue) {
2151
2152 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002153 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002154 this->opaqueValue = 0;
2155 return;
2156 }
John McCall56ca35d2011-02-17 10:25:35 +00002157 }
2158
2159 bool hasError() const { return opaqueValue == 0; }
2160
2161 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00002162 // FIXME: This will not work for recursive constexpr functions using opaque
2163 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00002164 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2165 }
2166};
2167
Mike Stumpc4c90452009-10-27 22:09:17 +00002168} // end anonymous namespace
2169
Eli Friedman4efaa272008-11-12 09:44:48 +00002170//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002171// Generic Evaluation
2172//===----------------------------------------------------------------------===//
2173namespace {
2174
Richard Smithf48fdb02011-12-09 22:58:01 +00002175// FIXME: RetTy is always bool. Remove it.
2176template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002177class ExprEvaluatorBase
2178 : public ConstStmtVisitor<Derived, RetTy> {
2179private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002180 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002181 return static_cast<Derived*>(this)->Success(V, E);
2182 }
Richard Smith51201882011-12-30 21:15:51 +00002183 RetTy DerivedZeroInitialization(const Expr *E) {
2184 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002185 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002186
2187protected:
2188 EvalInfo &Info;
2189 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2190 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2191
Richard Smithdd1f29b2011-12-12 09:28:41 +00002192 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002193 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002194 }
2195
2196 /// Report an evaluation error. This should only be called when an error is
2197 /// first discovered. When propagating an error, just return false.
2198 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002199 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002200 return false;
2201 }
2202 bool Error(const Expr *E) {
2203 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2204 }
2205
Richard Smith51201882011-12-30 21:15:51 +00002206 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002207
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002208public:
2209 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2210
2211 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002212 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002213 }
2214 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002215 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002216 }
2217
2218 RetTy VisitParenExpr(const ParenExpr *E)
2219 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2220 RetTy VisitUnaryExtension(const UnaryOperator *E)
2221 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2222 RetTy VisitUnaryPlus(const UnaryOperator *E)
2223 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2224 RetTy VisitChooseExpr(const ChooseExpr *E)
2225 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2226 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2227 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002228 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2229 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002230 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2231 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002232 // We cannot create any objects for which cleanups are required, so there is
2233 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2234 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2235 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002236
Richard Smithc216a012011-12-12 12:46:16 +00002237 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2238 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2239 return static_cast<Derived*>(this)->VisitCastExpr(E);
2240 }
2241 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2242 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2243 return static_cast<Derived*>(this)->VisitCastExpr(E);
2244 }
2245
Richard Smithe24f5fc2011-11-17 22:56:20 +00002246 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2247 switch (E->getOpcode()) {
2248 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002249 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002250
2251 case BO_Comma:
2252 VisitIgnoredValue(E->getLHS());
2253 return StmtVisitorTy::Visit(E->getRHS());
2254
2255 case BO_PtrMemD:
2256 case BO_PtrMemI: {
2257 LValue Obj;
2258 if (!HandleMemberPointerAccess(Info, E, Obj))
2259 return false;
2260 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002261 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002262 return false;
2263 return DerivedSuccess(Result, E);
2264 }
2265 }
2266 }
2267
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002268 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2269 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2270 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002271 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002272
2273 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002274 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002275 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002276
2277 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2278 }
2279
2280 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2281 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002282 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002283 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002284
Richard Smithc49bd112011-10-28 17:51:58 +00002285 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002286 return StmtVisitorTy::Visit(EvalExpr);
2287 }
2288
2289 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002290 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002291 if (!Value) {
2292 const Expr *Source = E->getSourceExpr();
2293 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002294 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002295 if (Source == E) { // sanity checking.
2296 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002297 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002298 }
2299 return StmtVisitorTy::Visit(Source);
2300 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002301 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002302 }
Richard Smithf10d9172011-10-11 21:43:33 +00002303
Richard Smithd0dccea2011-10-28 22:34:42 +00002304 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002305 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002306 QualType CalleeType = Callee->getType();
2307
Richard Smithd0dccea2011-10-28 22:34:42 +00002308 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002309 LValue *This = 0, ThisVal;
2310 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002311
Richard Smith59efe262011-11-11 04:05:33 +00002312 // Extract function decl and 'this' pointer from the callee.
2313 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002314 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002315 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2316 // Explicit bound member calls, such as x.f() or p->g();
2317 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002318 return false;
2319 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002320 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002321 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2322 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002323 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2324 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002325 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002326 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002327 return Error(Callee);
2328
2329 FD = dyn_cast<FunctionDecl>(Member);
2330 if (!FD)
2331 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002332 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002333 LValue Call;
2334 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002335 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002336
Richard Smithb4e85ed2012-01-06 16:39:00 +00002337 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002338 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002339 FD = dyn_cast_or_null<FunctionDecl>(
2340 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002341 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002342 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002343
2344 // Overloaded operator calls to member functions are represented as normal
2345 // calls with '*this' as the first argument.
2346 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2347 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002348 // FIXME: When selecting an implicit conversion for an overloaded
2349 // operator delete, we sometimes try to evaluate calls to conversion
2350 // operators without a 'this' parameter!
2351 if (Args.empty())
2352 return Error(E);
2353
Richard Smith59efe262011-11-11 04:05:33 +00002354 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2355 return false;
2356 This = &ThisVal;
2357 Args = Args.slice(1);
2358 }
2359
2360 // Don't call function pointers which have been cast to some other type.
2361 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002362 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002363 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002364 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002365
Richard Smithb04035a2012-02-01 02:39:43 +00002366 if (This && !This->checkSubobject(Info, E, CSK_This))
2367 return false;
2368
Richard Smithc1c5f272011-12-13 06:39:58 +00002369 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002370 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002371 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002372
Richard Smithc1c5f272011-12-13 06:39:58 +00002373 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002374 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2375 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002376 return false;
2377
Richard Smithb4e85ed2012-01-06 16:39:00 +00002378 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002379 }
2380
Richard Smithc49bd112011-10-28 17:51:58 +00002381 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2382 return StmtVisitorTy::Visit(E->getInitializer());
2383 }
Richard Smithf10d9172011-10-11 21:43:33 +00002384 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002385 if (E->getNumInits() == 0)
2386 return DerivedZeroInitialization(E);
2387 if (E->getNumInits() == 1)
2388 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002389 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002390 }
2391 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002392 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002393 }
2394 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002395 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002396 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002397 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002398 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002399 }
Richard Smithf10d9172011-10-11 21:43:33 +00002400
Richard Smith180f4792011-11-10 06:34:14 +00002401 /// A member expression where the object is a prvalue is itself a prvalue.
2402 RetTy VisitMemberExpr(const MemberExpr *E) {
2403 assert(!E->isArrow() && "missing call to bound member function?");
2404
2405 CCValue Val;
2406 if (!Evaluate(Val, Info, E->getBase()))
2407 return false;
2408
2409 QualType BaseTy = E->getBase()->getType();
2410
2411 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002412 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002413 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2414 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2415 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2416
Richard Smithb4e85ed2012-01-06 16:39:00 +00002417 SubobjectDesignator Designator(BaseTy);
2418 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002419
Richard Smithf48fdb02011-12-09 22:58:01 +00002420 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002421 DerivedSuccess(Val, E);
2422 }
2423
Richard Smithc49bd112011-10-28 17:51:58 +00002424 RetTy VisitCastExpr(const CastExpr *E) {
2425 switch (E->getCastKind()) {
2426 default:
2427 break;
2428
David Chisnall7a7ee302012-01-16 17:27:18 +00002429 case CK_AtomicToNonAtomic:
2430 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002431 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002432 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002433 return StmtVisitorTy::Visit(E->getSubExpr());
2434
2435 case CK_LValueToRValue: {
2436 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002437 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2438 return false;
2439 CCValue RVal;
2440 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2441 return false;
2442 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002443 }
2444 }
2445
Richard Smithf48fdb02011-12-09 22:58:01 +00002446 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002447 }
2448
Richard Smith8327fad2011-10-24 18:44:57 +00002449 /// Visit a value which is evaluated, but whose value is ignored.
2450 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002451 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002452 if (!Evaluate(Scratch, Info, E))
2453 Info.EvalStatus.HasSideEffects = true;
2454 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002455};
2456
2457}
2458
2459//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002460// Common base class for lvalue and temporary evaluation.
2461//===----------------------------------------------------------------------===//
2462namespace {
2463template<class Derived>
2464class LValueExprEvaluatorBase
2465 : public ExprEvaluatorBase<Derived, bool> {
2466protected:
2467 LValue &Result;
2468 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2469 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2470
2471 bool Success(APValue::LValueBase B) {
2472 Result.set(B);
2473 return true;
2474 }
2475
2476public:
2477 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2478 ExprEvaluatorBaseTy(Info), Result(Result) {}
2479
2480 bool Success(const CCValue &V, const Expr *E) {
2481 Result.setFrom(V);
2482 return true;
2483 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002484
Richard Smithe24f5fc2011-11-17 22:56:20 +00002485 bool VisitMemberExpr(const MemberExpr *E) {
2486 // Handle non-static data members.
2487 QualType BaseTy;
2488 if (E->isArrow()) {
2489 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2490 return false;
2491 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002492 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002493 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002494 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2495 return false;
2496 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002497 } else {
2498 if (!this->Visit(E->getBase()))
2499 return false;
2500 BaseTy = E->getBase()->getType();
2501 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002502
Richard Smithd9b02e72012-01-25 22:15:11 +00002503 const ValueDecl *MD = E->getMemberDecl();
2504 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2505 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2506 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2507 (void)BaseTy;
2508 HandleLValueMember(this->Info, E, Result, FD);
2509 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2510 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2511 } else
2512 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002513
Richard Smithd9b02e72012-01-25 22:15:11 +00002514 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002515 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002516 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002517 RefValue))
2518 return false;
2519 return Success(RefValue, E);
2520 }
2521 return true;
2522 }
2523
2524 bool VisitBinaryOperator(const BinaryOperator *E) {
2525 switch (E->getOpcode()) {
2526 default:
2527 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2528
2529 case BO_PtrMemD:
2530 case BO_PtrMemI:
2531 return HandleMemberPointerAccess(this->Info, E, Result);
2532 }
2533 }
2534
2535 bool VisitCastExpr(const CastExpr *E) {
2536 switch (E->getCastKind()) {
2537 default:
2538 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2539
2540 case CK_DerivedToBase:
2541 case CK_UncheckedDerivedToBase: {
2542 if (!this->Visit(E->getSubExpr()))
2543 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002544
2545 // Now figure out the necessary offset to add to the base LV to get from
2546 // the derived class to the base class.
2547 QualType Type = E->getSubExpr()->getType();
2548
2549 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2550 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002551 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002552 *PathI))
2553 return false;
2554 Type = (*PathI)->getType();
2555 }
2556
2557 return true;
2558 }
2559 }
2560 }
2561};
2562}
2563
2564//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002565// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002566//
2567// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2568// function designators (in C), decl references to void objects (in C), and
2569// temporaries (if building with -Wno-address-of-temporary).
2570//
2571// LValue evaluation produces values comprising a base expression of one of the
2572// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002573// - Declarations
2574// * VarDecl
2575// * FunctionDecl
2576// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002577// * CompoundLiteralExpr in C
2578// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002579// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002580// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002581// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002582// * ObjCEncodeExpr
2583// * AddrLabelExpr
2584// * BlockExpr
2585// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002586// - Locals and temporaries
2587// * Any Expr, with a Frame indicating the function in which the temporary was
2588// evaluated.
2589// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002590//===----------------------------------------------------------------------===//
2591namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002592class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002593 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002594public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002595 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2596 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002597
Richard Smithc49bd112011-10-28 17:51:58 +00002598 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2599
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002600 bool VisitDeclRefExpr(const DeclRefExpr *E);
2601 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002602 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002603 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2604 bool VisitMemberExpr(const MemberExpr *E);
2605 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2606 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002607 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002608 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2609 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002610
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002611 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002612 switch (E->getCastKind()) {
2613 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002614 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002615
Eli Friedmandb924222011-10-11 00:13:24 +00002616 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002617 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002618 if (!Visit(E->getSubExpr()))
2619 return false;
2620 Result.Designator.setInvalid();
2621 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002622
Richard Smithe24f5fc2011-11-17 22:56:20 +00002623 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002624 if (!Visit(E->getSubExpr()))
2625 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002626 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002627 }
2628 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002629
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002630 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002631
Eli Friedman4efaa272008-11-12 09:44:48 +00002632};
2633} // end anonymous namespace
2634
Richard Smithc49bd112011-10-28 17:51:58 +00002635/// Evaluate an expression as an lvalue. This can be legitimately called on
2636/// expressions which are not glvalues, in a few cases:
2637/// * function designators in C,
2638/// * "extern void" objects,
2639/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002640static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002641 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2642 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2643 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002644 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002645}
2646
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002647bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002648 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2649 return Success(FD);
2650 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002651 return VisitVarDecl(E, VD);
2652 return Error(E);
2653}
Richard Smith436c8892011-10-24 23:14:33 +00002654
Richard Smithc49bd112011-10-28 17:51:58 +00002655bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002656 if (!VD->getType()->isReferenceType()) {
2657 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002658 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002659 return true;
2660 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002661 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002662 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002663
Richard Smith47a1eed2011-10-29 20:57:55 +00002664 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002665 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2666 return false;
2667 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002668}
2669
Richard Smithbd552ef2011-10-31 05:52:43 +00002670bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2671 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002672 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002673 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002674 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2675
2676 Result.set(E, Info.CurrentCall);
2677 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2678 Result, E->GetTemporaryExpr());
2679 }
2680
2681 // Materialization of an lvalue temporary occurs when we need to force a copy
2682 // (for instance, if it's a bitfield).
2683 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2684 if (!Visit(E->GetTemporaryExpr()))
2685 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002686 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002687 Info.CurrentCall->Temporaries[E]))
2688 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002689 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002690 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002691}
2692
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002693bool
2694LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002695 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2696 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2697 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002698 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002699}
2700
Richard Smith47d21452011-12-27 12:18:28 +00002701bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2702 if (E->isTypeOperand())
2703 return Success(E);
2704 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2705 if (RD && RD->isPolymorphic()) {
2706 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2707 << E->getExprOperand()->getType()
2708 << E->getExprOperand()->getSourceRange();
2709 return false;
2710 }
2711 return Success(E);
2712}
2713
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002714bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002715 // Handle static data members.
2716 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2717 VisitIgnoredValue(E->getBase());
2718 return VisitVarDecl(E, VD);
2719 }
2720
Richard Smithd0dccea2011-10-28 22:34:42 +00002721 // Handle static member functions.
2722 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2723 if (MD->isStatic()) {
2724 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002725 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002726 }
2727 }
2728
Richard Smith180f4792011-11-10 06:34:14 +00002729 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002730 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002731}
2732
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002733bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002734 // FIXME: Deal with vectors as array subscript bases.
2735 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002736 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002737
Anders Carlsson3068d112008-11-16 19:01:22 +00002738 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002739 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Anders Carlsson3068d112008-11-16 19:01:22 +00002741 APSInt Index;
2742 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002743 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002744 int64_t IndexValue
2745 = Index.isSigned() ? Index.getSExtValue()
2746 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002747
Richard Smithb4e85ed2012-01-06 16:39:00 +00002748 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002749}
Eli Friedman4efaa272008-11-12 09:44:48 +00002750
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002751bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002752 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002753}
2754
Eli Friedman4efaa272008-11-12 09:44:48 +00002755//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002756// Pointer Evaluation
2757//===----------------------------------------------------------------------===//
2758
Anders Carlssonc754aa62008-07-08 05:13:58 +00002759namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002760class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002761 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002762 LValue &Result;
2763
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002764 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002765 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002766 return true;
2767 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002768public:
Mike Stump1eb44332009-09-09 15:08:12 +00002769
John McCallefdb83e2010-05-07 21:00:08 +00002770 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002771 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002772
Richard Smith47a1eed2011-10-29 20:57:55 +00002773 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002774 Result.setFrom(V);
2775 return true;
2776 }
Richard Smith51201882011-12-30 21:15:51 +00002777 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002778 return Success((Expr*)0);
2779 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002780
John McCallefdb83e2010-05-07 21:00:08 +00002781 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002782 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002783 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002784 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002785 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002786 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002787 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002788 bool VisitCallExpr(const CallExpr *E);
2789 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002790 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002791 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002792 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002793 }
Richard Smith180f4792011-11-10 06:34:14 +00002794 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2795 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002796 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002797 Result = *Info.CurrentCall->This;
2798 return true;
2799 }
John McCall56ca35d2011-02-17 10:25:35 +00002800
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002801 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002802};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002803} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002804
John McCallefdb83e2010-05-07 21:00:08 +00002805static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002806 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002807 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002808}
2809
John McCallefdb83e2010-05-07 21:00:08 +00002810bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002811 if (E->getOpcode() != BO_Add &&
2812 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002813 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002814
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002815 const Expr *PExp = E->getLHS();
2816 const Expr *IExp = E->getRHS();
2817 if (IExp->getType()->isPointerType())
2818 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002819
Richard Smith745f5142012-01-27 01:14:48 +00002820 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
2821 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00002822 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002823
John McCallefdb83e2010-05-07 21:00:08 +00002824 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00002825 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00002826 return false;
2827 int64_t AdditionalOffset
2828 = Offset.isSigned() ? Offset.getSExtValue()
2829 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002830 if (E->getOpcode() == BO_Sub)
2831 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002832
Richard Smith180f4792011-11-10 06:34:14 +00002833 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00002834 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2835 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002836}
Eli Friedman4efaa272008-11-12 09:44:48 +00002837
John McCallefdb83e2010-05-07 21:00:08 +00002838bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2839 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002840}
Mike Stump1eb44332009-09-09 15:08:12 +00002841
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002842bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2843 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002844
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002845 switch (E->getCastKind()) {
2846 default:
2847 break;
2848
John McCall2de56d12010-08-25 11:45:40 +00002849 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002850 case CK_CPointerToObjCPointerCast:
2851 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002852 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00002853 if (!Visit(SubExpr))
2854 return false;
Richard Smithc216a012011-12-12 12:46:16 +00002855 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2856 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2857 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002858 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00002859 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002860 if (SubExpr->getType()->isVoidPointerType())
2861 CCEDiag(E, diag::note_constexpr_invalid_cast)
2862 << 3 << SubExpr->getType();
2863 else
2864 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2865 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002866 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002867
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002868 case CK_DerivedToBase:
2869 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002870 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002871 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002872 if (!Result.Base && Result.Offset.isZero())
2873 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002874
Richard Smith180f4792011-11-10 06:34:14 +00002875 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002876 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002877 QualType Type =
2878 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002879
Richard Smith180f4792011-11-10 06:34:14 +00002880 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002881 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002882 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2883 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002884 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002885 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002886 }
2887
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002888 return true;
2889 }
2890
Richard Smithe24f5fc2011-11-17 22:56:20 +00002891 case CK_BaseToDerived:
2892 if (!Visit(E->getSubExpr()))
2893 return false;
2894 if (!Result.Base && Result.Offset.isZero())
2895 return true;
2896 return HandleBaseToDerivedCast(Info, E, Result);
2897
Richard Smith47a1eed2011-10-29 20:57:55 +00002898 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00002899 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002900
John McCall2de56d12010-08-25 11:45:40 +00002901 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002902 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2903
Richard Smith47a1eed2011-10-29 20:57:55 +00002904 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002905 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002906 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002907
John McCallefdb83e2010-05-07 21:00:08 +00002908 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002909 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2910 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002911 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002912 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002913 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002914 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002915 return true;
2916 } else {
2917 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002918 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002919 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002920 }
2921 }
John McCall2de56d12010-08-25 11:45:40 +00002922 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002923 if (SubExpr->isGLValue()) {
2924 if (!EvaluateLValue(SubExpr, Result, Info))
2925 return false;
2926 } else {
2927 Result.set(SubExpr, Info.CurrentCall);
2928 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2929 Info, Result, SubExpr))
2930 return false;
2931 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002932 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002933 if (const ConstantArrayType *CAT
2934 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
2935 Result.addArray(Info, E, CAT);
2936 else
2937 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00002938 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002939
John McCall2de56d12010-08-25 11:45:40 +00002940 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002941 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002942 }
2943
Richard Smithc49bd112011-10-28 17:51:58 +00002944 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002945}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002946
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002947bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002948 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002949 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002950
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002951 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002952}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002953
2954//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002955// Member Pointer Evaluation
2956//===----------------------------------------------------------------------===//
2957
2958namespace {
2959class MemberPointerExprEvaluator
2960 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2961 MemberPtr &Result;
2962
2963 bool Success(const ValueDecl *D) {
2964 Result = MemberPtr(D);
2965 return true;
2966 }
2967public:
2968
2969 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2970 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2971
2972 bool Success(const CCValue &V, const Expr *E) {
2973 Result.setFrom(V);
2974 return true;
2975 }
Richard Smith51201882011-12-30 21:15:51 +00002976 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002977 return Success((const ValueDecl*)0);
2978 }
2979
2980 bool VisitCastExpr(const CastExpr *E);
2981 bool VisitUnaryAddrOf(const UnaryOperator *E);
2982};
2983} // end anonymous namespace
2984
2985static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2986 EvalInfo &Info) {
2987 assert(E->isRValue() && E->getType()->isMemberPointerType());
2988 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2989}
2990
2991bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2992 switch (E->getCastKind()) {
2993 default:
2994 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2995
2996 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00002997 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002998
2999 case CK_BaseToDerivedMemberPointer: {
3000 if (!Visit(E->getSubExpr()))
3001 return false;
3002 if (E->path_empty())
3003 return true;
3004 // Base-to-derived member pointer casts store the path in derived-to-base
3005 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3006 // the wrong end of the derived->base arc, so stagger the path by one class.
3007 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3008 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3009 PathI != PathE; ++PathI) {
3010 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3011 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3012 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003013 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003014 }
3015 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3016 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003017 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003018 return true;
3019 }
3020
3021 case CK_DerivedToBaseMemberPointer:
3022 if (!Visit(E->getSubExpr()))
3023 return false;
3024 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3025 PathE = E->path_end(); PathI != PathE; ++PathI) {
3026 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3027 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3028 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003029 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003030 }
3031 return true;
3032 }
3033}
3034
3035bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3036 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3037 // member can be formed.
3038 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3039}
3040
3041//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003042// Record Evaluation
3043//===----------------------------------------------------------------------===//
3044
3045namespace {
3046 class RecordExprEvaluator
3047 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3048 const LValue &This;
3049 APValue &Result;
3050 public:
3051
3052 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3053 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3054
3055 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003056 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00003057 }
Richard Smith51201882011-12-30 21:15:51 +00003058 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003059
Richard Smith59efe262011-11-11 04:05:33 +00003060 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003061 bool VisitInitListExpr(const InitListExpr *E);
3062 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3063 };
3064}
3065
Richard Smith51201882011-12-30 21:15:51 +00003066/// Perform zero-initialization on an object of non-union class type.
3067/// C++11 [dcl.init]p5:
3068/// To zero-initialize an object or reference of type T means:
3069/// [...]
3070/// -- if T is a (possibly cv-qualified) non-union class type,
3071/// each non-static data member and each base-class subobject is
3072/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003073static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3074 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003075 const LValue &This, APValue &Result) {
3076 assert(!RD->isUnion() && "Expected non-union class type");
3077 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3078 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3079 std::distance(RD->field_begin(), RD->field_end()));
3080
3081 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3082
3083 if (CD) {
3084 unsigned Index = 0;
3085 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003086 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003087 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3088 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003089 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3090 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003091 Result.getStructBase(Index)))
3092 return false;
3093 }
3094 }
3095
Richard Smithb4e85ed2012-01-06 16:39:00 +00003096 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3097 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003098 // -- if T is a reference type, no initialization is performed.
3099 if ((*I)->getType()->isReferenceType())
3100 continue;
3101
3102 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003103 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003104
3105 ImplicitValueInitExpr VIE((*I)->getType());
3106 if (!EvaluateConstantExpression(
3107 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3108 return false;
3109 }
3110
3111 return true;
3112}
3113
3114bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3115 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3116 if (RD->isUnion()) {
3117 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3118 // object's first non-static named data member is zero-initialized
3119 RecordDecl::field_iterator I = RD->field_begin();
3120 if (I == RD->field_end()) {
3121 Result = APValue((const FieldDecl*)0);
3122 return true;
3123 }
3124
3125 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003126 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003127 Result = APValue(*I);
3128 ImplicitValueInitExpr VIE((*I)->getType());
3129 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3130 Subobject, &VIE);
3131 }
3132
Richard Smithb4e85ed2012-01-06 16:39:00 +00003133 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003134}
3135
Richard Smith59efe262011-11-11 04:05:33 +00003136bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3137 switch (E->getCastKind()) {
3138 default:
3139 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3140
3141 case CK_ConstructorConversion:
3142 return Visit(E->getSubExpr());
3143
3144 case CK_DerivedToBase:
3145 case CK_UncheckedDerivedToBase: {
3146 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003147 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003148 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003149 if (!DerivedObject.isStruct())
3150 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003151
3152 // Derived-to-base rvalue conversion: just slice off the derived part.
3153 APValue *Value = &DerivedObject;
3154 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3155 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3156 PathE = E->path_end(); PathI != PathE; ++PathI) {
3157 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3158 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3159 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3160 RD = Base;
3161 }
3162 Result = *Value;
3163 return true;
3164 }
3165 }
3166}
3167
Richard Smith180f4792011-11-10 06:34:14 +00003168bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3169 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3170 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3171
3172 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003173 const FieldDecl *Field = E->getInitializedFieldInUnion();
3174 Result = APValue(Field);
3175 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003176 return true;
Richard Smithec789162012-01-12 18:54:33 +00003177
3178 // If the initializer list for a union does not contain any elements, the
3179 // first element of the union is value-initialized.
3180 ImplicitValueInitExpr VIE(Field->getType());
3181 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3182
Richard Smith180f4792011-11-10 06:34:14 +00003183 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003184 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003185 return EvaluateConstantExpression(Result.getUnionValue(), Info,
Richard Smithec789162012-01-12 18:54:33 +00003186 Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003187 }
3188
3189 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3190 "initializer list for class with base classes");
3191 Result = APValue(APValue::UninitStruct(), 0,
3192 std::distance(RD->field_begin(), RD->field_end()));
3193 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003194 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003195 for (RecordDecl::field_iterator Field = RD->field_begin(),
3196 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3197 // Anonymous bit-fields are not considered members of the class for
3198 // purposes of aggregate initialization.
3199 if (Field->isUnnamedBitfield())
3200 continue;
3201
3202 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003203
Richard Smith745f5142012-01-27 01:14:48 +00003204 bool HaveInit = ElementNo < E->getNumInits();
3205
3206 // FIXME: Diagnostics here should point to the end of the initializer
3207 // list, not the start.
3208 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3209 *Field, &Layout);
3210
3211 // Perform an implicit value-initialization for members beyond the end of
3212 // the initializer list.
3213 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3214
3215 if (!EvaluateConstantExpression(
3216 Result.getStructField((*Field)->getFieldIndex()),
3217 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3218 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003219 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003220 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003221 }
3222 }
3223
Richard Smith745f5142012-01-27 01:14:48 +00003224 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003225}
3226
3227bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3228 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003229 bool ZeroInit = E->requiresZeroInitialization();
3230 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003231 // If we've already performed zero-initialization, we're already done.
3232 if (!Result.isUninit())
3233 return true;
3234
Richard Smith51201882011-12-30 21:15:51 +00003235 if (ZeroInit)
3236 return ZeroInitialization(E);
3237
Richard Smith61802452011-12-22 02:22:31 +00003238 const CXXRecordDecl *RD = FD->getParent();
3239 if (RD->isUnion())
3240 Result = APValue((FieldDecl*)0);
3241 else
3242 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3243 std::distance(RD->field_begin(), RD->field_end()));
3244 return true;
3245 }
3246
Richard Smith180f4792011-11-10 06:34:14 +00003247 const FunctionDecl *Definition = 0;
3248 FD->getBody(Definition);
3249
Richard Smithc1c5f272011-12-13 06:39:58 +00003250 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3251 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003252
Richard Smith610a60c2012-01-10 04:32:03 +00003253 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003254 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003255 if (const MaterializeTemporaryExpr *ME
3256 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3257 return Visit(ME->GetTemporaryExpr());
3258
Richard Smith51201882011-12-30 21:15:51 +00003259 if (ZeroInit && !ZeroInitialization(E))
3260 return false;
3261
Richard Smith180f4792011-11-10 06:34:14 +00003262 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003263 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003264 cast<CXXConstructorDecl>(Definition), Info,
3265 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003266}
3267
3268static bool EvaluateRecord(const Expr *E, const LValue &This,
3269 APValue &Result, EvalInfo &Info) {
3270 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003271 "can't evaluate expression as a record rvalue");
3272 return RecordExprEvaluator(Info, This, Result).Visit(E);
3273}
3274
3275//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003276// Temporary Evaluation
3277//
3278// Temporaries are represented in the AST as rvalues, but generally behave like
3279// lvalues. The full-object of which the temporary is a subobject is implicitly
3280// materialized so that a reference can bind to it.
3281//===----------------------------------------------------------------------===//
3282namespace {
3283class TemporaryExprEvaluator
3284 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3285public:
3286 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3287 LValueExprEvaluatorBaseTy(Info, Result) {}
3288
3289 /// Visit an expression which constructs the value of this temporary.
3290 bool VisitConstructExpr(const Expr *E) {
3291 Result.set(E, Info.CurrentCall);
3292 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3293 Result, E);
3294 }
3295
3296 bool VisitCastExpr(const CastExpr *E) {
3297 switch (E->getCastKind()) {
3298 default:
3299 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3300
3301 case CK_ConstructorConversion:
3302 return VisitConstructExpr(E->getSubExpr());
3303 }
3304 }
3305 bool VisitInitListExpr(const InitListExpr *E) {
3306 return VisitConstructExpr(E);
3307 }
3308 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3309 return VisitConstructExpr(E);
3310 }
3311 bool VisitCallExpr(const CallExpr *E) {
3312 return VisitConstructExpr(E);
3313 }
3314};
3315} // end anonymous namespace
3316
3317/// Evaluate an expression of record type as a temporary.
3318static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003319 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003320 return TemporaryExprEvaluator(Info, Result).Visit(E);
3321}
3322
3323//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003324// Vector Evaluation
3325//===----------------------------------------------------------------------===//
3326
3327namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003328 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003329 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3330 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003331 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003332
Richard Smith07fc6572011-10-22 21:10:00 +00003333 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3334 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003335
Richard Smith07fc6572011-10-22 21:10:00 +00003336 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3337 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3338 // FIXME: remove this APValue copy.
3339 Result = APValue(V.data(), V.size());
3340 return true;
3341 }
Richard Smith69c2c502011-11-04 05:33:44 +00003342 bool Success(const CCValue &V, const Expr *E) {
3343 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003344 Result = V;
3345 return true;
3346 }
Richard Smith51201882011-12-30 21:15:51 +00003347 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003348
Richard Smith07fc6572011-10-22 21:10:00 +00003349 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003350 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003351 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003352 bool VisitInitListExpr(const InitListExpr *E);
3353 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003354 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003355 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003356 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003357 };
3358} // end anonymous namespace
3359
3360static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003361 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003362 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003363}
3364
Richard Smith07fc6572011-10-22 21:10:00 +00003365bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3366 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003367 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003368
Richard Smithd62ca372011-12-06 22:44:34 +00003369 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003370 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003371
Eli Friedman46a52322011-03-25 00:43:55 +00003372 switch (E->getCastKind()) {
3373 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003374 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003375 if (SETy->isIntegerType()) {
3376 APSInt IntResult;
3377 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003378 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003379 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003380 } else if (SETy->isRealFloatingType()) {
3381 APFloat F(0.0);
3382 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003383 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003384 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003385 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003386 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003387 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003388
3389 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003390 SmallVector<APValue, 4> Elts(NElts, Val);
3391 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003392 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003393 case CK_BitCast: {
3394 // Evaluate the operand into an APInt we can extract from.
3395 llvm::APInt SValInt;
3396 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3397 return false;
3398 // Extract the elements
3399 QualType EltTy = VTy->getElementType();
3400 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3401 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3402 SmallVector<APValue, 4> Elts;
3403 if (EltTy->isRealFloatingType()) {
3404 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3405 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3406 unsigned FloatEltSize = EltSize;
3407 if (&Sem == &APFloat::x87DoubleExtended)
3408 FloatEltSize = 80;
3409 for (unsigned i = 0; i < NElts; i++) {
3410 llvm::APInt Elt;
3411 if (BigEndian)
3412 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3413 else
3414 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3415 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3416 }
3417 } else if (EltTy->isIntegerType()) {
3418 for (unsigned i = 0; i < NElts; i++) {
3419 llvm::APInt Elt;
3420 if (BigEndian)
3421 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3422 else
3423 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3424 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3425 }
3426 } else {
3427 return Error(E);
3428 }
3429 return Success(Elts, E);
3430 }
Eli Friedman46a52322011-03-25 00:43:55 +00003431 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003432 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003433 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003434}
3435
Richard Smith07fc6572011-10-22 21:10:00 +00003436bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003437VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003438 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003439 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003440 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003441
Nate Begeman59b5da62009-01-18 03:20:47 +00003442 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003443 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003444
Eli Friedman3edd5a92012-01-03 23:24:20 +00003445 // The number of initializers can be less than the number of
3446 // vector elements. For OpenCL, this can be due to nested vector
3447 // initialization. For GCC compatibility, missing trailing elements
3448 // should be initialized with zeroes.
3449 unsigned CountInits = 0, CountElts = 0;
3450 while (CountElts < NumElements) {
3451 // Handle nested vector initialization.
3452 if (CountInits < NumInits
3453 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3454 APValue v;
3455 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3456 return Error(E);
3457 unsigned vlen = v.getVectorLength();
3458 for (unsigned j = 0; j < vlen; j++)
3459 Elements.push_back(v.getVectorElt(j));
3460 CountElts += vlen;
3461 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003462 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003463 if (CountInits < NumInits) {
3464 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3465 return Error(E);
3466 } else // trailing integer zero.
3467 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3468 Elements.push_back(APValue(sInt));
3469 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003470 } else {
3471 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003472 if (CountInits < NumInits) {
3473 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3474 return Error(E);
3475 } else // trailing float zero.
3476 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3477 Elements.push_back(APValue(f));
3478 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003479 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003480 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003481 }
Richard Smith07fc6572011-10-22 21:10:00 +00003482 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003483}
3484
Richard Smith07fc6572011-10-22 21:10:00 +00003485bool
Richard Smith51201882011-12-30 21:15:51 +00003486VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003487 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003488 QualType EltTy = VT->getElementType();
3489 APValue ZeroElement;
3490 if (EltTy->isIntegerType())
3491 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3492 else
3493 ZeroElement =
3494 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3495
Chris Lattner5f9e2722011-07-23 10:55:15 +00003496 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003497 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003498}
3499
Richard Smith07fc6572011-10-22 21:10:00 +00003500bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003501 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003502 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003503}
3504
Nate Begeman59b5da62009-01-18 03:20:47 +00003505//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003506// Array Evaluation
3507//===----------------------------------------------------------------------===//
3508
3509namespace {
3510 class ArrayExprEvaluator
3511 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003512 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003513 APValue &Result;
3514 public:
3515
Richard Smith180f4792011-11-10 06:34:14 +00003516 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3517 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003518
3519 bool Success(const APValue &V, const Expr *E) {
3520 assert(V.isArray() && "Expected array type");
3521 Result = V;
3522 return true;
3523 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003524
Richard Smith51201882011-12-30 21:15:51 +00003525 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003526 const ConstantArrayType *CAT =
3527 Info.Ctx.getAsConstantArrayType(E->getType());
3528 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003529 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003530
3531 Result = APValue(APValue::UninitArray(), 0,
3532 CAT->getSize().getZExtValue());
3533 if (!Result.hasArrayFiller()) return true;
3534
Richard Smith51201882011-12-30 21:15:51 +00003535 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003536 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003537 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003538 ImplicitValueInitExpr VIE(CAT->getElementType());
3539 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3540 Subobject, &VIE);
3541 }
3542
Richard Smithcc5d4f62011-11-07 09:22:26 +00003543 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003544 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003545 };
3546} // end anonymous namespace
3547
Richard Smith180f4792011-11-10 06:34:14 +00003548static bool EvaluateArray(const Expr *E, const LValue &This,
3549 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003550 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003551 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003552}
3553
3554bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3555 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3556 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003557 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003558
Richard Smith974c5f92011-12-22 01:07:19 +00003559 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3560 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003561 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003562 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3563 LValue LV;
3564 if (!EvaluateLValue(E->getInit(0), LV, Info))
3565 return false;
3566 uint64_t NumElements = CAT->getSize().getZExtValue();
3567 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3568
3569 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003570 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003571 for (uint64_t I = 0; I < NumElements; ++I) {
3572 CCValue Char;
3573 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
Richard Smith745f5142012-01-27 01:14:48 +00003574 CAT->getElementType(), LV, Char) ||
3575 !CheckConstantExpression(Info, E->getInit(0), Char,
3576 Result.getArrayInitializedElt(I)) ||
3577 !HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
Richard Smithb4e85ed2012-01-06 16:39:00 +00003578 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003579 return false;
3580 }
3581 return true;
3582 }
3583
Richard Smith745f5142012-01-27 01:14:48 +00003584 bool Success = true;
3585
Richard Smithcc5d4f62011-11-07 09:22:26 +00003586 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3587 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003588 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003589 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003590 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003591 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003592 I != End; ++I, ++Index) {
3593 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
Richard Smith745f5142012-01-27 01:14:48 +00003594 Info, Subobject, cast<Expr>(*I)) ||
3595 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3596 CAT->getElementType(), 1)) {
3597 if (!Info.keepEvaluatingAfterFailure())
3598 return false;
3599 Success = false;
3600 }
Richard Smith180f4792011-11-10 06:34:14 +00003601 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003602
Richard Smith745f5142012-01-27 01:14:48 +00003603 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003604 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003605 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3606 // but sometimes does:
3607 // struct S { constexpr S() : p(&p) {} void *p; };
3608 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003609 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith745f5142012-01-27 01:14:48 +00003610 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003611}
3612
Richard Smithe24f5fc2011-11-17 22:56:20 +00003613bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3614 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3615 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003616 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003617
Richard Smithec789162012-01-12 18:54:33 +00003618 bool HadZeroInit = !Result.isUninit();
3619 if (!HadZeroInit)
3620 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003621 if (!Result.hasArrayFiller())
3622 return true;
3623
3624 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003625
Richard Smith51201882011-12-30 21:15:51 +00003626 bool ZeroInit = E->requiresZeroInitialization();
3627 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003628 if (HadZeroInit)
3629 return true;
3630
Richard Smith51201882011-12-30 21:15:51 +00003631 if (ZeroInit) {
3632 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003633 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003634 ImplicitValueInitExpr VIE(CAT->getElementType());
3635 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3636 Subobject, &VIE);
3637 }
3638
Richard Smith61802452011-12-22 02:22:31 +00003639 const CXXRecordDecl *RD = FD->getParent();
3640 if (RD->isUnion())
3641 Result.getArrayFiller() = APValue((FieldDecl*)0);
3642 else
3643 Result.getArrayFiller() =
3644 APValue(APValue::UninitStruct(), RD->getNumBases(),
3645 std::distance(RD->field_begin(), RD->field_end()));
3646 return true;
3647 }
3648
Richard Smithe24f5fc2011-11-17 22:56:20 +00003649 const FunctionDecl *Definition = 0;
3650 FD->getBody(Definition);
3651
Richard Smithc1c5f272011-12-13 06:39:58 +00003652 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3653 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003654
3655 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3656 // but sometimes does:
3657 // struct S { constexpr S() : p(&p) {} void *p; };
3658 // S s[10];
3659 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003660 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003661
Richard Smithec789162012-01-12 18:54:33 +00003662 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003663 ImplicitValueInitExpr VIE(CAT->getElementType());
3664 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3665 &VIE))
3666 return false;
3667 }
3668
Richard Smithe24f5fc2011-11-17 22:56:20 +00003669 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003670 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003671 cast<CXXConstructorDecl>(Definition),
3672 Info, Result.getArrayFiller());
3673}
3674
Richard Smithcc5d4f62011-11-07 09:22:26 +00003675//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003676// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003677//
3678// As a GNU extension, we support casting pointers to sufficiently-wide integer
3679// types and back in constant folding. Integer values are thus represented
3680// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003681//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003682
3683namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003684class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003685 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003686 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003687public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003688 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003689 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003690
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003691 bool Success(const llvm::APSInt &SI, const Expr *E) {
3692 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003693 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003694 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003695 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003696 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003697 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003698 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003699 return true;
3700 }
3701
Daniel Dunbar131eb432009-02-19 09:06:44 +00003702 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003703 assert(E->getType()->isIntegralOrEnumerationType() &&
3704 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003705 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003706 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003707 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003708 Result.getInt().setIsUnsigned(
3709 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003710 return true;
3711 }
3712
3713 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003714 assert(E->getType()->isIntegralOrEnumerationType() &&
3715 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003716 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003717 return true;
3718 }
3719
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003720 bool Success(CharUnits Size, const Expr *E) {
3721 return Success(Size.getQuantity(), E);
3722 }
3723
Richard Smith47a1eed2011-10-29 20:57:55 +00003724 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003725 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003726 Result = V;
3727 return true;
3728 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003729 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003730 }
Mike Stump1eb44332009-09-09 15:08:12 +00003731
Richard Smith51201882011-12-30 21:15:51 +00003732 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003733
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003734 //===--------------------------------------------------------------------===//
3735 // Visitor Methods
3736 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003737
Chris Lattner4c4867e2008-07-12 00:38:25 +00003738 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003739 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003740 }
3741 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003742 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003743 }
Eli Friedman04309752009-11-24 05:28:59 +00003744
3745 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3746 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003747 if (CheckReferencedDecl(E, E->getDecl()))
3748 return true;
3749
3750 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003751 }
3752 bool VisitMemberExpr(const MemberExpr *E) {
3753 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003754 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003755 return true;
3756 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003757
3758 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003759 }
3760
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003761 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003762 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003763 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003764 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003765
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003766 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003767 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003768
Anders Carlsson3068d112008-11-16 19:01:22 +00003769 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003770 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003771 }
Mike Stump1eb44332009-09-09 15:08:12 +00003772
Richard Smithf10d9172011-10-11 21:43:33 +00003773 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003774 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003775 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003776 }
3777
Sebastian Redl64b45f72009-01-05 20:52:13 +00003778 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003779 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003780 }
3781
Francois Pichet6ad6f282010-12-07 00:08:36 +00003782 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3783 return Success(E->getValue(), E);
3784 }
3785
John Wiegley21ff2e52011-04-28 00:16:57 +00003786 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3787 return Success(E->getValue(), E);
3788 }
3789
John Wiegley55262202011-04-25 06:54:41 +00003790 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3791 return Success(E->getValue(), E);
3792 }
3793
Eli Friedman722c7172009-02-28 03:59:05 +00003794 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003795 bool VisitUnaryImag(const UnaryOperator *E);
3796
Sebastian Redl295995c2010-09-10 20:55:47 +00003797 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003798 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003799
Chris Lattnerfcee0012008-07-11 21:24:13 +00003800private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003801 CharUnits GetAlignOfExpr(const Expr *E);
3802 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003803 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003804 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003805 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003806};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003807} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003808
Richard Smithc49bd112011-10-28 17:51:58 +00003809/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3810/// produce either the integer value or a pointer.
3811///
3812/// GCC has a heinous extension which folds casts between pointer types and
3813/// pointer-sized integral types. We support this by allowing the evaluation of
3814/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3815/// Some simple arithmetic on such values is supported (they are treated much
3816/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003817static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003818 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003819 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003820 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003821}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003822
Richard Smithf48fdb02011-12-09 22:58:01 +00003823static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003824 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003825 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003826 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003827 if (!Val.isInt()) {
3828 // FIXME: It would be better to produce the diagnostic for casting
3829 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003830 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003831 return false;
3832 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003833 Result = Val.getInt();
3834 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003835}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003836
Richard Smithf48fdb02011-12-09 22:58:01 +00003837/// Check whether the given declaration can be directly converted to an integral
3838/// rvalue. If not, no diagnostic is produced; there are other things we can
3839/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003840bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003841 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003842 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003843 // Check for signedness/width mismatches between E type and ECD value.
3844 bool SameSign = (ECD->getInitVal().isSigned()
3845 == E->getType()->isSignedIntegerOrEnumerationType());
3846 bool SameWidth = (ECD->getInitVal().getBitWidth()
3847 == Info.Ctx.getIntWidth(E->getType()));
3848 if (SameSign && SameWidth)
3849 return Success(ECD->getInitVal(), E);
3850 else {
3851 // Get rid of mismatch (otherwise Success assertions will fail)
3852 // by computing a new value matching the type of E.
3853 llvm::APSInt Val = ECD->getInitVal();
3854 if (!SameSign)
3855 Val.setIsSigned(!ECD->getInitVal().isSigned());
3856 if (!SameWidth)
3857 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3858 return Success(Val, E);
3859 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003860 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003861 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003862}
3863
Chris Lattnera4d55d82008-10-06 06:40:35 +00003864/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3865/// as GCC.
3866static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3867 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003868 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003869 enum gcc_type_class {
3870 no_type_class = -1,
3871 void_type_class, integer_type_class, char_type_class,
3872 enumeral_type_class, boolean_type_class,
3873 pointer_type_class, reference_type_class, offset_type_class,
3874 real_type_class, complex_type_class,
3875 function_type_class, method_type_class,
3876 record_type_class, union_type_class,
3877 array_type_class, string_type_class,
3878 lang_type_class
3879 };
Mike Stump1eb44332009-09-09 15:08:12 +00003880
3881 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003882 // ideal, however it is what gcc does.
3883 if (E->getNumArgs() == 0)
3884 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003885
Chris Lattnera4d55d82008-10-06 06:40:35 +00003886 QualType ArgTy = E->getArg(0)->getType();
3887 if (ArgTy->isVoidType())
3888 return void_type_class;
3889 else if (ArgTy->isEnumeralType())
3890 return enumeral_type_class;
3891 else if (ArgTy->isBooleanType())
3892 return boolean_type_class;
3893 else if (ArgTy->isCharType())
3894 return string_type_class; // gcc doesn't appear to use char_type_class
3895 else if (ArgTy->isIntegerType())
3896 return integer_type_class;
3897 else if (ArgTy->isPointerType())
3898 return pointer_type_class;
3899 else if (ArgTy->isReferenceType())
3900 return reference_type_class;
3901 else if (ArgTy->isRealType())
3902 return real_type_class;
3903 else if (ArgTy->isComplexType())
3904 return complex_type_class;
3905 else if (ArgTy->isFunctionType())
3906 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003907 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003908 return record_type_class;
3909 else if (ArgTy->isUnionType())
3910 return union_type_class;
3911 else if (ArgTy->isArrayType())
3912 return array_type_class;
3913 else if (ArgTy->isUnionType())
3914 return union_type_class;
3915 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003916 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003917}
3918
Richard Smith80d4b552011-12-28 19:48:30 +00003919/// EvaluateBuiltinConstantPForLValue - Determine the result of
3920/// __builtin_constant_p when applied to the given lvalue.
3921///
3922/// An lvalue is only "constant" if it is a pointer or reference to the first
3923/// character of a string literal.
3924template<typename LValue>
3925static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3926 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3927 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3928}
3929
3930/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3931/// GCC as we can manage.
3932static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3933 QualType ArgType = Arg->getType();
3934
3935 // __builtin_constant_p always has one operand. The rules which gcc follows
3936 // are not precisely documented, but are as follows:
3937 //
3938 // - If the operand is of integral, floating, complex or enumeration type,
3939 // and can be folded to a known value of that type, it returns 1.
3940 // - If the operand and can be folded to a pointer to the first character
3941 // of a string literal (or such a pointer cast to an integral type), it
3942 // returns 1.
3943 //
3944 // Otherwise, it returns 0.
3945 //
3946 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3947 // its support for this does not currently work.
3948 if (ArgType->isIntegralOrEnumerationType()) {
3949 Expr::EvalResult Result;
3950 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3951 return false;
3952
3953 APValue &V = Result.Val;
3954 if (V.getKind() == APValue::Int)
3955 return true;
3956
3957 return EvaluateBuiltinConstantPForLValue(V);
3958 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3959 return Arg->isEvaluatable(Ctx);
3960 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3961 LValue LV;
3962 Expr::EvalStatus Status;
3963 EvalInfo Info(Ctx, Status);
3964 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3965 : EvaluatePointer(Arg, LV, Info)) &&
3966 !Status.HasSideEffects)
3967 return EvaluateBuiltinConstantPForLValue(LV);
3968 }
3969
3970 // Anything else isn't considered to be sufficiently constant.
3971 return false;
3972}
3973
John McCall42c8f872010-05-10 23:27:23 +00003974/// Retrieves the "underlying object type" of the given expression,
3975/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003976QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3977 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3978 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003979 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003980 } else if (const Expr *E = B.get<const Expr*>()) {
3981 if (isa<CompoundLiteralExpr>(E))
3982 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003983 }
3984
3985 return QualType();
3986}
3987
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003988bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003989 // TODO: Perhaps we should let LLVM lower this?
3990 LValue Base;
3991 if (!EvaluatePointer(E->getArg(0), Base, Info))
3992 return false;
3993
3994 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003995 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003996
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003997 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003998 if (T.isNull() ||
3999 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004000 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004001 T->isVariablyModifiedType() ||
4002 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004003 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004004
4005 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4006 CharUnits Offset = Base.getLValueOffset();
4007
4008 if (!Offset.isNegative() && Offset <= Size)
4009 Size -= Offset;
4010 else
4011 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004012 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004013}
4014
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004015bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004016 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004017 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004018 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004019
4020 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004021 if (TryEvaluateBuiltinObjectSize(E))
4022 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004023
Eric Christopherb2aaf512010-01-19 22:58:35 +00004024 // If evaluating the argument has side-effects we can't determine
4025 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004026 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004027 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004028 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004029 return Success(0, E);
4030 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004031
Richard Smithf48fdb02011-12-09 22:58:01 +00004032 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004033 }
4034
Chris Lattner019f4e82008-10-06 05:28:25 +00004035 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004036 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004037
Richard Smith80d4b552011-12-28 19:48:30 +00004038 case Builtin::BI__builtin_constant_p:
4039 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004040
Chris Lattner21fb98e2009-09-23 06:06:36 +00004041 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004042 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004043 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004044 return Success(Operand, E);
4045 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004046
4047 case Builtin::BI__builtin_expect:
4048 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004049
Douglas Gregor5726d402010-09-10 06:27:15 +00004050 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004051 // A call to strlen is not a constant expression.
4052 if (Info.getLangOpts().CPlusPlus0x)
4053 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4054 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4055 else
4056 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4057 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004058 case Builtin::BI__builtin_strlen:
4059 // As an extension, we support strlen() and __builtin_strlen() as constant
4060 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004061 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004062 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4063 // The string literal may have embedded null characters. Find the first
4064 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004065 StringRef Str = S->getString();
4066 StringRef::size_type Pos = Str.find(0);
4067 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004068 Str = Str.substr(0, Pos);
4069
4070 return Success(Str.size(), E);
4071 }
4072
Richard Smithf48fdb02011-12-09 22:58:01 +00004073 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004074
4075 case Builtin::BI__atomic_is_lock_free: {
4076 APSInt SizeVal;
4077 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4078 return false;
4079
4080 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4081 // of two less than the maximum inline atomic width, we know it is
4082 // lock-free. If the size isn't a power of two, or greater than the
4083 // maximum alignment where we promote atomics, we know it is not lock-free
4084 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4085 // the answer can only be determined at runtime; for example, 16-byte
4086 // atomics have lock-free implementations on some, but not all,
4087 // x86-64 processors.
4088
4089 // Check power-of-two.
4090 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4091 if (!Size.isPowerOfTwo())
4092#if 0
4093 // FIXME: Suppress this folding until the ABI for the promotion width
4094 // settles.
4095 return Success(0, E);
4096#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004097 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004098#endif
4099
4100#if 0
4101 // Check against promotion width.
4102 // FIXME: Suppress this folding until the ABI for the promotion width
4103 // settles.
4104 unsigned PromoteWidthBits =
4105 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4106 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4107 return Success(0, E);
4108#endif
4109
4110 // Check against inlining width.
4111 unsigned InlineWidthBits =
4112 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4113 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4114 return Success(1, E);
4115
Richard Smithf48fdb02011-12-09 22:58:01 +00004116 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004117 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004118 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004119}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004120
Richard Smith625b8072011-10-31 01:37:14 +00004121static bool HasSameBase(const LValue &A, const LValue &B) {
4122 if (!A.getLValueBase())
4123 return !B.getLValueBase();
4124 if (!B.getLValueBase())
4125 return false;
4126
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004127 if (A.getLValueBase().getOpaqueValue() !=
4128 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004129 const Decl *ADecl = GetLValueBaseDecl(A);
4130 if (!ADecl)
4131 return false;
4132 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004133 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004134 return false;
4135 }
4136
4137 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00004138 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00004139}
4140
Chris Lattnerb542afe2008-07-11 19:10:17 +00004141bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004142 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004143 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004144
John McCall2de56d12010-08-25 11:45:40 +00004145 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004146 VisitIgnoredValue(E->getLHS());
4147 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004148 }
4149
4150 if (E->isLogicalOp()) {
4151 // These need to be handled specially because the operands aren't
4152 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004153 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004154
Richard Smithc49bd112011-10-28 17:51:58 +00004155 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004156 // We were able to evaluate the LHS, see if we can get away with not
4157 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004158 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004159 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004160
Richard Smithc49bd112011-10-28 17:51:58 +00004161 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004162 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004163 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004164 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004165 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004166 }
4167 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004168 // FIXME: If both evaluations fail, we should produce the diagnostic from
4169 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4170 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00004171 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004172 // We can't evaluate the LHS; however, sometimes the result
4173 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00004174 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004175 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004176 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00004177 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004178
4179 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004180 }
4181 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004182 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004183
Eli Friedmana6afa762008-11-13 06:09:17 +00004184 return false;
4185 }
4186
Anders Carlsson286f85e2008-11-16 07:17:21 +00004187 QualType LHSTy = E->getLHS()->getType();
4188 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004189
4190 if (LHSTy->isAnyComplexType()) {
4191 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004192 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004193
Richard Smith745f5142012-01-27 01:14:48 +00004194 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4195 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004196 return false;
4197
Richard Smith745f5142012-01-27 01:14:48 +00004198 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004199 return false;
4200
4201 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004202 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004203 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004204 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004205 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4206
John McCall2de56d12010-08-25 11:45:40 +00004207 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004208 return Success((CR_r == APFloat::cmpEqual &&
4209 CR_i == APFloat::cmpEqual), E);
4210 else {
John McCall2de56d12010-08-25 11:45:40 +00004211 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004212 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004213 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004214 CR_r == APFloat::cmpLessThan ||
4215 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004216 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004217 CR_i == APFloat::cmpLessThan ||
4218 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004219 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004220 } else {
John McCall2de56d12010-08-25 11:45:40 +00004221 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004222 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4223 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4224 else {
John McCall2de56d12010-08-25 11:45:40 +00004225 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004226 "Invalid compex comparison.");
4227 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4228 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4229 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004230 }
4231 }
Mike Stump1eb44332009-09-09 15:08:12 +00004232
Anders Carlsson286f85e2008-11-16 07:17:21 +00004233 if (LHSTy->isRealFloatingType() &&
4234 RHSTy->isRealFloatingType()) {
4235 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004236
Richard Smith745f5142012-01-27 01:14:48 +00004237 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4238 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004239 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004240
Richard Smith745f5142012-01-27 01:14:48 +00004241 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004242 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004243
Anders Carlsson286f85e2008-11-16 07:17:21 +00004244 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004245
Anders Carlsson286f85e2008-11-16 07:17:21 +00004246 switch (E->getOpcode()) {
4247 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004248 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004249 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004250 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004251 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004252 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004253 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004254 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004255 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004256 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004257 E);
John McCall2de56d12010-08-25 11:45:40 +00004258 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004259 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004260 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004261 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004262 || CR == APFloat::cmpLessThan
4263 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004264 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004265 }
Mike Stump1eb44332009-09-09 15:08:12 +00004266
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004267 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004268 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004269 LValue LHSValue, RHSValue;
4270
4271 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4272 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004273 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004274
Richard Smith745f5142012-01-27 01:14:48 +00004275 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004276 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004277
Richard Smith625b8072011-10-31 01:37:14 +00004278 // Reject differing bases from the normal codepath; we special-case
4279 // comparisons to null.
4280 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004281 if (E->getOpcode() == BO_Sub) {
4282 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004283 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4284 return false;
4285 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4286 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4287 if (!LHSExpr || !RHSExpr)
4288 return false;
4289 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4290 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4291 if (!LHSAddrExpr || !RHSAddrExpr)
4292 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004293 // Make sure both labels come from the same function.
4294 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4295 RHSAddrExpr->getLabel()->getDeclContext())
4296 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004297 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4298 return true;
4299 }
Richard Smith9e36b532011-10-31 05:11:32 +00004300 // Inequalities and subtractions between unrelated pointers have
4301 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004302 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004303 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004304 // A constant address may compare equal to the address of a symbol.
4305 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004306 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004307 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4308 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004309 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004310 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004311 // distinct addresses. In clang, the result of such a comparison is
4312 // unspecified, so it is not a constant expression. However, we do know
4313 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004314 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4315 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004316 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004317 // We can't tell whether weak symbols will end up pointing to the same
4318 // object.
4319 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004320 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004321 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004322 // (Note that clang defaults to -fmerge-all-constants, which can
4323 // lead to inconsistent results for comparisons involving the address
4324 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004325 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004326 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004327
Richard Smithcc5d4f62011-11-07 09:22:26 +00004328 // FIXME: Implement the C++11 restrictions:
4329 // - Pointer subtractions must be on elements of the same array.
4330 // - Pointer comparisons must be between members with the same access.
4331
John McCall2de56d12010-08-25 11:45:40 +00004332 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00004333 QualType Type = E->getLHS()->getType();
4334 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004335
Richard Smith180f4792011-11-10 06:34:14 +00004336 CharUnits ElementSize;
4337 if (!HandleSizeof(Info, ElementType, ElementSize))
4338 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004339
Richard Smith180f4792011-11-10 06:34:14 +00004340 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00004341 RHSValue.getLValueOffset();
4342 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004343 }
Richard Smith625b8072011-10-31 01:37:14 +00004344
4345 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4346 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith82f28582012-01-31 06:41:30 +00004347
4348 // C++11 [expr.rel]p3:
4349 // Pointers to void (after pointer conversions) can be compared, with a
4350 // result defined as follows: If both pointers represent the same
4351 // address or are both the null pointer value, the result is true if the
4352 // operator is <= or >= and false otherwise; otherwise the result is
4353 // unspecified.
4354 // We interpret this as applying to pointers to *cv* void.
4355 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
4356 E->getOpcode() != BO_EQ && E->getOpcode() != BO_NE)
4357 CCEDiag(E, diag::note_constexpr_void_comparison);
4358
Richard Smith625b8072011-10-31 01:37:14 +00004359 switch (E->getOpcode()) {
4360 default: llvm_unreachable("missing comparison operator");
4361 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4362 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4363 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4364 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4365 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4366 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004367 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004368 }
4369 }
Richard Smithb02e4622012-02-01 01:42:44 +00004370
4371 if (LHSTy->isMemberPointerType()) {
4372 assert(E->isEqualityOp() && "unexpected member pointer operation");
4373 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4374
4375 MemberPtr LHSValue, RHSValue;
4376
4377 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4378 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4379 return false;
4380
4381 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4382 return false;
4383
4384 // C++11 [expr.eq]p2:
4385 // If both operands are null, they compare equal. Otherwise if only one is
4386 // null, they compare unequal.
4387 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4388 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4389 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4390 }
4391
4392 // Otherwise if either is a pointer to a virtual member function, the
4393 // result is unspecified.
4394 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4395 if (MD->isVirtual())
4396 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4397 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4398 if (MD->isVirtual())
4399 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4400
4401 // Otherwise they compare equal if and only if they would refer to the
4402 // same member of the same most derived object or the same subobject if
4403 // they were dereferenced with a hypothetical object of the associated
4404 // class type.
4405 bool Equal = LHSValue == RHSValue;
4406 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4407 }
4408
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004409 if (!LHSTy->isIntegralOrEnumerationType() ||
4410 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004411 // We can't continue from here for non-integral types.
4412 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004413 }
4414
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004415 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004416 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004417
4418 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4419 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004420 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004421
Richard Smith745f5142012-01-27 01:14:48 +00004422 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004423 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004424
Richard Smith47a1eed2011-10-29 20:57:55 +00004425 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004426
4427 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004428 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004429 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4430 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004431 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004432 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004433 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004434 LHSVal.getLValueOffset() -= AdditionalOffset;
4435 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004436 return true;
4437 }
4438
4439 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004440 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004441 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004442 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4443 LHSVal.getInt().getZExtValue());
4444 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004445 return true;
4446 }
4447
Eli Friedman65639282012-01-04 23:13:47 +00004448 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4449 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004450 if (!LHSVal.getLValueOffset().isZero() ||
4451 !RHSVal.getLValueOffset().isZero())
4452 return false;
4453 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4454 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4455 if (!LHSExpr || !RHSExpr)
4456 return false;
4457 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4458 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4459 if (!LHSAddrExpr || !RHSAddrExpr)
4460 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004461 // Make sure both labels come from the same function.
4462 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4463 RHSAddrExpr->getLabel()->getDeclContext())
4464 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004465 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4466 return true;
4467 }
4468
Eli Friedman42edd0d2009-03-24 01:14:50 +00004469 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004470 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004471 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004472
Richard Smithc49bd112011-10-28 17:51:58 +00004473 APSInt &LHS = LHSVal.getInt();
4474 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004475
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004476 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004477 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004478 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004479 case BO_Mul: return Success(LHS * RHS, E);
4480 case BO_Add: return Success(LHS + RHS, E);
4481 case BO_Sub: return Success(LHS - RHS, E);
4482 case BO_And: return Success(LHS & RHS, E);
4483 case BO_Xor: return Success(LHS ^ RHS, E);
4484 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004485 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004486 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004487 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004488 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004489 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4490 // actually undefined behavior in C++11 due to a language defect.
4491 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4492 LHS.isSigned() && LHS.isMinSignedValue())
4493 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4494 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004495 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004496 // During constant-folding, a negative shift is an opposite shift. Such a
4497 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004498 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004499 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004500 RHS = -RHS;
4501 goto shift_right;
4502 }
4503
4504 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004505 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4506 // shifted type.
4507 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4508 if (SA != RHS) {
4509 CCEDiag(E, diag::note_constexpr_large_shift)
4510 << RHS << E->getType() << LHS.getBitWidth();
4511 } else if (LHS.isSigned()) {
4512 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4513 // operand, and must not overflow.
4514 if (LHS.isNegative())
4515 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4516 else if (LHS.countLeadingZeros() <= SA)
4517 HandleOverflow(Info, E, LHS.extend(LHS.getBitWidth() + SA) << SA,
4518 E->getType());
4519 }
4520
Richard Smithc49bd112011-10-28 17:51:58 +00004521 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004522 }
John McCall2de56d12010-08-25 11:45:40 +00004523 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004524 // During constant-folding, a negative shift is an opposite shift. Such a
4525 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004526 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004527 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004528 RHS = -RHS;
4529 goto shift_left;
4530 }
4531
4532 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004533 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4534 // shifted type.
4535 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4536 if (SA != RHS)
4537 CCEDiag(E, diag::note_constexpr_large_shift)
4538 << RHS << E->getType() << LHS.getBitWidth();
4539
Richard Smithc49bd112011-10-28 17:51:58 +00004540 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004541 }
Mike Stump1eb44332009-09-09 15:08:12 +00004542
Richard Smithc49bd112011-10-28 17:51:58 +00004543 case BO_LT: return Success(LHS < RHS, E);
4544 case BO_GT: return Success(LHS > RHS, E);
4545 case BO_LE: return Success(LHS <= RHS, E);
4546 case BO_GE: return Success(LHS >= RHS, E);
4547 case BO_EQ: return Success(LHS == RHS, E);
4548 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004549 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004550}
4551
Ken Dyck8b752f12010-01-27 17:10:57 +00004552CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004553 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4554 // the result is the size of the referenced type."
4555 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4556 // result shall be the alignment of the referenced type."
4557 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4558 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004559
4560 // __alignof is defined to return the preferred alignment.
4561 return Info.Ctx.toCharUnitsFromBits(
4562 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004563}
4564
Ken Dyck8b752f12010-01-27 17:10:57 +00004565CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004566 E = E->IgnoreParens();
4567
4568 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004569 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004570 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004571 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4572 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004573
Chris Lattneraf707ab2009-01-24 21:53:27 +00004574 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004575 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4576 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004577
Chris Lattnere9feb472009-01-24 21:09:06 +00004578 return GetAlignOfType(E->getType());
4579}
4580
4581
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004582/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4583/// a result as the expression's type.
4584bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4585 const UnaryExprOrTypeTraitExpr *E) {
4586 switch(E->getKind()) {
4587 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004588 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004589 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004590 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004591 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004592 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004593
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004594 case UETT_VecStep: {
4595 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004596
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004597 if (Ty->isVectorType()) {
4598 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004599
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004600 // The vec_step built-in functions that take a 3-component
4601 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4602 if (n == 3)
4603 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004604
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004605 return Success(n, E);
4606 } else
4607 return Success(1, E);
4608 }
4609
4610 case UETT_SizeOf: {
4611 QualType SrcTy = E->getTypeOfArgument();
4612 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4613 // the result is the size of the referenced type."
4614 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4615 // result shall be the alignment of the referenced type."
4616 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4617 SrcTy = Ref->getPointeeType();
4618
Richard Smith180f4792011-11-10 06:34:14 +00004619 CharUnits Sizeof;
4620 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004621 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004622 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004623 }
4624 }
4625
4626 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004627}
4628
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004629bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004630 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004631 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004632 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004633 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004634 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004635 for (unsigned i = 0; i != n; ++i) {
4636 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4637 switch (ON.getKind()) {
4638 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004639 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004640 APSInt IdxResult;
4641 if (!EvaluateInteger(Idx, IdxResult, Info))
4642 return false;
4643 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4644 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004645 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004646 CurrentType = AT->getElementType();
4647 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4648 Result += IdxResult.getSExtValue() * ElementSize;
4649 break;
4650 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004651
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004652 case OffsetOfExpr::OffsetOfNode::Field: {
4653 FieldDecl *MemberDecl = ON.getField();
4654 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004655 if (!RT)
4656 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004657 RecordDecl *RD = RT->getDecl();
4658 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004659 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004660 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004661 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004662 CurrentType = MemberDecl->getType().getNonReferenceType();
4663 break;
4664 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004665
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004666 case OffsetOfExpr::OffsetOfNode::Identifier:
4667 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004668
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004669 case OffsetOfExpr::OffsetOfNode::Base: {
4670 CXXBaseSpecifier *BaseSpec = ON.getBase();
4671 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004672 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004673
4674 // Find the layout of the class whose base we are looking into.
4675 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004676 if (!RT)
4677 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004678 RecordDecl *RD = RT->getDecl();
4679 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4680
4681 // Find the base class itself.
4682 CurrentType = BaseSpec->getType();
4683 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4684 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004685 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004686
4687 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004688 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004689 break;
4690 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004691 }
4692 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004693 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004694}
4695
Chris Lattnerb542afe2008-07-11 19:10:17 +00004696bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004697 switch (E->getOpcode()) {
4698 default:
4699 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4700 // See C99 6.6p3.
4701 return Error(E);
4702 case UO_Extension:
4703 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4704 // If so, we could clear the diagnostic ID.
4705 return Visit(E->getSubExpr());
4706 case UO_Plus:
4707 // The result is just the value.
4708 return Visit(E->getSubExpr());
4709 case UO_Minus: {
4710 if (!Visit(E->getSubExpr()))
4711 return false;
4712 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00004713 const APSInt &Value = Result.getInt();
4714 if (Value.isSigned() && Value.isMinSignedValue())
4715 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
4716 E->getType());
4717 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00004718 }
4719 case UO_Not: {
4720 if (!Visit(E->getSubExpr()))
4721 return false;
4722 if (!Result.isInt()) return Error(E);
4723 return Success(~Result.getInt(), E);
4724 }
4725 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004726 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004727 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004728 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004729 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004730 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004731 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004732}
Mike Stump1eb44332009-09-09 15:08:12 +00004733
Chris Lattner732b2232008-07-12 01:15:53 +00004734/// HandleCast - This is used to evaluate implicit or explicit casts where the
4735/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004736bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4737 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004738 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004739 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004740
Eli Friedman46a52322011-03-25 00:43:55 +00004741 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004742 case CK_BaseToDerived:
4743 case CK_DerivedToBase:
4744 case CK_UncheckedDerivedToBase:
4745 case CK_Dynamic:
4746 case CK_ToUnion:
4747 case CK_ArrayToPointerDecay:
4748 case CK_FunctionToPointerDecay:
4749 case CK_NullToPointer:
4750 case CK_NullToMemberPointer:
4751 case CK_BaseToDerivedMemberPointer:
4752 case CK_DerivedToBaseMemberPointer:
4753 case CK_ConstructorConversion:
4754 case CK_IntegralToPointer:
4755 case CK_ToVoid:
4756 case CK_VectorSplat:
4757 case CK_IntegralToFloating:
4758 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004759 case CK_CPointerToObjCPointerCast:
4760 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004761 case CK_AnyPointerToBlockPointerCast:
4762 case CK_ObjCObjectLValueCast:
4763 case CK_FloatingRealToComplex:
4764 case CK_FloatingComplexToReal:
4765 case CK_FloatingComplexCast:
4766 case CK_FloatingComplexToIntegralComplex:
4767 case CK_IntegralRealToComplex:
4768 case CK_IntegralComplexCast:
4769 case CK_IntegralComplexToFloatingComplex:
4770 llvm_unreachable("invalid cast kind for integral value");
4771
Eli Friedmane50c2972011-03-25 19:07:11 +00004772 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004773 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004774 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00004775 case CK_ARCProduceObject:
4776 case CK_ARCConsumeObject:
4777 case CK_ARCReclaimReturnedObject:
4778 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004779 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004780
Richard Smith7d580a42012-01-17 21:17:26 +00004781 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00004782 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00004783 case CK_AtomicToNonAtomic:
4784 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00004785 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004786 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004787
4788 case CK_MemberPointerToBoolean:
4789 case CK_PointerToBoolean:
4790 case CK_IntegralToBoolean:
4791 case CK_FloatingToBoolean:
4792 case CK_FloatingComplexToBoolean:
4793 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004794 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004795 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004796 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004797 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004798 }
4799
Eli Friedman46a52322011-03-25 00:43:55 +00004800 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004801 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004802 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004803
Eli Friedmanbe265702009-02-20 01:15:07 +00004804 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00004805 // Allow casts of address-of-label differences if they are no-ops
4806 // or narrowing. (The narrowing case isn't actually guaranteed to
4807 // be constant-evaluatable except in some narrow cases which are hard
4808 // to detect here. We let it through on the assumption the user knows
4809 // what they are doing.)
4810 if (Result.isAddrLabelDiff())
4811 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00004812 // Only allow casts of lvalues if they are lossless.
4813 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4814 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004815
Richard Smithf72fccf2012-01-30 22:27:01 +00004816 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
4817 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00004818 }
Mike Stump1eb44332009-09-09 15:08:12 +00004819
Eli Friedman46a52322011-03-25 00:43:55 +00004820 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00004821 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4822
John McCallefdb83e2010-05-07 21:00:08 +00004823 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00004824 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004825 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00004826
Daniel Dunbardd211642009-02-19 22:24:01 +00004827 if (LV.getLValueBase()) {
4828 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00004829 // FIXME: Allow a larger integer size than the pointer size, and allow
4830 // narrowing back down to pointer width in subsequent integral casts.
4831 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00004832 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00004833 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004834
Richard Smithb755a9d2011-11-16 07:18:12 +00004835 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004836 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00004837 return true;
4838 }
4839
Ken Dycka7305832010-01-15 12:37:54 +00004840 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4841 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00004842 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00004843 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004844
Eli Friedman46a52322011-03-25 00:43:55 +00004845 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00004846 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00004847 if (!EvaluateComplex(SubExpr, C, Info))
4848 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00004849 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00004850 }
Eli Friedman2217c872009-02-22 11:46:18 +00004851
Eli Friedman46a52322011-03-25 00:43:55 +00004852 case CK_FloatingToIntegral: {
4853 APFloat F(0.0);
4854 if (!EvaluateFloat(SubExpr, F, Info))
4855 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00004856
Richard Smithc1c5f272011-12-13 06:39:58 +00004857 APSInt Value;
4858 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4859 return false;
4860 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00004861 }
4862 }
Mike Stump1eb44332009-09-09 15:08:12 +00004863
Eli Friedman46a52322011-03-25 00:43:55 +00004864 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004865}
Anders Carlsson2bad1682008-07-08 14:30:00 +00004866
Eli Friedman722c7172009-02-28 03:59:05 +00004867bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4868 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004869 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004870 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4871 return false;
4872 if (!LV.isComplexInt())
4873 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004874 return Success(LV.getComplexIntReal(), E);
4875 }
4876
4877 return Visit(E->getSubExpr());
4878}
4879
Eli Friedman664a1042009-02-27 04:45:43 +00004880bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004881 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004882 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004883 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4884 return false;
4885 if (!LV.isComplexInt())
4886 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004887 return Success(LV.getComplexIntImag(), E);
4888 }
4889
Richard Smith8327fad2011-10-24 18:44:57 +00004890 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004891 return Success(0, E);
4892}
4893
Douglas Gregoree8aff02011-01-04 17:33:58 +00004894bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4895 return Success(E->getPackLength(), E);
4896}
4897
Sebastian Redl295995c2010-09-10 20:55:47 +00004898bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4899 return Success(E->getValue(), E);
4900}
4901
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004902//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004903// Float Evaluation
4904//===----------------------------------------------------------------------===//
4905
4906namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004907class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004908 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004909 APFloat &Result;
4910public:
4911 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004912 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004913
Richard Smith47a1eed2011-10-29 20:57:55 +00004914 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004915 Result = V.getFloat();
4916 return true;
4917 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004918
Richard Smith51201882011-12-30 21:15:51 +00004919 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00004920 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4921 return true;
4922 }
4923
Chris Lattner019f4e82008-10-06 05:28:25 +00004924 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004925
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004926 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004927 bool VisitBinaryOperator(const BinaryOperator *E);
4928 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004929 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004930
John McCallabd3a852010-05-07 22:08:54 +00004931 bool VisitUnaryReal(const UnaryOperator *E);
4932 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004933
Richard Smith51201882011-12-30 21:15:51 +00004934 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004935};
4936} // end anonymous namespace
4937
4938static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004939 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004940 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004941}
4942
Jay Foad4ba2a172011-01-12 09:06:06 +00004943static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004944 QualType ResultTy,
4945 const Expr *Arg,
4946 bool SNaN,
4947 llvm::APFloat &Result) {
4948 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4949 if (!S) return false;
4950
4951 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4952
4953 llvm::APInt fill;
4954
4955 // Treat empty strings as if they were zero.
4956 if (S->getString().empty())
4957 fill = llvm::APInt(32, 0);
4958 else if (S->getString().getAsInteger(0, fill))
4959 return false;
4960
4961 if (SNaN)
4962 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4963 else
4964 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4965 return true;
4966}
4967
Chris Lattner019f4e82008-10-06 05:28:25 +00004968bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004969 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004970 default:
4971 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4972
Chris Lattner019f4e82008-10-06 05:28:25 +00004973 case Builtin::BI__builtin_huge_val:
4974 case Builtin::BI__builtin_huge_valf:
4975 case Builtin::BI__builtin_huge_vall:
4976 case Builtin::BI__builtin_inf:
4977 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004978 case Builtin::BI__builtin_infl: {
4979 const llvm::fltSemantics &Sem =
4980 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00004981 Result = llvm::APFloat::getInf(Sem);
4982 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004983 }
Mike Stump1eb44332009-09-09 15:08:12 +00004984
John McCalldb7b72a2010-02-28 13:00:19 +00004985 case Builtin::BI__builtin_nans:
4986 case Builtin::BI__builtin_nansf:
4987 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00004988 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4989 true, Result))
4990 return Error(E);
4991 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00004992
Chris Lattner9e621712008-10-06 06:31:58 +00004993 case Builtin::BI__builtin_nan:
4994 case Builtin::BI__builtin_nanf:
4995 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00004996 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00004997 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00004998 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4999 false, Result))
5000 return Error(E);
5001 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005002
5003 case Builtin::BI__builtin_fabs:
5004 case Builtin::BI__builtin_fabsf:
5005 case Builtin::BI__builtin_fabsl:
5006 if (!EvaluateFloat(E->getArg(0), Result, Info))
5007 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005008
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005009 if (Result.isNegative())
5010 Result.changeSign();
5011 return true;
5012
Mike Stump1eb44332009-09-09 15:08:12 +00005013 case Builtin::BI__builtin_copysign:
5014 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005015 case Builtin::BI__builtin_copysignl: {
5016 APFloat RHS(0.);
5017 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5018 !EvaluateFloat(E->getArg(1), RHS, Info))
5019 return false;
5020 Result.copySign(RHS);
5021 return true;
5022 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005023 }
5024}
5025
John McCallabd3a852010-05-07 22:08:54 +00005026bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005027 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5028 ComplexValue CV;
5029 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5030 return false;
5031 Result = CV.FloatReal;
5032 return true;
5033 }
5034
5035 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005036}
5037
5038bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005039 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5040 ComplexValue CV;
5041 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5042 return false;
5043 Result = CV.FloatImag;
5044 return true;
5045 }
5046
Richard Smith8327fad2011-10-24 18:44:57 +00005047 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005048 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5049 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005050 return true;
5051}
5052
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005053bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005054 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005055 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005056 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005057 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005058 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005059 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5060 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005061 Result.changeSign();
5062 return true;
5063 }
5064}
Chris Lattner019f4e82008-10-06 05:28:25 +00005065
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005066bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005067 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5068 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005069
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005070 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005071 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5072 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005073 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005074 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005075 return false;
5076
5077 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005078 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005079 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005080 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
5081 return true;
John McCall2de56d12010-08-25 11:45:40 +00005082 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005083 Result.add(RHS, APFloat::rmNearestTiesToEven);
5084 return true;
John McCall2de56d12010-08-25 11:45:40 +00005085 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005086 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
5087 return true;
John McCall2de56d12010-08-25 11:45:40 +00005088 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005089 Result.divide(RHS, APFloat::rmNearestTiesToEven);
5090 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005091 }
5092}
5093
5094bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5095 Result = E->getValue();
5096 return true;
5097}
5098
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005099bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5100 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005101
Eli Friedman2a523ee2011-03-25 00:54:52 +00005102 switch (E->getCastKind()) {
5103 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005104 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005105
5106 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005107 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005108 return EvaluateInteger(SubExpr, IntResult, Info) &&
5109 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5110 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005111 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005112
5113 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005114 if (!Visit(SubExpr))
5115 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005116 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5117 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005118 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005119
Eli Friedman2a523ee2011-03-25 00:54:52 +00005120 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005121 ComplexValue V;
5122 if (!EvaluateComplex(SubExpr, V, Info))
5123 return false;
5124 Result = V.getComplexFloatReal();
5125 return true;
5126 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005127 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005128}
5129
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005130//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005131// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005132//===----------------------------------------------------------------------===//
5133
5134namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005135class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005136 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005137 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005138
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005139public:
John McCallf4cf1a12010-05-07 17:22:02 +00005140 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005141 : ExprEvaluatorBaseTy(info), Result(Result) {}
5142
Richard Smith47a1eed2011-10-29 20:57:55 +00005143 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005144 Result.setFrom(V);
5145 return true;
5146 }
Mike Stump1eb44332009-09-09 15:08:12 +00005147
Eli Friedman7ead5c72012-01-10 04:58:17 +00005148 bool ZeroInitialization(const Expr *E);
5149
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005150 //===--------------------------------------------------------------------===//
5151 // Visitor Methods
5152 //===--------------------------------------------------------------------===//
5153
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005154 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005155 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005156 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005157 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005158 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005159};
5160} // end anonymous namespace
5161
John McCallf4cf1a12010-05-07 17:22:02 +00005162static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5163 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005164 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005165 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005166}
5167
Eli Friedman7ead5c72012-01-10 04:58:17 +00005168bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005169 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005170 if (ElemTy->isRealFloatingType()) {
5171 Result.makeComplexFloat();
5172 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5173 Result.FloatReal = Zero;
5174 Result.FloatImag = Zero;
5175 } else {
5176 Result.makeComplexInt();
5177 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5178 Result.IntReal = Zero;
5179 Result.IntImag = Zero;
5180 }
5181 return true;
5182}
5183
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005184bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5185 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005186
5187 if (SubExpr->getType()->isRealFloatingType()) {
5188 Result.makeComplexFloat();
5189 APFloat &Imag = Result.FloatImag;
5190 if (!EvaluateFloat(SubExpr, Imag, Info))
5191 return false;
5192
5193 Result.FloatReal = APFloat(Imag.getSemantics());
5194 return true;
5195 } else {
5196 assert(SubExpr->getType()->isIntegerType() &&
5197 "Unexpected imaginary literal.");
5198
5199 Result.makeComplexInt();
5200 APSInt &Imag = Result.IntImag;
5201 if (!EvaluateInteger(SubExpr, Imag, Info))
5202 return false;
5203
5204 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5205 return true;
5206 }
5207}
5208
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005209bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005210
John McCall8786da72010-12-14 17:51:41 +00005211 switch (E->getCastKind()) {
5212 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005213 case CK_BaseToDerived:
5214 case CK_DerivedToBase:
5215 case CK_UncheckedDerivedToBase:
5216 case CK_Dynamic:
5217 case CK_ToUnion:
5218 case CK_ArrayToPointerDecay:
5219 case CK_FunctionToPointerDecay:
5220 case CK_NullToPointer:
5221 case CK_NullToMemberPointer:
5222 case CK_BaseToDerivedMemberPointer:
5223 case CK_DerivedToBaseMemberPointer:
5224 case CK_MemberPointerToBoolean:
5225 case CK_ConstructorConversion:
5226 case CK_IntegralToPointer:
5227 case CK_PointerToIntegral:
5228 case CK_PointerToBoolean:
5229 case CK_ToVoid:
5230 case CK_VectorSplat:
5231 case CK_IntegralCast:
5232 case CK_IntegralToBoolean:
5233 case CK_IntegralToFloating:
5234 case CK_FloatingToIntegral:
5235 case CK_FloatingToBoolean:
5236 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005237 case CK_CPointerToObjCPointerCast:
5238 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005239 case CK_AnyPointerToBlockPointerCast:
5240 case CK_ObjCObjectLValueCast:
5241 case CK_FloatingComplexToReal:
5242 case CK_FloatingComplexToBoolean:
5243 case CK_IntegralComplexToReal:
5244 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005245 case CK_ARCProduceObject:
5246 case CK_ARCConsumeObject:
5247 case CK_ARCReclaimReturnedObject:
5248 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005249 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005250
John McCall8786da72010-12-14 17:51:41 +00005251 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005252 case CK_AtomicToNonAtomic:
5253 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005254 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005255 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005256
5257 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005258 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005259 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005260 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005261
5262 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005263 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005264 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005265 return false;
5266
John McCall8786da72010-12-14 17:51:41 +00005267 Result.makeComplexFloat();
5268 Result.FloatImag = APFloat(Real.getSemantics());
5269 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005270 }
5271
John McCall8786da72010-12-14 17:51:41 +00005272 case CK_FloatingComplexCast: {
5273 if (!Visit(E->getSubExpr()))
5274 return false;
5275
5276 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5277 QualType From
5278 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5279
Richard Smithc1c5f272011-12-13 06:39:58 +00005280 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5281 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005282 }
5283
5284 case CK_FloatingComplexToIntegralComplex: {
5285 if (!Visit(E->getSubExpr()))
5286 return false;
5287
5288 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5289 QualType From
5290 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5291 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005292 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5293 To, Result.IntReal) &&
5294 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5295 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005296 }
5297
5298 case CK_IntegralRealToComplex: {
5299 APSInt &Real = Result.IntReal;
5300 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5301 return false;
5302
5303 Result.makeComplexInt();
5304 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5305 return true;
5306 }
5307
5308 case CK_IntegralComplexCast: {
5309 if (!Visit(E->getSubExpr()))
5310 return false;
5311
5312 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5313 QualType From
5314 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5315
Richard Smithf72fccf2012-01-30 22:27:01 +00005316 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5317 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005318 return true;
5319 }
5320
5321 case CK_IntegralComplexToFloatingComplex: {
5322 if (!Visit(E->getSubExpr()))
5323 return false;
5324
5325 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5326 QualType From
5327 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5328 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005329 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5330 To, Result.FloatReal) &&
5331 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5332 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005333 }
5334 }
5335
5336 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005337}
5338
John McCallf4cf1a12010-05-07 17:22:02 +00005339bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005340 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005341 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5342
Richard Smith745f5142012-01-27 01:14:48 +00005343 bool LHSOK = Visit(E->getLHS());
5344 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005345 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005346
John McCallf4cf1a12010-05-07 17:22:02 +00005347 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005348 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005349 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005350
Daniel Dunbar3f279872009-01-29 01:32:56 +00005351 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5352 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005353 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005354 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005355 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005356 if (Result.isComplexFloat()) {
5357 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5358 APFloat::rmNearestTiesToEven);
5359 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5360 APFloat::rmNearestTiesToEven);
5361 } else {
5362 Result.getComplexIntReal() += RHS.getComplexIntReal();
5363 Result.getComplexIntImag() += RHS.getComplexIntImag();
5364 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005365 break;
John McCall2de56d12010-08-25 11:45:40 +00005366 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005367 if (Result.isComplexFloat()) {
5368 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5369 APFloat::rmNearestTiesToEven);
5370 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5371 APFloat::rmNearestTiesToEven);
5372 } else {
5373 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5374 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5375 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005376 break;
John McCall2de56d12010-08-25 11:45:40 +00005377 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005378 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005379 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005380 APFloat &LHS_r = LHS.getComplexFloatReal();
5381 APFloat &LHS_i = LHS.getComplexFloatImag();
5382 APFloat &RHS_r = RHS.getComplexFloatReal();
5383 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005384
Daniel Dunbar3f279872009-01-29 01:32:56 +00005385 APFloat Tmp = LHS_r;
5386 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5387 Result.getComplexFloatReal() = Tmp;
5388 Tmp = LHS_i;
5389 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5390 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5391
5392 Tmp = LHS_r;
5393 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5394 Result.getComplexFloatImag() = Tmp;
5395 Tmp = LHS_i;
5396 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5397 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5398 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005399 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005400 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005401 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5402 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005403 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005404 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5405 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5406 }
5407 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005408 case BO_Div:
5409 if (Result.isComplexFloat()) {
5410 ComplexValue LHS = Result;
5411 APFloat &LHS_r = LHS.getComplexFloatReal();
5412 APFloat &LHS_i = LHS.getComplexFloatImag();
5413 APFloat &RHS_r = RHS.getComplexFloatReal();
5414 APFloat &RHS_i = RHS.getComplexFloatImag();
5415 APFloat &Res_r = Result.getComplexFloatReal();
5416 APFloat &Res_i = Result.getComplexFloatImag();
5417
5418 APFloat Den = RHS_r;
5419 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5420 APFloat Tmp = RHS_i;
5421 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5422 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5423
5424 Res_r = LHS_r;
5425 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5426 Tmp = LHS_i;
5427 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5428 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5429 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5430
5431 Res_i = LHS_i;
5432 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5433 Tmp = LHS_r;
5434 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5435 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5436 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5437 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005438 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5439 return Error(E, diag::note_expr_divide_by_zero);
5440
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005441 ComplexValue LHS = Result;
5442 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5443 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5444 Result.getComplexIntReal() =
5445 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5446 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5447 Result.getComplexIntImag() =
5448 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5449 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5450 }
5451 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005452 }
5453
John McCallf4cf1a12010-05-07 17:22:02 +00005454 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005455}
5456
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005457bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5458 // Get the operand value into 'Result'.
5459 if (!Visit(E->getSubExpr()))
5460 return false;
5461
5462 switch (E->getOpcode()) {
5463 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005464 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005465 case UO_Extension:
5466 return true;
5467 case UO_Plus:
5468 // The result is always just the subexpr.
5469 return true;
5470 case UO_Minus:
5471 if (Result.isComplexFloat()) {
5472 Result.getComplexFloatReal().changeSign();
5473 Result.getComplexFloatImag().changeSign();
5474 }
5475 else {
5476 Result.getComplexIntReal() = -Result.getComplexIntReal();
5477 Result.getComplexIntImag() = -Result.getComplexIntImag();
5478 }
5479 return true;
5480 case UO_Not:
5481 if (Result.isComplexFloat())
5482 Result.getComplexFloatImag().changeSign();
5483 else
5484 Result.getComplexIntImag() = -Result.getComplexIntImag();
5485 return true;
5486 }
5487}
5488
Eli Friedman7ead5c72012-01-10 04:58:17 +00005489bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5490 if (E->getNumInits() == 2) {
5491 if (E->getType()->isComplexType()) {
5492 Result.makeComplexFloat();
5493 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5494 return false;
5495 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5496 return false;
5497 } else {
5498 Result.makeComplexInt();
5499 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5500 return false;
5501 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5502 return false;
5503 }
5504 return true;
5505 }
5506 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5507}
5508
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005509//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005510// Void expression evaluation, primarily for a cast to void on the LHS of a
5511// comma operator
5512//===----------------------------------------------------------------------===//
5513
5514namespace {
5515class VoidExprEvaluator
5516 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5517public:
5518 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5519
5520 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005521
5522 bool VisitCastExpr(const CastExpr *E) {
5523 switch (E->getCastKind()) {
5524 default:
5525 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5526 case CK_ToVoid:
5527 VisitIgnoredValue(E->getSubExpr());
5528 return true;
5529 }
5530 }
5531};
5532} // end anonymous namespace
5533
5534static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5535 assert(E->isRValue() && E->getType()->isVoidType());
5536 return VoidExprEvaluator(Info).Visit(E);
5537}
5538
5539//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005540// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005541//===----------------------------------------------------------------------===//
5542
Richard Smith47a1eed2011-10-29 20:57:55 +00005543static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005544 // In C, function designators are not lvalues, but we evaluate them as if they
5545 // are.
5546 if (E->isGLValue() || E->getType()->isFunctionType()) {
5547 LValue LV;
5548 if (!EvaluateLValue(E, LV, Info))
5549 return false;
5550 LV.moveInto(Result);
5551 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005552 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005553 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005554 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005555 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005556 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005557 } else if (E->getType()->hasPointerRepresentation()) {
5558 LValue LV;
5559 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005560 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005561 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005562 } else if (E->getType()->isRealFloatingType()) {
5563 llvm::APFloat F(0.0);
5564 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005565 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005566 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005567 } else if (E->getType()->isAnyComplexType()) {
5568 ComplexValue C;
5569 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005570 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005571 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005572 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005573 MemberPtr P;
5574 if (!EvaluateMemberPointer(E, P, Info))
5575 return false;
5576 P.moveInto(Result);
5577 return true;
Richard Smith51201882011-12-30 21:15:51 +00005578 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005579 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005580 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005581 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005582 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005583 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005584 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005585 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005586 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005587 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5588 return false;
5589 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005590 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005591 if (Info.getLangOpts().CPlusPlus0x)
5592 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5593 << E->getType();
5594 else
5595 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005596 if (!EvaluateVoid(E, Info))
5597 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005598 } else if (Info.getLangOpts().CPlusPlus0x) {
5599 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5600 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005601 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005602 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005603 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005604 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005605
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005606 return true;
5607}
5608
Richard Smith69c2c502011-11-04 05:33:44 +00005609/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5610/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5611/// since later initializers for an object can indirectly refer to subobjects
5612/// which were initialized earlier.
5613static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005614 const LValue &This, const Expr *E,
5615 CheckConstantExpressionKind CCEK) {
Richard Smith51201882011-12-30 21:15:51 +00005616 if (!CheckLiteralType(Info, E))
5617 return false;
5618
5619 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005620 // Evaluate arrays and record types in-place, so that later initializers can
5621 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005622 if (E->getType()->isArrayType())
5623 return EvaluateArray(E, This, Result, Info);
5624 else if (E->getType()->isRecordType())
5625 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005626 }
5627
5628 // For any other type, in-place evaluation is unimportant.
5629 CCValue CoreConstResult;
5630 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005631 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005632}
5633
Richard Smithf48fdb02011-12-09 22:58:01 +00005634/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5635/// lvalue-to-rvalue cast if it is an lvalue.
5636static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005637 if (!CheckLiteralType(Info, E))
5638 return false;
5639
Richard Smithf48fdb02011-12-09 22:58:01 +00005640 CCValue Value;
5641 if (!::Evaluate(Value, Info, E))
5642 return false;
5643
5644 if (E->isGLValue()) {
5645 LValue LV;
5646 LV.setFrom(Value);
5647 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5648 return false;
5649 }
5650
5651 // Check this core constant expression is a constant expression, and if so,
5652 // convert it to one.
5653 return CheckConstantExpression(Info, E, Value, Result);
5654}
Richard Smithc49bd112011-10-28 17:51:58 +00005655
Richard Smith51f47082011-10-29 00:50:52 +00005656/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005657/// any crazy technique (that has nothing to do with language standards) that
5658/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005659/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5660/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005661bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005662 // Fast-path evaluations of integer literals, since we sometimes see files
5663 // containing vast quantities of these.
5664 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5665 Result.Val = APValue(APSInt(L->getValue(),
5666 L->getType()->isUnsignedIntegerType()));
5667 return true;
5668 }
5669
Richard Smith2d6a5672012-01-14 04:30:29 +00005670 // FIXME: Evaluating values of large array and record types can cause
5671 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005672 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5673 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005674 return false;
5675
Richard Smithf48fdb02011-12-09 22:58:01 +00005676 EvalInfo Info(Ctx, Result);
5677 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005678}
5679
Jay Foad4ba2a172011-01-12 09:06:06 +00005680bool Expr::EvaluateAsBooleanCondition(bool &Result,
5681 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005682 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005683 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00005684 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5685 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005686 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005687}
5688
Richard Smith80d4b552011-12-28 19:48:30 +00005689bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5690 SideEffectsKind AllowSideEffects) const {
5691 if (!getType()->isIntegralOrEnumerationType())
5692 return false;
5693
Richard Smithc49bd112011-10-28 17:51:58 +00005694 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00005695 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5696 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00005697 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005698
Richard Smithc49bd112011-10-28 17:51:58 +00005699 Result = ExprResult.Val.getInt();
5700 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005701}
5702
Jay Foad4ba2a172011-01-12 09:06:06 +00005703bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005704 EvalInfo Info(Ctx, Result);
5705
John McCallefdb83e2010-05-07 21:00:08 +00005706 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005707 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005708 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5709 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005710}
5711
Richard Smith099e7f62011-12-19 06:19:21 +00005712bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5713 const VarDecl *VD,
5714 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00005715 // FIXME: Evaluating initializers for large array and record types can cause
5716 // performance problems. Only do so in C++11 for now.
5717 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5718 !Ctx.getLangOptions().CPlusPlus0x)
5719 return false;
5720
Richard Smith099e7f62011-12-19 06:19:21 +00005721 Expr::EvalStatus EStatus;
5722 EStatus.Diag = &Notes;
5723
5724 EvalInfo InitInfo(Ctx, EStatus);
5725 InitInfo.setEvaluatingDecl(VD, Value);
5726
Richard Smith51201882011-12-30 21:15:51 +00005727 if (!CheckLiteralType(InitInfo, this))
5728 return false;
5729
Richard Smith099e7f62011-12-19 06:19:21 +00005730 LValue LVal;
5731 LVal.set(VD);
5732
Richard Smith51201882011-12-30 21:15:51 +00005733 // C++11 [basic.start.init]p2:
5734 // Variables with static storage duration or thread storage duration shall be
5735 // zero-initialized before any other initialization takes place.
5736 // This behavior is not present in C.
5737 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5738 !VD->getType()->isReferenceType()) {
5739 ImplicitValueInitExpr VIE(VD->getType());
5740 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5741 return false;
5742 }
5743
Richard Smith099e7f62011-12-19 06:19:21 +00005744 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5745 !EStatus.HasSideEffects;
5746}
5747
Richard Smith51f47082011-10-29 00:50:52 +00005748/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5749/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005750bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005751 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005752 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005753}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005754
Jay Foad4ba2a172011-01-12 09:06:06 +00005755bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005756 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005757}
5758
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005759APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005760 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005761 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005762 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005763 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005764 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005765
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005766 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005767}
John McCalld905f5a2010-05-07 05:32:02 +00005768
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005769 bool Expr::EvalResult::isGlobalLValue() const {
5770 assert(Val.isLValue());
5771 return IsGlobalLValue(Val.getLValueBase());
5772 }
5773
5774
John McCalld905f5a2010-05-07 05:32:02 +00005775/// isIntegerConstantExpr - this recursive routine will test if an expression is
5776/// an integer constant expression.
5777
5778/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5779/// comma, etc
5780///
5781/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5782/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5783/// cast+dereference.
5784
5785// CheckICE - This function does the fundamental ICE checking: the returned
5786// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5787// Note that to reduce code duplication, this helper does no evaluation
5788// itself; the caller checks whether the expression is evaluatable, and
5789// in the rare cases where CheckICE actually cares about the evaluated
5790// value, it calls into Evalute.
5791//
5792// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005793// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005794// 1: This expression is not an ICE, but if it isn't evaluated, it's
5795// a legal subexpression for an ICE. This return value is used to handle
5796// the comma operator in C99 mode.
5797// 2: This expression is not an ICE, and is not a legal subexpression for one.
5798
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005799namespace {
5800
John McCalld905f5a2010-05-07 05:32:02 +00005801struct ICEDiag {
5802 unsigned Val;
5803 SourceLocation Loc;
5804
5805 public:
5806 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5807 ICEDiag() : Val(0) {}
5808};
5809
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005810}
5811
5812static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00005813
5814static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5815 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005816 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005817 !EVResult.Val.isInt()) {
5818 return ICEDiag(2, E->getLocStart());
5819 }
5820 return NoDiag();
5821}
5822
5823static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5824 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005825 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00005826 return ICEDiag(2, E->getLocStart());
5827 }
5828
5829 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00005830#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00005831#define STMT(Node, Base) case Expr::Node##Class:
5832#define EXPR(Node, Base)
5833#include "clang/AST/StmtNodes.inc"
5834 case Expr::PredefinedExprClass:
5835 case Expr::FloatingLiteralClass:
5836 case Expr::ImaginaryLiteralClass:
5837 case Expr::StringLiteralClass:
5838 case Expr::ArraySubscriptExprClass:
5839 case Expr::MemberExprClass:
5840 case Expr::CompoundAssignOperatorClass:
5841 case Expr::CompoundLiteralExprClass:
5842 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005843 case Expr::DesignatedInitExprClass:
5844 case Expr::ImplicitValueInitExprClass:
5845 case Expr::ParenListExprClass:
5846 case Expr::VAArgExprClass:
5847 case Expr::AddrLabelExprClass:
5848 case Expr::StmtExprClass:
5849 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00005850 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005851 case Expr::CXXDynamicCastExprClass:
5852 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00005853 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005854 case Expr::CXXNullPtrLiteralExprClass:
5855 case Expr::CXXThisExprClass:
5856 case Expr::CXXThrowExprClass:
5857 case Expr::CXXNewExprClass:
5858 case Expr::CXXDeleteExprClass:
5859 case Expr::CXXPseudoDestructorExprClass:
5860 case Expr::UnresolvedLookupExprClass:
5861 case Expr::DependentScopeDeclRefExprClass:
5862 case Expr::CXXConstructExprClass:
5863 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00005864 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00005865 case Expr::CXXTemporaryObjectExprClass:
5866 case Expr::CXXUnresolvedConstructExprClass:
5867 case Expr::CXXDependentScopeMemberExprClass:
5868 case Expr::UnresolvedMemberExprClass:
5869 case Expr::ObjCStringLiteralClass:
5870 case Expr::ObjCEncodeExprClass:
5871 case Expr::ObjCMessageExprClass:
5872 case Expr::ObjCSelectorExprClass:
5873 case Expr::ObjCProtocolExprClass:
5874 case Expr::ObjCIvarRefExprClass:
5875 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005876 case Expr::ObjCIsaExprClass:
5877 case Expr::ShuffleVectorExprClass:
5878 case Expr::BlockExprClass:
5879 case Expr::BlockDeclRefExprClass:
5880 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00005881 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00005882 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00005883 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005884 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005885 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00005886 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00005887 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00005888 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005889 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005890 return ICEDiag(2, E->getLocStart());
5891
Douglas Gregoree8aff02011-01-04 17:33:58 +00005892 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005893 case Expr::GNUNullExprClass:
5894 // GCC considers the GNU __null value to be an integral constant expression.
5895 return NoDiag();
5896
John McCall91a57552011-07-15 05:09:51 +00005897 case Expr::SubstNonTypeTemplateParmExprClass:
5898 return
5899 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5900
John McCalld905f5a2010-05-07 05:32:02 +00005901 case Expr::ParenExprClass:
5902 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00005903 case Expr::GenericSelectionExprClass:
5904 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005905 case Expr::IntegerLiteralClass:
5906 case Expr::CharacterLiteralClass:
5907 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00005908 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005909 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00005910 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00005911 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00005912 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00005913 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005914 return NoDiag();
5915 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00005916 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00005917 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5918 // constant expressions, but they can never be ICEs because an ICE cannot
5919 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00005920 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00005921 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00005922 return CheckEvalInICE(E, Ctx);
5923 return ICEDiag(2, E->getLocStart());
5924 }
5925 case Expr::DeclRefExprClass:
5926 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5927 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00005928 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00005929 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5930
5931 // Parameter variables are never constants. Without this check,
5932 // getAnyInitializer() can find a default argument, which leads
5933 // to chaos.
5934 if (isa<ParmVarDecl>(D))
5935 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5936
5937 // C++ 7.1.5.1p2
5938 // A variable of non-volatile const-qualified integral or enumeration
5939 // type initialized by an ICE can be used in ICEs.
5940 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00005941 if (!Dcl->getType()->isIntegralOrEnumerationType())
5942 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5943
Richard Smith099e7f62011-12-19 06:19:21 +00005944 const VarDecl *VD;
5945 // Look for a declaration of this variable that has an initializer, and
5946 // check whether it is an ICE.
5947 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5948 return NoDiag();
5949 else
5950 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00005951 }
5952 }
5953 return ICEDiag(2, E->getLocStart());
5954 case Expr::UnaryOperatorClass: {
5955 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5956 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005957 case UO_PostInc:
5958 case UO_PostDec:
5959 case UO_PreInc:
5960 case UO_PreDec:
5961 case UO_AddrOf:
5962 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00005963 // C99 6.6/3 allows increment and decrement within unevaluated
5964 // subexpressions of constant expressions, but they can never be ICEs
5965 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005966 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00005967 case UO_Extension:
5968 case UO_LNot:
5969 case UO_Plus:
5970 case UO_Minus:
5971 case UO_Not:
5972 case UO_Real:
5973 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00005974 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005975 }
5976
5977 // OffsetOf falls through here.
5978 }
5979 case Expr::OffsetOfExprClass: {
5980 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00005981 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00005982 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00005983 // compliance: we should warn earlier for offsetof expressions with
5984 // array subscripts that aren't ICEs, and if the array subscripts
5985 // are ICEs, the value of the offsetof must be an integer constant.
5986 return CheckEvalInICE(E, Ctx);
5987 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005988 case Expr::UnaryExprOrTypeTraitExprClass: {
5989 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5990 if ((Exp->getKind() == UETT_SizeOf) &&
5991 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00005992 return ICEDiag(2, E->getLocStart());
5993 return NoDiag();
5994 }
5995 case Expr::BinaryOperatorClass: {
5996 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5997 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005998 case BO_PtrMemD:
5999 case BO_PtrMemI:
6000 case BO_Assign:
6001 case BO_MulAssign:
6002 case BO_DivAssign:
6003 case BO_RemAssign:
6004 case BO_AddAssign:
6005 case BO_SubAssign:
6006 case BO_ShlAssign:
6007 case BO_ShrAssign:
6008 case BO_AndAssign:
6009 case BO_XorAssign:
6010 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006011 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6012 // constant expressions, but they can never be ICEs because an ICE cannot
6013 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006014 return ICEDiag(2, E->getLocStart());
6015
John McCall2de56d12010-08-25 11:45:40 +00006016 case BO_Mul:
6017 case BO_Div:
6018 case BO_Rem:
6019 case BO_Add:
6020 case BO_Sub:
6021 case BO_Shl:
6022 case BO_Shr:
6023 case BO_LT:
6024 case BO_GT:
6025 case BO_LE:
6026 case BO_GE:
6027 case BO_EQ:
6028 case BO_NE:
6029 case BO_And:
6030 case BO_Xor:
6031 case BO_Or:
6032 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006033 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6034 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006035 if (Exp->getOpcode() == BO_Div ||
6036 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006037 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006038 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006039 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006040 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006041 if (REval == 0)
6042 return ICEDiag(1, E->getLocStart());
6043 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006044 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006045 if (LEval.isMinSignedValue())
6046 return ICEDiag(1, E->getLocStart());
6047 }
6048 }
6049 }
John McCall2de56d12010-08-25 11:45:40 +00006050 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006051 if (Ctx.getLangOptions().C99) {
6052 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6053 // if it isn't evaluated.
6054 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6055 return ICEDiag(1, E->getLocStart());
6056 } else {
6057 // In both C89 and C++, commas in ICEs are illegal.
6058 return ICEDiag(2, E->getLocStart());
6059 }
6060 }
6061 if (LHSResult.Val >= RHSResult.Val)
6062 return LHSResult;
6063 return RHSResult;
6064 }
John McCall2de56d12010-08-25 11:45:40 +00006065 case BO_LAnd:
6066 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006067 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6068 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6069 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6070 // Rare case where the RHS has a comma "side-effect"; we need
6071 // to actually check the condition to see whether the side
6072 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006073 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006074 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006075 return RHSResult;
6076 return NoDiag();
6077 }
6078
6079 if (LHSResult.Val >= RHSResult.Val)
6080 return LHSResult;
6081 return RHSResult;
6082 }
6083 }
6084 }
6085 case Expr::ImplicitCastExprClass:
6086 case Expr::CStyleCastExprClass:
6087 case Expr::CXXFunctionalCastExprClass:
6088 case Expr::CXXStaticCastExprClass:
6089 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006090 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006091 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006092 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006093 if (isa<ExplicitCastExpr>(E)) {
6094 if (const FloatingLiteral *FL
6095 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6096 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6097 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6098 APSInt IgnoredVal(DestWidth, !DestSigned);
6099 bool Ignored;
6100 // If the value does not fit in the destination type, the behavior is
6101 // undefined, so we are not required to treat it as a constant
6102 // expression.
6103 if (FL->getValue().convertToInteger(IgnoredVal,
6104 llvm::APFloat::rmTowardZero,
6105 &Ignored) & APFloat::opInvalidOp)
6106 return ICEDiag(2, E->getLocStart());
6107 return NoDiag();
6108 }
6109 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006110 switch (cast<CastExpr>(E)->getCastKind()) {
6111 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006112 case CK_AtomicToNonAtomic:
6113 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006114 case CK_NoOp:
6115 case CK_IntegralToBoolean:
6116 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006117 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006118 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006119 return ICEDiag(2, E->getLocStart());
6120 }
John McCalld905f5a2010-05-07 05:32:02 +00006121 }
John McCall56ca35d2011-02-17 10:25:35 +00006122 case Expr::BinaryConditionalOperatorClass: {
6123 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6124 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6125 if (CommonResult.Val == 2) return CommonResult;
6126 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6127 if (FalseResult.Val == 2) return FalseResult;
6128 if (CommonResult.Val == 1) return CommonResult;
6129 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006130 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006131 return FalseResult;
6132 }
John McCalld905f5a2010-05-07 05:32:02 +00006133 case Expr::ConditionalOperatorClass: {
6134 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6135 // If the condition (ignoring parens) is a __builtin_constant_p call,
6136 // then only the true side is actually considered in an integer constant
6137 // expression, and it is fully evaluated. This is an important GNU
6138 // extension. See GCC PR38377 for discussion.
6139 if (const CallExpr *CallCE
6140 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006141 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6142 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006143 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006144 if (CondResult.Val == 2)
6145 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006146
Richard Smithf48fdb02011-12-09 22:58:01 +00006147 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6148 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006149
John McCalld905f5a2010-05-07 05:32:02 +00006150 if (TrueResult.Val == 2)
6151 return TrueResult;
6152 if (FalseResult.Val == 2)
6153 return FalseResult;
6154 if (CondResult.Val == 1)
6155 return CondResult;
6156 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6157 return NoDiag();
6158 // Rare case where the diagnostics depend on which side is evaluated
6159 // Note that if we get here, CondResult is 0, and at least one of
6160 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006161 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006162 return FalseResult;
6163 }
6164 return TrueResult;
6165 }
6166 case Expr::CXXDefaultArgExprClass:
6167 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6168 case Expr::ChooseExprClass: {
6169 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6170 }
6171 }
6172
David Blaikie30263482012-01-20 21:50:17 +00006173 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006174}
6175
Richard Smithf48fdb02011-12-09 22:58:01 +00006176/// Evaluate an expression as a C++11 integral constant expression.
6177static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6178 const Expr *E,
6179 llvm::APSInt *Value,
6180 SourceLocation *Loc) {
6181 if (!E->getType()->isIntegralOrEnumerationType()) {
6182 if (Loc) *Loc = E->getExprLoc();
6183 return false;
6184 }
6185
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006186 APValue Result;
6187 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006188 return false;
6189
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006190 assert(Result.isInt() && "pointer cast to int is not an ICE");
6191 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006192 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006193}
6194
Richard Smithdd1f29b2011-12-12 09:28:41 +00006195bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006196 if (Ctx.getLangOptions().CPlusPlus0x)
6197 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6198
John McCalld905f5a2010-05-07 05:32:02 +00006199 ICEDiag d = CheckICE(this, Ctx);
6200 if (d.Val != 0) {
6201 if (Loc) *Loc = d.Loc;
6202 return false;
6203 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006204 return true;
6205}
6206
6207bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6208 SourceLocation *Loc, bool isEvaluated) const {
6209 if (Ctx.getLangOptions().CPlusPlus0x)
6210 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6211
6212 if (!isIntegerConstantExpr(Ctx, Loc))
6213 return false;
6214 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006215 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006216 return true;
6217}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006218
6219bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6220 SourceLocation *Loc) const {
6221 // We support this checking in C++98 mode in order to diagnose compatibility
6222 // issues.
6223 assert(Ctx.getLangOptions().CPlusPlus);
6224
6225 Expr::EvalStatus Status;
6226 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6227 Status.Diag = &Diags;
6228 EvalInfo Info(Ctx, Status);
6229
6230 APValue Scratch;
6231 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6232
6233 if (!Diags.empty()) {
6234 IsConstExpr = false;
6235 if (Loc) *Loc = Diags[0].first;
6236 } else if (!IsConstExpr) {
6237 // FIXME: This shouldn't happen.
6238 if (Loc) *Loc = getExprLoc();
6239 }
6240
6241 return IsConstExpr;
6242}
Richard Smith745f5142012-01-27 01:14:48 +00006243
6244bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6245 llvm::SmallVectorImpl<
6246 PartialDiagnosticAt> &Diags) {
6247 // FIXME: It would be useful to check constexpr function templates, but at the
6248 // moment the constant expression evaluator cannot cope with the non-rigorous
6249 // ASTs which we build for dependent expressions.
6250 if (FD->isDependentContext())
6251 return true;
6252
6253 Expr::EvalStatus Status;
6254 Status.Diag = &Diags;
6255
6256 EvalInfo Info(FD->getASTContext(), Status);
6257 Info.CheckingPotentialConstantExpression = true;
6258
6259 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6260 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6261
6262 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6263 // is a temporary being used as the 'this' pointer.
6264 LValue This;
6265 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6266 This.set(&VIE, Info.CurrentCall);
6267
6268 APValue Scratch;
6269 ArrayRef<const Expr*> Args;
6270
6271 SourceLocation Loc = FD->getLocation();
6272
6273 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
6274 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6275 } else
6276 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6277 Args, FD->getBody(), Info, Scratch);
6278
6279 return Diags.empty();
6280}