blob: 8897667592b07293ac986e75053dd54f57564fdc [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 {
130 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex
131 };
132
Richard Smith0a3bdb62011-11-04 02:25:55 +0000133 /// A path from a glvalue to a subobject of that glvalue.
134 struct SubobjectDesignator {
135 /// True if the subobject was named in a manner not supported by C++11. Such
136 /// lvalues can still be folded, but they are not core constant expressions
137 /// and we cannot perform lvalue-to-rvalue conversions on them.
138 bool Invalid : 1;
139
Richard Smithb4e85ed2012-01-06 16:39:00 +0000140 /// Is this a pointer one past the end of an object?
141 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000142
Richard Smithb4e85ed2012-01-06 16:39:00 +0000143 /// The length of the path to the most-derived object of which this is a
144 /// subobject.
145 unsigned MostDerivedPathLength : 30;
146
147 /// The size of the array of which the most-derived object is an element, or
148 /// 0 if the most-derived object is not an array element.
149 uint64_t MostDerivedArraySize;
150
151 /// The type of the most derived object referred to by this address.
152 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000153
Richard Smith9a17a682011-11-07 05:07:52 +0000154 typedef APValue::LValuePathEntry PathEntry;
155
Richard Smith0a3bdb62011-11-04 02:25:55 +0000156 /// The entries on the path from the glvalue to the designated subobject.
157 SmallVector<PathEntry, 8> Entries;
158
Richard Smithb4e85ed2012-01-06 16:39:00 +0000159 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000160
Richard Smithb4e85ed2012-01-06 16:39:00 +0000161 explicit SubobjectDesignator(QualType T)
162 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
163 MostDerivedArraySize(0), MostDerivedType(T) {}
164
165 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
166 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
167 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000168 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000169 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000170 ArrayRef<PathEntry> VEntries = V.getLValuePath();
171 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
172 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000173 MostDerivedPathLength =
174 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
175 V.getLValuePath(), MostDerivedArraySize,
176 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000177 }
178 }
179
Richard Smith0a3bdb62011-11-04 02:25:55 +0000180 void setInvalid() {
181 Invalid = true;
182 Entries.clear();
183 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000184
185 /// Determine whether this is a one-past-the-end pointer.
186 bool isOnePastTheEnd() const {
187 if (IsOnePastTheEnd)
188 return true;
189 if (MostDerivedArraySize &&
190 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
191 return true;
192 return false;
193 }
194
195 /// Check that this refers to a valid subobject.
196 bool isValidSubobject() const {
197 if (Invalid)
198 return false;
199 return !isOnePastTheEnd();
200 }
201 /// Check that this refers to a valid subobject, and if not, produce a
202 /// relevant diagnostic and set the designator as invalid.
203 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
204
205 /// Update this designator to refer to the first element within this array.
206 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000207 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000208 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000209 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000210
211 // This is a most-derived object.
212 MostDerivedType = CAT->getElementType();
213 MostDerivedArraySize = CAT->getSize().getZExtValue();
214 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000215 }
216 /// Update this designator to refer to the given base or member of this
217 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000218 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000219 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000220 APValue::BaseOrMemberType Value(D, Virtual);
221 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000222 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000223
224 // If this isn't a base class, it's a new most-derived object.
225 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
226 MostDerivedType = FD->getType();
227 MostDerivedArraySize = 0;
228 MostDerivedPathLength = Entries.size();
229 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000230 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000231 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000232 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000233 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000234 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000235 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000236 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000237 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
238 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
239 setInvalid();
240 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000241 return;
242 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000243 // [expr.add]p4: For the purposes of these operators, a pointer to a
244 // nonarray object behaves the same as a pointer to the first element of
245 // an array of length one with the type of the object as its element type.
246 if (IsOnePastTheEnd && N == (uint64_t)-1)
247 IsOnePastTheEnd = false;
248 else if (!IsOnePastTheEnd && N == 1)
249 IsOnePastTheEnd = true;
250 else if (N != 0) {
251 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000252 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000253 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000254 }
255 };
256
Richard Smith47a1eed2011-10-29 20:57:55 +0000257 /// A core constant value. This can be the value of any constant expression,
258 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000259 ///
260 /// For an LValue, the base and offset are stored in the APValue subobject,
261 /// but the other information is stored in the SubobjectDesignator. For all
262 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000263 class CCValue : public APValue {
264 typedef llvm::APSInt APSInt;
265 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000266 /// If the value is a reference or pointer into a parameter or temporary,
267 /// this is the corresponding call stack frame.
268 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000269 /// If the value is a reference or pointer, this is a description of how the
270 /// subobject was specified.
271 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000272 public:
Richard Smith177dce72011-11-01 16:57:24 +0000273 struct GlobalValue {};
274
Richard Smith47a1eed2011-10-29 20:57:55 +0000275 CCValue() {}
276 explicit CCValue(const APSInt &I) : APValue(I) {}
277 explicit CCValue(const APFloat &F) : APValue(F) {}
278 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
279 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
280 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000281 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000282 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000283 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000284 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000285 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
286 APValue(V), CallFrame(0), Designator(Ctx, V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000287 CCValue(const ValueDecl *D, bool IsDerivedMember,
288 ArrayRef<const CXXRecordDecl*> Path) :
289 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000290 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
291 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000292
Richard Smith177dce72011-11-01 16:57:24 +0000293 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000294 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000295 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000296 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000297 SubobjectDesignator &getLValueDesignator() {
298 assert(getKind() == LValue);
299 return Designator;
300 }
301 const SubobjectDesignator &getLValueDesignator() const {
302 return const_cast<CCValue*>(this)->getLValueDesignator();
303 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000304 };
305
Richard Smithd0dccea2011-10-28 22:34:42 +0000306 /// A stack frame in the constexpr call stack.
307 struct CallStackFrame {
308 EvalInfo &Info;
309
310 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000311 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000312
Richard Smith08d6e032011-12-16 19:06:07 +0000313 /// CallLoc - The location of the call expression for this call.
314 SourceLocation CallLoc;
315
316 /// Callee - The function which was called.
317 const FunctionDecl *Callee;
318
Richard Smith180f4792011-11-10 06:34:14 +0000319 /// This - The binding for the this pointer in this call, if any.
320 const LValue *This;
321
Richard Smithd0dccea2011-10-28 22:34:42 +0000322 /// ParmBindings - Parameter bindings for this function call, indexed by
323 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000324 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000325
Richard Smithbd552ef2011-10-31 05:52:43 +0000326 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
327 typedef MapTy::const_iterator temp_iterator;
328 /// Temporaries - Temporary lvalues materialized within this stack frame.
329 MapTy Temporaries;
330
Richard Smith08d6e032011-12-16 19:06:07 +0000331 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
332 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000333 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000334 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000335 };
336
Richard Smithdd1f29b2011-12-12 09:28:41 +0000337 /// A partial diagnostic which we might know in advance that we are not going
338 /// to emit.
339 class OptionalDiagnostic {
340 PartialDiagnostic *Diag;
341
342 public:
343 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
344
345 template<typename T>
346 OptionalDiagnostic &operator<<(const T &v) {
347 if (Diag)
348 *Diag << v;
349 return *this;
350 }
Richard Smith789f9b62012-01-31 04:08:20 +0000351
352 OptionalDiagnostic &operator<<(const APSInt &I) {
353 if (Diag) {
354 llvm::SmallVector<char, 32> Buffer;
355 I.toString(Buffer);
356 *Diag << StringRef(Buffer.data(), Buffer.size());
357 }
358 return *this;
359 }
360
361 OptionalDiagnostic &operator<<(const APFloat &F) {
362 if (Diag) {
363 llvm::SmallVector<char, 32> Buffer;
364 F.toString(Buffer);
365 *Diag << StringRef(Buffer.data(), Buffer.size());
366 }
367 return *this;
368 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000369 };
370
Richard Smithbd552ef2011-10-31 05:52:43 +0000371 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000372 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000373
374 /// EvalStatus - Contains information about the evaluation.
375 Expr::EvalStatus &EvalStatus;
376
377 /// CurrentCall - The top of the constexpr call stack.
378 CallStackFrame *CurrentCall;
379
Richard Smithbd552ef2011-10-31 05:52:43 +0000380 /// CallStackDepth - The number of calls in the call stack right now.
381 unsigned CallStackDepth;
382
383 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
384 /// OpaqueValues - Values used as the common expression in a
385 /// BinaryConditionalOperator.
386 MapTy OpaqueValues;
387
388 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000389 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000390 CallStackFrame BottomFrame;
391
Richard Smith180f4792011-11-10 06:34:14 +0000392 /// EvaluatingDecl - This is the declaration whose initializer is being
393 /// evaluated, if any.
394 const VarDecl *EvaluatingDecl;
395
396 /// EvaluatingDeclValue - This is the value being constructed for the
397 /// declaration whose initializer is being evaluated, if any.
398 APValue *EvaluatingDeclValue;
399
Richard Smithc1c5f272011-12-13 06:39:58 +0000400 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
401 /// notes attached to it will also be stored, otherwise they will not be.
402 bool HasActiveDiagnostic;
403
Richard Smith745f5142012-01-27 01:14:48 +0000404 /// CheckingPotentialConstantExpression - Are we checking whether the
405 /// expression is a potential constant expression? If so, some diagnostics
406 /// are suppressed.
407 bool CheckingPotentialConstantExpression;
408
Richard Smithbd552ef2011-10-31 05:52:43 +0000409
410 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000411 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith08d6e032011-12-16 19:06:07 +0000412 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000413 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
414 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000415
Richard Smithbd552ef2011-10-31 05:52:43 +0000416 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
417 MapTy::const_iterator i = OpaqueValues.find(e);
418 if (i == OpaqueValues.end()) return 0;
419 return &i->second;
420 }
421
Richard Smith180f4792011-11-10 06:34:14 +0000422 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
423 EvaluatingDecl = VD;
424 EvaluatingDeclValue = &Value;
425 }
426
Richard Smithc18c4232011-11-21 19:36:32 +0000427 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
428
Richard Smithc1c5f272011-12-13 06:39:58 +0000429 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000430 // Don't perform any constexpr calls (other than the call we're checking)
431 // when checking a potential constant expression.
432 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
433 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +0000434 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
435 return true;
436 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
437 << getLangOpts().ConstexprCallDepth;
438 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000439 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000440
Richard Smithc1c5f272011-12-13 06:39:58 +0000441 private:
442 /// Add a diagnostic to the diagnostics list.
443 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
444 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
445 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
446 return EvalStatus.Diag->back().second;
447 }
448
Richard Smith08d6e032011-12-16 19:06:07 +0000449 /// Add notes containing a call stack to the current point of evaluation.
450 void addCallStack(unsigned Limit);
451
Richard Smithc1c5f272011-12-13 06:39:58 +0000452 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000453 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000454 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
455 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000456 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000457 // If we have a prior diagnostic, it will be noting that the expression
458 // isn't a constant expression. This diagnostic is more important.
459 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000460 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000461 unsigned CallStackNotes = CallStackDepth - 1;
462 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
463 if (Limit)
464 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000465 if (CheckingPotentialConstantExpression)
466 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000467
Richard Smithc1c5f272011-12-13 06:39:58 +0000468 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000469 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000470 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
471 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000472 if (!CheckingPotentialConstantExpression)
473 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000474 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000475 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000476 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000477 return OptionalDiagnostic();
478 }
479
480 /// Diagnose that the evaluation does not produce a C++11 core constant
481 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000482 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
483 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000484 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000485 // Don't override a previous diagnostic.
486 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
487 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000488 return Diag(Loc, DiagId, ExtraNotes);
489 }
490
491 /// Add a note to a prior diagnostic.
492 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
493 if (!HasActiveDiagnostic)
494 return OptionalDiagnostic();
495 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000496 }
Richard Smith099e7f62011-12-19 06:19:21 +0000497
498 /// Add a stack of notes to a prior diagnostic.
499 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
500 if (HasActiveDiagnostic) {
501 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
502 Diags.begin(), Diags.end());
503 }
504 }
Richard Smith745f5142012-01-27 01:14:48 +0000505
506 /// Should we continue evaluation as much as possible after encountering a
507 /// construct which can't be folded?
508 bool keepEvaluatingAfterFailure() {
509 return CheckingPotentialConstantExpression && EvalStatus.Diag->empty();
510 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000511 };
Richard Smith08d6e032011-12-16 19:06:07 +0000512}
Richard Smithbd552ef2011-10-31 05:52:43 +0000513
Richard Smithb4e85ed2012-01-06 16:39:00 +0000514bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
515 CheckSubobjectKind CSK) {
516 if (Invalid)
517 return false;
518 if (isOnePastTheEnd()) {
519 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
520 << CSK;
521 setInvalid();
522 return false;
523 }
524 return true;
525}
526
527void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
528 const Expr *E, uint64_t N) {
529 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
530 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
531 << static_cast<int>(N) << /*array*/ 0
532 << static_cast<unsigned>(MostDerivedArraySize);
533 else
534 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
535 << static_cast<int>(N) << /*non-array*/ 1;
536 setInvalid();
537}
538
Richard Smith08d6e032011-12-16 19:06:07 +0000539CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
540 const FunctionDecl *Callee, const LValue *This,
541 const CCValue *Arguments)
542 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
543 This(This), Arguments(Arguments) {
544 Info.CurrentCall = this;
545 ++Info.CallStackDepth;
546}
547
548CallStackFrame::~CallStackFrame() {
549 assert(Info.CurrentCall == this && "calls retired out of order");
550 --Info.CallStackDepth;
551 Info.CurrentCall = Caller;
552}
553
554/// Produce a string describing the given constexpr call.
555static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
556 unsigned ArgIndex = 0;
557 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
558 !isa<CXXConstructorDecl>(Frame->Callee);
559
560 if (!IsMemberCall)
561 Out << *Frame->Callee << '(';
562
563 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
564 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000565 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000566 Out << ", ";
567
568 const ParmVarDecl *Param = *I;
569 const CCValue &Arg = Frame->Arguments[ArgIndex];
570 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
571 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
572 else {
573 // Deliberately slice off the frame to form an APValue we can print.
574 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
575 Arg.getLValueDesignator().Entries,
Richard Smithb4e85ed2012-01-06 16:39:00 +0000576 Arg.getLValueDesignator().IsOnePastTheEnd);
Richard Smith08d6e032011-12-16 19:06:07 +0000577 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
578 }
579
580 if (ArgIndex == 0 && IsMemberCall)
581 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000582 }
583
Richard Smith08d6e032011-12-16 19:06:07 +0000584 Out << ')';
585}
586
587void EvalInfo::addCallStack(unsigned Limit) {
588 // Determine which calls to skip, if any.
589 unsigned ActiveCalls = CallStackDepth - 1;
590 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
591 if (Limit && Limit < ActiveCalls) {
592 SkipStart = Limit / 2 + Limit % 2;
593 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000594 }
595
Richard Smith08d6e032011-12-16 19:06:07 +0000596 // Walk the call stack and add the diagnostics.
597 unsigned CallIdx = 0;
598 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
599 Frame = Frame->Caller, ++CallIdx) {
600 // Skip this call?
601 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
602 if (CallIdx == SkipStart) {
603 // Note that we're skipping calls.
604 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
605 << unsigned(ActiveCalls - Limit);
606 }
607 continue;
608 }
609
610 llvm::SmallVector<char, 128> Buffer;
611 llvm::raw_svector_ostream Out(Buffer);
612 describeCall(Frame, Out);
613 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
614 }
615}
616
617namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000618 struct ComplexValue {
619 private:
620 bool IsInt;
621
622 public:
623 APSInt IntReal, IntImag;
624 APFloat FloatReal, FloatImag;
625
626 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
627
628 void makeComplexFloat() { IsInt = false; }
629 bool isComplexFloat() const { return !IsInt; }
630 APFloat &getComplexFloatReal() { return FloatReal; }
631 APFloat &getComplexFloatImag() { return FloatImag; }
632
633 void makeComplexInt() { IsInt = true; }
634 bool isComplexInt() const { return IsInt; }
635 APSInt &getComplexIntReal() { return IntReal; }
636 APSInt &getComplexIntImag() { return IntImag; }
637
Richard Smith47a1eed2011-10-29 20:57:55 +0000638 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000639 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000640 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000641 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000642 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000643 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000644 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000645 assert(v.isComplexFloat() || v.isComplexInt());
646 if (v.isComplexFloat()) {
647 makeComplexFloat();
648 FloatReal = v.getComplexFloatReal();
649 FloatImag = v.getComplexFloatImag();
650 } else {
651 makeComplexInt();
652 IntReal = v.getComplexIntReal();
653 IntImag = v.getComplexIntImag();
654 }
655 }
John McCallf4cf1a12010-05-07 17:22:02 +0000656 };
John McCallefdb83e2010-05-07 21:00:08 +0000657
658 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000659 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000660 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000661 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000662 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000663
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000664 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000665 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000666 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000667 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000668 SubobjectDesignator &getLValueDesignator() { return Designator; }
669 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000670
Richard Smith47a1eed2011-10-29 20:57:55 +0000671 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000672 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000673 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000674 void setFrom(const CCValue &V) {
675 assert(V.isLValue());
676 Base = V.getLValueBase();
677 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000678 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000679 Designator = V.getLValueDesignator();
680 }
681
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000682 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
683 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000684 Offset = CharUnits::Zero();
685 Frame = F;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000686 Designator = SubobjectDesignator(getType(B));
687 }
688
689 // Check that this LValue is not based on a null pointer. If it is, produce
690 // a diagnostic and mark the designator as invalid.
691 bool checkNullPointer(EvalInfo &Info, const Expr *E,
692 CheckSubobjectKind CSK) {
693 if (Designator.Invalid)
694 return false;
695 if (!Base) {
696 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
697 << CSK;
698 Designator.setInvalid();
699 return false;
700 }
701 return true;
702 }
703
704 // Check this LValue refers to an object. If not, set the designator to be
705 // invalid and emit a diagnostic.
706 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
707 return checkNullPointer(Info, E, CSK) &&
708 Designator.checkSubobject(Info, E, CSK);
709 }
710
711 void addDecl(EvalInfo &Info, const Expr *E,
712 const Decl *D, bool Virtual = false) {
713 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
714 Designator.addDeclUnchecked(D, Virtual);
715 }
716 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
717 checkSubobject(Info, E, CSK_ArrayToPointer);
718 Designator.addArrayUnchecked(CAT);
719 }
720 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
721 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
722 return;
723 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000724 }
John McCallefdb83e2010-05-07 21:00:08 +0000725 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000726
727 struct MemberPtr {
728 MemberPtr() {}
729 explicit MemberPtr(const ValueDecl *Decl) :
730 DeclAndIsDerivedMember(Decl, false), Path() {}
731
732 /// The member or (direct or indirect) field referred to by this member
733 /// pointer, or 0 if this is a null member pointer.
734 const ValueDecl *getDecl() const {
735 return DeclAndIsDerivedMember.getPointer();
736 }
737 /// Is this actually a member of some type derived from the relevant class?
738 bool isDerivedMember() const {
739 return DeclAndIsDerivedMember.getInt();
740 }
741 /// Get the class which the declaration actually lives in.
742 const CXXRecordDecl *getContainingRecord() const {
743 return cast<CXXRecordDecl>(
744 DeclAndIsDerivedMember.getPointer()->getDeclContext());
745 }
746
747 void moveInto(CCValue &V) const {
748 V = CCValue(getDecl(), isDerivedMember(), Path);
749 }
750 void setFrom(const CCValue &V) {
751 assert(V.isMemberPointer());
752 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
753 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
754 Path.clear();
755 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
756 Path.insert(Path.end(), P.begin(), P.end());
757 }
758
759 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
760 /// whether the member is a member of some class derived from the class type
761 /// of the member pointer.
762 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
763 /// Path - The path of base/derived classes from the member declaration's
764 /// class (exclusive) to the class type of the member pointer (inclusive).
765 SmallVector<const CXXRecordDecl*, 4> Path;
766
767 /// Perform a cast towards the class of the Decl (either up or down the
768 /// hierarchy).
769 bool castBack(const CXXRecordDecl *Class) {
770 assert(!Path.empty());
771 const CXXRecordDecl *Expected;
772 if (Path.size() >= 2)
773 Expected = Path[Path.size() - 2];
774 else
775 Expected = getContainingRecord();
776 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
777 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
778 // if B does not contain the original member and is not a base or
779 // derived class of the class containing the original member, the result
780 // of the cast is undefined.
781 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
782 // (D::*). We consider that to be a language defect.
783 return false;
784 }
785 Path.pop_back();
786 return true;
787 }
788 /// Perform a base-to-derived member pointer cast.
789 bool castToDerived(const CXXRecordDecl *Derived) {
790 if (!getDecl())
791 return true;
792 if (!isDerivedMember()) {
793 Path.push_back(Derived);
794 return true;
795 }
796 if (!castBack(Derived))
797 return false;
798 if (Path.empty())
799 DeclAndIsDerivedMember.setInt(false);
800 return true;
801 }
802 /// Perform a derived-to-base member pointer cast.
803 bool castToBase(const CXXRecordDecl *Base) {
804 if (!getDecl())
805 return true;
806 if (Path.empty())
807 DeclAndIsDerivedMember.setInt(true);
808 if (isDerivedMember()) {
809 Path.push_back(Base);
810 return true;
811 }
812 return castBack(Base);
813 }
814 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000815
Richard Smithb02e4622012-02-01 01:42:44 +0000816 /// Compare two member pointers, which are assumed to be of the same type.
817 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
818 if (!LHS.getDecl() || !RHS.getDecl())
819 return !LHS.getDecl() && !RHS.getDecl();
820 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
821 return false;
822 return LHS.Path == RHS.Path;
823 }
824
Richard Smithc1c5f272011-12-13 06:39:58 +0000825 /// Kinds of constant expression checking, for diagnostics.
826 enum CheckConstantExpressionKind {
827 CCEK_Constant, ///< A normal constant.
828 CCEK_ReturnValue, ///< A constexpr function return value.
829 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
830 };
John McCallf4cf1a12010-05-07 17:22:02 +0000831}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000832
Richard Smith47a1eed2011-10-29 20:57:55 +0000833static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000834static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000835 const LValue &This, const Expr *E,
836 CheckConstantExpressionKind CCEK
837 = CCEK_Constant);
John McCallefdb83e2010-05-07 21:00:08 +0000838static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
839static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000840static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
841 EvalInfo &Info);
842static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000843static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000844static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000845 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000846static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000847static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000848
849//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000850// Misc utilities
851//===----------------------------------------------------------------------===//
852
Richard Smith180f4792011-11-10 06:34:14 +0000853/// Should this call expression be treated as a string literal?
854static bool IsStringLiteralCall(const CallExpr *E) {
855 unsigned Builtin = E->isBuiltinCall();
856 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
857 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
858}
859
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000860static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000861 // C++11 [expr.const]p3 An address constant expression is a prvalue core
862 // constant expression of pointer type that evaluates to...
863
864 // ... a null pointer value, or a prvalue core constant expression of type
865 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000866 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000867
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000868 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
869 // ... the address of an object with static storage duration,
870 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
871 return VD->hasGlobalStorage();
872 // ... the address of a function,
873 return isa<FunctionDecl>(D);
874 }
875
876 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000877 switch (E->getStmtClass()) {
878 default:
879 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000880 case Expr::CompoundLiteralExprClass:
881 return cast<CompoundLiteralExpr>(E)->isFileScope();
882 // A string literal has static storage duration.
883 case Expr::StringLiteralClass:
884 case Expr::PredefinedExprClass:
885 case Expr::ObjCStringLiteralClass:
886 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000887 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000888 return true;
889 case Expr::CallExprClass:
890 return IsStringLiteralCall(cast<CallExpr>(E));
891 // For GCC compatibility, &&label has static storage duration.
892 case Expr::AddrLabelExprClass:
893 return true;
894 // A Block literal expression may be used as the initialization value for
895 // Block variables at global or local static scope.
896 case Expr::BlockExprClass:
897 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000898 case Expr::ImplicitValueInitExprClass:
899 // FIXME:
900 // We can never form an lvalue with an implicit value initialization as its
901 // base through expression evaluation, so these only appear in one case: the
902 // implicit variable declaration we invent when checking whether a constexpr
903 // constructor can produce a constant expression. We must assume that such
904 // an expression might be a global lvalue.
905 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000906 }
John McCall42c8f872010-05-10 23:27:23 +0000907}
908
Richard Smith9a17a682011-11-07 05:07:52 +0000909/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000910/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000911/// either LValue or CCValue. Return true if we can fold this expression,
912/// whether or not it's a constant expression.
Richard Smith9a17a682011-11-07 05:07:52 +0000913template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000914static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000915 const T &LVal, APValue &Value,
916 CheckConstantExpressionKind CCEK) {
917 APValue::LValueBase Base = LVal.getLValueBase();
918 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
919
920 if (!IsGlobalLValue(Base)) {
921 if (Info.getLangOpts().CPlusPlus0x) {
922 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
923 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
924 << E->isGLValue() << !Designator.Entries.empty()
925 << !!VD << CCEK << VD;
926 if (VD)
927 Info.Note(VD->getLocation(), diag::note_declared_at);
928 else
929 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
930 diag::note_constexpr_temporary_here);
931 } else {
Richard Smith7098cbd2011-12-21 05:04:46 +0000932 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000933 }
Richard Smith61e61622012-01-12 06:08:57 +0000934 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000935 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000936 }
Richard Smith9a17a682011-11-07 05:07:52 +0000937
Richard Smithb4e85ed2012-01-06 16:39:00 +0000938 bool IsReferenceType = E->isGLValue();
939
940 if (Designator.Invalid) {
Richard Smith61e61622012-01-12 06:08:57 +0000941 // This is not a core constant expression. An appropriate diagnostic will
942 // have already been produced.
Richard Smith9a17a682011-11-07 05:07:52 +0000943 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
944 APValue::NoLValuePath());
945 return true;
946 }
947
Richard Smithb4e85ed2012-01-06 16:39:00 +0000948 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
949 Designator.Entries, Designator.IsOnePastTheEnd);
950
951 // Allow address constant expressions to be past-the-end pointers. This is
952 // an extension: the standard requires them to point to an object.
953 if (!IsReferenceType)
954 return true;
955
956 // A reference constant expression must refer to an object.
957 if (!Base) {
958 // FIXME: diagnostic
959 Info.CCEDiag(E->getExprLoc());
Richard Smith61e61622012-01-12 06:08:57 +0000960 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000961 }
962
Richard Smithc1c5f272011-12-13 06:39:58 +0000963 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +0000964 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000965 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
966 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
967 << !Designator.Entries.empty() << !!VD << VD;
968 if (VD)
969 Info.Note(VD->getLocation(), diag::note_declared_at);
970 else
971 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
972 diag::note_constexpr_temporary_here);
Richard Smithc1c5f272011-12-13 06:39:58 +0000973 }
974
Richard Smith9a17a682011-11-07 05:07:52 +0000975 return true;
976}
977
Richard Smith51201882011-12-30 21:15:51 +0000978/// Check that this core constant expression is of literal type, and if not,
979/// produce an appropriate diagnostic.
980static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
981 if (!E->isRValue() || E->getType()->isLiteralType())
982 return true;
983
984 // Prvalue constant expressions must be of literal types.
985 if (Info.getLangOpts().CPlusPlus0x)
986 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
987 << E->getType();
988 else
989 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
990 return false;
991}
992
Richard Smith47a1eed2011-10-29 20:57:55 +0000993/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000994/// constant expression, and if it is, produce the corresponding constant value.
Richard Smith51201882011-12-30 21:15:51 +0000995/// If not, report an appropriate diagnostic. Does not check that the expression
996/// is of literal type.
Richard Smithf48fdb02011-12-09 22:58:01 +0000997static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000998 const CCValue &CCValue, APValue &Value,
999 CheckConstantExpressionKind CCEK
1000 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +00001001 if (!CCValue.isLValue()) {
1002 Value = CCValue;
1003 return true;
1004 }
Richard Smithc1c5f272011-12-13 06:39:58 +00001005 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +00001006}
1007
Richard Smith9e36b532011-10-31 05:11:32 +00001008const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001009 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001010}
1011
1012static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001013 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +00001014}
1015
Richard Smith65ac5982011-11-01 21:06:14 +00001016static bool IsWeakLValue(const LValue &Value) {
1017 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001018 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001019}
1020
Richard Smithe24f5fc2011-11-17 22:56:20 +00001021static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001022 // A null base expression indicates a null pointer. These are always
1023 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001024 if (!Value.getLValueBase()) {
1025 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001026 return true;
1027 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001028
Richard Smithe24f5fc2011-11-17 22:56:20 +00001029 // We have a non-null base. These are generally known to be true, but if it's
1030 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001031 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001032 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001033 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001034}
1035
Richard Smith47a1eed2011-10-29 20:57:55 +00001036static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001037 switch (Val.getKind()) {
1038 case APValue::Uninitialized:
1039 return false;
1040 case APValue::Int:
1041 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001042 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001043 case APValue::Float:
1044 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001045 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001046 case APValue::ComplexInt:
1047 Result = Val.getComplexIntReal().getBoolValue() ||
1048 Val.getComplexIntImag().getBoolValue();
1049 return true;
1050 case APValue::ComplexFloat:
1051 Result = !Val.getComplexFloatReal().isZero() ||
1052 !Val.getComplexFloatImag().isZero();
1053 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001054 case APValue::LValue:
1055 return EvalPointerValueAsBool(Val, Result);
1056 case APValue::MemberPointer:
1057 Result = Val.getMemberPointerDecl();
1058 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001059 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001060 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001061 case APValue::Struct:
1062 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001063 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001064 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001065 }
1066
Richard Smithc49bd112011-10-28 17:51:58 +00001067 llvm_unreachable("unknown APValue kind");
1068}
1069
1070static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1071 EvalInfo &Info) {
1072 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001073 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001074 if (!Evaluate(Val, Info, E))
1075 return false;
1076 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001077}
1078
Richard Smithc1c5f272011-12-13 06:39:58 +00001079template<typename T>
1080static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1081 const T &SrcValue, QualType DestType) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001082 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001083 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001084 return false;
1085}
1086
1087static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1088 QualType SrcType, const APFloat &Value,
1089 QualType DestType, APSInt &Result) {
1090 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001091 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001092 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001093
Richard Smithc1c5f272011-12-13 06:39:58 +00001094 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001095 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001096 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1097 & APFloat::opInvalidOp)
1098 return HandleOverflow(Info, E, Value, DestType);
1099 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001100}
1101
Richard Smithc1c5f272011-12-13 06:39:58 +00001102static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1103 QualType SrcType, QualType DestType,
1104 APFloat &Result) {
1105 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001106 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001107 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1108 APFloat::rmNearestTiesToEven, &ignored)
1109 & APFloat::opOverflow)
1110 return HandleOverflow(Info, E, Value, DestType);
1111 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001112}
1113
Richard Smithf72fccf2012-01-30 22:27:01 +00001114static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1115 QualType DestType, QualType SrcType,
1116 APSInt &Value) {
1117 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001118 APSInt Result = Value;
1119 // Figure out if this is a truncate, extend or noop cast.
1120 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001121 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001122 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001123 return Result;
1124}
1125
Richard Smithc1c5f272011-12-13 06:39:58 +00001126static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1127 QualType SrcType, const APSInt &Value,
1128 QualType DestType, APFloat &Result) {
1129 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1130 if (Result.convertFromAPInt(Value, Value.isSigned(),
1131 APFloat::rmNearestTiesToEven)
1132 & APFloat::opOverflow)
1133 return HandleOverflow(Info, E, Value, DestType);
1134 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001135}
1136
Eli Friedmane6a24e82011-12-22 03:51:45 +00001137static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1138 llvm::APInt &Res) {
1139 CCValue SVal;
1140 if (!Evaluate(SVal, Info, E))
1141 return false;
1142 if (SVal.isInt()) {
1143 Res = SVal.getInt();
1144 return true;
1145 }
1146 if (SVal.isFloat()) {
1147 Res = SVal.getFloat().bitcastToAPInt();
1148 return true;
1149 }
1150 if (SVal.isVector()) {
1151 QualType VecTy = E->getType();
1152 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1153 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1154 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1155 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1156 Res = llvm::APInt::getNullValue(VecSize);
1157 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1158 APValue &Elt = SVal.getVectorElt(i);
1159 llvm::APInt EltAsInt;
1160 if (Elt.isInt()) {
1161 EltAsInt = Elt.getInt();
1162 } else if (Elt.isFloat()) {
1163 EltAsInt = Elt.getFloat().bitcastToAPInt();
1164 } else {
1165 // Don't try to handle vectors of anything other than int or float
1166 // (not sure if it's possible to hit this case).
1167 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1168 return false;
1169 }
1170 unsigned BaseEltSize = EltAsInt.getBitWidth();
1171 if (BigEndian)
1172 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1173 else
1174 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1175 }
1176 return true;
1177 }
1178 // Give up if the input isn't an int, float, or vector. For example, we
1179 // reject "(v4i16)(intptr_t)&a".
1180 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1181 return false;
1182}
1183
Richard Smithb4e85ed2012-01-06 16:39:00 +00001184/// Cast an lvalue referring to a base subobject to a derived class, by
1185/// truncating the lvalue's path to the given length.
1186static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1187 const RecordDecl *TruncatedType,
1188 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001189 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001190
1191 // Check we actually point to a derived class object.
1192 if (TruncatedElements == D.Entries.size())
1193 return true;
1194 assert(TruncatedElements >= D.MostDerivedPathLength &&
1195 "not casting to a derived class");
1196 if (!Result.checkSubobject(Info, E, CSK_Derived))
1197 return false;
1198
1199 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001200 const RecordDecl *RD = TruncatedType;
1201 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001202 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1203 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001204 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001205 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001206 else
Richard Smith180f4792011-11-10 06:34:14 +00001207 Result.Offset -= Layout.getBaseClassOffset(Base);
1208 RD = Base;
1209 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001210 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001211 return true;
1212}
1213
Richard Smithb4e85ed2012-01-06 16:39:00 +00001214static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001215 const CXXRecordDecl *Derived,
1216 const CXXRecordDecl *Base,
1217 const ASTRecordLayout *RL = 0) {
1218 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1219 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001220 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001221}
1222
Richard Smithb4e85ed2012-01-06 16:39:00 +00001223static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001224 const CXXRecordDecl *DerivedDecl,
1225 const CXXBaseSpecifier *Base) {
1226 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1227
1228 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001229 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001230 return true;
1231 }
1232
Richard Smithb4e85ed2012-01-06 16:39:00 +00001233 SubobjectDesignator &D = Obj.Designator;
1234 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001235 return false;
1236
Richard Smithb4e85ed2012-01-06 16:39:00 +00001237 // Extract most-derived object and corresponding type.
1238 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1239 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1240 return false;
1241
1242 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001243 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1244 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001245 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001246 return true;
1247}
1248
1249/// Update LVal to refer to the given field, which must be a member of the type
1250/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001251static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001252 const FieldDecl *FD,
1253 const ASTRecordLayout *RL = 0) {
1254 if (!RL)
1255 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1256
1257 unsigned I = FD->getFieldIndex();
1258 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001259 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001260}
1261
Richard Smithd9b02e72012-01-25 22:15:11 +00001262/// Update LVal to refer to the given indirect field.
1263static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1264 LValue &LVal,
1265 const IndirectFieldDecl *IFD) {
1266 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1267 CE = IFD->chain_end(); C != CE; ++C)
1268 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1269}
1270
Richard Smith180f4792011-11-10 06:34:14 +00001271/// Get the size of the given type in char units.
1272static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1273 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1274 // extension.
1275 if (Type->isVoidType() || Type->isFunctionType()) {
1276 Size = CharUnits::One();
1277 return true;
1278 }
1279
1280 if (!Type->isConstantSizeType()) {
1281 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001282 // FIXME: Diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001283 return false;
1284 }
1285
1286 Size = Info.Ctx.getTypeSizeInChars(Type);
1287 return true;
1288}
1289
1290/// Update a pointer value to model pointer arithmetic.
1291/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001292/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001293/// \param LVal - The pointer value to be updated.
1294/// \param EltTy - The pointee type represented by LVal.
1295/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001296static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1297 LValue &LVal, QualType EltTy,
1298 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001299 CharUnits SizeOfPointee;
1300 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1301 return false;
1302
1303 // Compute the new offset in the appropriate width.
1304 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001305 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001306 return true;
1307}
1308
Richard Smith03f96112011-10-24 17:54:18 +00001309/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001310static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1311 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001312 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001313 // If this is a parameter to an active constexpr function call, perform
1314 // argument substitution.
1315 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001316 // Assume arguments of a potential constant expression are unknown
1317 // constant expressions.
1318 if (Info.CheckingPotentialConstantExpression)
1319 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001320 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001321 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001322 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001323 }
Richard Smith177dce72011-11-01 16:57:24 +00001324 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1325 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001326 }
Richard Smith03f96112011-10-24 17:54:18 +00001327
Richard Smith099e7f62011-12-19 06:19:21 +00001328 // Dig out the initializer, and use the declaration which it's attached to.
1329 const Expr *Init = VD->getAnyInitializer(VD);
1330 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001331 // If we're checking a potential constant expression, the variable could be
1332 // initialized later.
1333 if (!Info.CheckingPotentialConstantExpression)
1334 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001335 return false;
1336 }
1337
Richard Smith180f4792011-11-10 06:34:14 +00001338 // If we're currently evaluating the initializer of this declaration, use that
1339 // in-flight value.
1340 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001341 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1342 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001343 return !Result.isUninit();
1344 }
1345
Richard Smith65ac5982011-11-01 21:06:14 +00001346 // Never evaluate the initializer of a weak variable. We can't be sure that
1347 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001348 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001349 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001350 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001351 }
Richard Smith65ac5982011-11-01 21:06:14 +00001352
Richard Smith099e7f62011-12-19 06:19:21 +00001353 // Check that we can fold the initializer. In C++, we will have already done
1354 // this in the cases where it matters for conformance.
1355 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1356 if (!VD->evaluateValue(Notes)) {
1357 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1358 Notes.size() + 1) << VD;
1359 Info.Note(VD->getLocation(), diag::note_declared_at);
1360 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001361 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001362 } else if (!VD->checkInitIsICE()) {
1363 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1364 Notes.size() + 1) << VD;
1365 Info.Note(VD->getLocation(), diag::note_declared_at);
1366 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001367 }
Richard Smith03f96112011-10-24 17:54:18 +00001368
Richard Smithb4e85ed2012-01-06 16:39:00 +00001369 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001370 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001371}
1372
Richard Smithc49bd112011-10-28 17:51:58 +00001373static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001374 Qualifiers Quals = T.getQualifiers();
1375 return Quals.hasConst() && !Quals.hasVolatile();
1376}
1377
Richard Smith59efe262011-11-11 04:05:33 +00001378/// Get the base index of the given base class within an APValue representing
1379/// the given derived class.
1380static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1381 const CXXRecordDecl *Base) {
1382 Base = Base->getCanonicalDecl();
1383 unsigned Index = 0;
1384 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1385 E = Derived->bases_end(); I != E; ++I, ++Index) {
1386 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1387 return Index;
1388 }
1389
1390 llvm_unreachable("base class missing from derived class's bases list");
1391}
1392
Richard Smithcc5d4f62011-11-07 09:22:26 +00001393/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001394static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1395 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001396 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001397 if (Sub.Invalid)
1398 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001399 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001400 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001401 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001402 (unsigned)diag::note_constexpr_read_past_end :
1403 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001404 return false;
1405 }
Richard Smithf64699e2011-11-11 08:28:03 +00001406 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001407 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001408 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1409 // This object might be initialized later.
1410 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001411
1412 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1413 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001414 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001415 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001416 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001417 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001418 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001419 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001420 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001421 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001422 // Note, it should not be possible to form a pointer with a valid
1423 // designator which points more than one past the end of the array.
1424 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001425 (unsigned)diag::note_constexpr_read_past_end :
1426 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001427 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001428 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001429 if (O->getArrayInitializedElts() > Index)
1430 O = &O->getArrayInitializedElt(Index);
1431 else
1432 O = &O->getArrayFiller();
1433 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001434 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1435 // Next subobject is a class, struct or union field.
1436 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1437 if (RD->isUnion()) {
1438 const FieldDecl *UnionField = O->getUnionField();
1439 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001440 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001441 Info.Diag(E->getExprLoc(),
1442 diag::note_constexpr_read_inactive_union_member)
1443 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001444 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001445 }
Richard Smith180f4792011-11-10 06:34:14 +00001446 O = &O->getUnionValue();
1447 } else
1448 O = &O->getStructField(Field->getFieldIndex());
1449 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001450
1451 if (ObjType.isVolatileQualified()) {
1452 if (Info.getLangOpts().CPlusPlus) {
1453 // FIXME: Include a description of the path to the volatile subobject.
1454 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1455 << 2 << Field;
1456 Info.Note(Field->getLocation(), diag::note_declared_at);
1457 } else {
1458 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1459 }
1460 return false;
1461 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001462 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001463 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001464 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1465 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1466 O = &O->getStructBase(getBaseIndex(Derived, Base));
1467 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001468 }
Richard Smith180f4792011-11-10 06:34:14 +00001469
Richard Smithf48fdb02011-12-09 22:58:01 +00001470 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001471 if (!Info.CheckingPotentialConstantExpression)
1472 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001473 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001474 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001475 }
1476
Richard Smithb4e85ed2012-01-06 16:39:00 +00001477 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001478 return true;
1479}
1480
Richard Smith180f4792011-11-10 06:34:14 +00001481/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1482/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1483/// for looking up the glvalue referred to by an entity of reference type.
1484///
1485/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001486/// \param Conv - The expression for which we are performing the conversion.
1487/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001488/// \param Type - The type we expect this conversion to produce.
1489/// \param LVal - The glvalue on which we are attempting to perform this action.
1490/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001491static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1492 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001493 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001494 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1495 if (!Info.getLangOpts().CPlusPlus)
1496 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1497
Richard Smithb4e85ed2012-01-06 16:39:00 +00001498 if (LVal.Designator.Invalid)
1499 // A diagnostic will have already been produced.
1500 return false;
1501
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001502 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001503 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001504 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001505
Richard Smithf48fdb02011-12-09 22:58:01 +00001506 if (!LVal.Base) {
1507 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001508 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1509 return false;
1510 }
1511
1512 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1513 // is not a constant expression (even if the object is non-volatile). We also
1514 // apply this rule to C++98, in order to conform to the expected 'volatile'
1515 // semantics.
1516 if (Type.isVolatileQualified()) {
1517 if (Info.getLangOpts().CPlusPlus)
1518 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1519 else
1520 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001521 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001522 }
Richard Smithc49bd112011-10-28 17:51:58 +00001523
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001524 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001525 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1526 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001527 // expressions are constant expressions too. Inside constexpr functions,
1528 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001529 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001530 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001531 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001532 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001533 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001534 }
1535
Richard Smith7098cbd2011-12-21 05:04:46 +00001536 // DR1313: If the object is volatile-qualified but the glvalue was not,
1537 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001538 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001539 if (VT.isVolatileQualified()) {
1540 if (Info.getLangOpts().CPlusPlus) {
1541 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1542 Info.Note(VD->getLocation(), diag::note_declared_at);
1543 } else {
1544 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001545 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001546 return false;
1547 }
1548
1549 if (!isa<ParmVarDecl>(VD)) {
1550 if (VD->isConstexpr()) {
1551 // OK, we can read this variable.
1552 } else if (VT->isIntegralOrEnumerationType()) {
1553 if (!VT.isConstQualified()) {
1554 if (Info.getLangOpts().CPlusPlus) {
1555 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1556 Info.Note(VD->getLocation(), diag::note_declared_at);
1557 } else {
1558 Info.Diag(Loc);
1559 }
1560 return false;
1561 }
1562 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1563 // We support folding of const floating-point types, in order to make
1564 // static const data members of such types (supported as an extension)
1565 // more useful.
1566 if (Info.getLangOpts().CPlusPlus0x) {
1567 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1568 Info.Note(VD->getLocation(), diag::note_declared_at);
1569 } else {
1570 Info.CCEDiag(Loc);
1571 }
1572 } else {
1573 // FIXME: Allow folding of values of any literal type in all languages.
1574 if (Info.getLangOpts().CPlusPlus0x) {
1575 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1576 Info.Note(VD->getLocation(), diag::note_declared_at);
1577 } else {
1578 Info.Diag(Loc);
1579 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001580 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001581 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001582 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001583
Richard Smithf48fdb02011-12-09 22:58:01 +00001584 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001585 return false;
1586
Richard Smith47a1eed2011-10-29 20:57:55 +00001587 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001588 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001589
1590 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1591 // conversion. This happens when the declaration and the lvalue should be
1592 // considered synonymous, for instance when initializing an array of char
1593 // from a string literal. Continue as if the initializer lvalue was the
1594 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001595 assert(RVal.getLValueOffset().isZero() &&
1596 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001597 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001598 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001599 }
1600
Richard Smith7098cbd2011-12-21 05:04:46 +00001601 // Volatile temporary objects cannot be read in constant expressions.
1602 if (Base->getType().isVolatileQualified()) {
1603 if (Info.getLangOpts().CPlusPlus) {
1604 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1605 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1606 } else {
1607 Info.Diag(Loc);
1608 }
1609 return false;
1610 }
1611
Richard Smith0a3bdb62011-11-04 02:25:55 +00001612 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1613 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1614 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001615 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001616 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001617 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001618 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001619
1620 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001621 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001622 const ConstantArrayType *CAT =
1623 Info.Ctx.getAsConstantArrayType(S->getType());
1624 if (Index >= CAT->getSize().getZExtValue()) {
1625 // Note, it should not be possible to form a pointer which points more
1626 // than one past the end of the array without producing a prior const expr
1627 // diagnostic.
1628 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001629 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001630 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001631 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1632 Type->isUnsignedIntegerType());
1633 if (Index < S->getLength())
1634 Value = S->getCodeUnit(Index);
1635 RVal = CCValue(Value);
1636 return true;
1637 }
1638
Richard Smithcc5d4f62011-11-07 09:22:26 +00001639 if (Frame) {
1640 // If this is a temporary expression with a nontrivial initializer, grab the
1641 // value from the relevant stack frame.
1642 RVal = Frame->Temporaries[Base];
1643 } else if (const CompoundLiteralExpr *CLE
1644 = dyn_cast<CompoundLiteralExpr>(Base)) {
1645 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1646 // initializer until now for such expressions. Such an expression can't be
1647 // an ICE in C, so this only matters for fold.
1648 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1649 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1650 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001651 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001652 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001653 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001654 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001655
Richard Smithf48fdb02011-12-09 22:58:01 +00001656 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1657 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001658}
1659
Richard Smith59efe262011-11-11 04:05:33 +00001660/// Build an lvalue for the object argument of a member function call.
1661static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1662 LValue &This) {
1663 if (Object->getType()->isPointerType())
1664 return EvaluatePointer(Object, This, Info);
1665
1666 if (Object->isGLValue())
1667 return EvaluateLValue(Object, This, Info);
1668
Richard Smithe24f5fc2011-11-17 22:56:20 +00001669 if (Object->getType()->isLiteralType())
1670 return EvaluateTemporary(Object, This, Info);
1671
1672 return false;
1673}
1674
1675/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1676/// lvalue referring to the result.
1677///
1678/// \param Info - Information about the ongoing evaluation.
1679/// \param BO - The member pointer access operation.
1680/// \param LV - Filled in with a reference to the resulting object.
1681/// \param IncludeMember - Specifies whether the member itself is included in
1682/// the resulting LValue subobject designator. This is not possible when
1683/// creating a bound member function.
1684/// \return The field or method declaration to which the member pointer refers,
1685/// or 0 if evaluation fails.
1686static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1687 const BinaryOperator *BO,
1688 LValue &LV,
1689 bool IncludeMember = true) {
1690 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1691
Richard Smith745f5142012-01-27 01:14:48 +00001692 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1693 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001694 return 0;
1695
1696 MemberPtr MemPtr;
1697 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1698 return 0;
1699
1700 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1701 // member value, the behavior is undefined.
1702 if (!MemPtr.getDecl())
1703 return 0;
1704
Richard Smith745f5142012-01-27 01:14:48 +00001705 if (!EvalObjOK)
1706 return 0;
1707
Richard Smithe24f5fc2011-11-17 22:56:20 +00001708 if (MemPtr.isDerivedMember()) {
1709 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001710 // The end of the derived-to-base path for the base object must match the
1711 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001712 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001713 LV.Designator.Entries.size())
1714 return 0;
1715 unsigned PathLengthToMember =
1716 LV.Designator.Entries.size() - MemPtr.Path.size();
1717 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1718 const CXXRecordDecl *LVDecl = getAsBaseClass(
1719 LV.Designator.Entries[PathLengthToMember + I]);
1720 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1721 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1722 return 0;
1723 }
1724
1725 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001726 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1727 PathLengthToMember))
1728 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001729 } else if (!MemPtr.Path.empty()) {
1730 // Extend the LValue path with the member pointer's path.
1731 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1732 MemPtr.Path.size() + IncludeMember);
1733
1734 // Walk down to the appropriate base class.
1735 QualType LVType = BO->getLHS()->getType();
1736 if (const PointerType *PT = LVType->getAs<PointerType>())
1737 LVType = PT->getPointeeType();
1738 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1739 assert(RD && "member pointer access on non-class-type expression");
1740 // The first class in the path is that of the lvalue.
1741 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1742 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001743 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001744 RD = Base;
1745 }
1746 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001747 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001748 }
1749
1750 // Add the member. Note that we cannot build bound member functions here.
1751 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001752 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1753 HandleLValueMember(Info, BO, LV, FD);
1754 else if (const IndirectFieldDecl *IFD =
1755 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1756 HandleLValueIndirectMember(Info, BO, LV, IFD);
1757 else
1758 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001759 }
1760
1761 return MemPtr.getDecl();
1762}
1763
1764/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1765/// the provided lvalue, which currently refers to the base object.
1766static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1767 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001768 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001769 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001770 return false;
1771
Richard Smithb4e85ed2012-01-06 16:39:00 +00001772 QualType TargetQT = E->getType();
1773 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1774 TargetQT = PT->getPointeeType();
1775
1776 // Check this cast lands within the final derived-to-base subobject path.
1777 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1778 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1779 << D.MostDerivedType << TargetQT;
1780 return false;
1781 }
1782
Richard Smithe24f5fc2011-11-17 22:56:20 +00001783 // Check the type of the final cast. We don't need to check the path,
1784 // since a cast can only be formed if the path is unique.
1785 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001786 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1787 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001788 if (NewEntriesSize == D.MostDerivedPathLength)
1789 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1790 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001791 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001792 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1793 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1794 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001795 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001796 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001797
1798 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001799 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001800}
1801
Mike Stumpc4c90452009-10-27 22:09:17 +00001802namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001803enum EvalStmtResult {
1804 /// Evaluation failed.
1805 ESR_Failed,
1806 /// Hit a 'return' statement.
1807 ESR_Returned,
1808 /// Evaluation succeeded.
1809 ESR_Succeeded
1810};
1811}
1812
1813// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001814static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001815 const Stmt *S) {
1816 switch (S->getStmtClass()) {
1817 default:
1818 return ESR_Failed;
1819
1820 case Stmt::NullStmtClass:
1821 case Stmt::DeclStmtClass:
1822 return ESR_Succeeded;
1823
Richard Smithc1c5f272011-12-13 06:39:58 +00001824 case Stmt::ReturnStmtClass: {
1825 CCValue CCResult;
1826 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1827 if (!Evaluate(CCResult, Info, RetExpr) ||
1828 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1829 CCEK_ReturnValue))
1830 return ESR_Failed;
1831 return ESR_Returned;
1832 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001833
1834 case Stmt::CompoundStmtClass: {
1835 const CompoundStmt *CS = cast<CompoundStmt>(S);
1836 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1837 BE = CS->body_end(); BI != BE; ++BI) {
1838 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1839 if (ESR != ESR_Succeeded)
1840 return ESR;
1841 }
1842 return ESR_Succeeded;
1843 }
1844 }
1845}
1846
Richard Smith61802452011-12-22 02:22:31 +00001847/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1848/// default constructor. If so, we'll fold it whether or not it's marked as
1849/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1850/// so we need special handling.
1851static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00001852 const CXXConstructorDecl *CD,
1853 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001854 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1855 return false;
1856
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001857 // Value-initialization does not call a trivial default constructor, so such a
1858 // call is a core constant expression whether or not the constructor is
1859 // constexpr.
1860 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001861 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001862 // FIXME: If DiagDecl is an implicitly-declared special member function,
1863 // we should be much more explicit about why it's not constexpr.
1864 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1865 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1866 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00001867 } else {
1868 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1869 }
1870 }
1871 return true;
1872}
1873
Richard Smithc1c5f272011-12-13 06:39:58 +00001874/// CheckConstexprFunction - Check that a function can be called in a constant
1875/// expression.
1876static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1877 const FunctionDecl *Declaration,
1878 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00001879 // Potential constant expressions can contain calls to declared, but not yet
1880 // defined, constexpr functions.
1881 if (Info.CheckingPotentialConstantExpression && !Definition &&
1882 Declaration->isConstexpr())
1883 return false;
1884
Richard Smithc1c5f272011-12-13 06:39:58 +00001885 // Can we evaluate this function call?
1886 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1887 return true;
1888
1889 if (Info.getLangOpts().CPlusPlus0x) {
1890 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001891 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1892 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001893 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1894 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1895 << DiagDecl;
1896 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1897 } else {
1898 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1899 }
1900 return false;
1901}
1902
Richard Smith180f4792011-11-10 06:34:14 +00001903namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001904typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001905}
1906
1907/// EvaluateArgs - Evaluate the arguments to a function call.
1908static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1909 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00001910 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001911 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00001912 I != E; ++I) {
1913 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
1914 // If we're checking for a potential constant expression, evaluate all
1915 // initializers even if some of them fail.
1916 if (!Info.keepEvaluatingAfterFailure())
1917 return false;
1918 Success = false;
1919 }
1920 }
1921 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00001922}
1923
Richard Smithd0dccea2011-10-28 22:34:42 +00001924/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00001925static bool HandleFunctionCall(SourceLocation CallLoc,
1926 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00001927 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001928 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00001929 ArgVector ArgValues(Args.size());
1930 if (!EvaluateArgs(Args, ArgValues, Info))
1931 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001932
Richard Smith745f5142012-01-27 01:14:48 +00001933 if (!Info.CheckCallLimit(CallLoc))
1934 return false;
1935
1936 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001937 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1938}
1939
Richard Smith180f4792011-11-10 06:34:14 +00001940/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00001941static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001942 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001943 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00001944 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00001945 ArgVector ArgValues(Args.size());
1946 if (!EvaluateArgs(Args, ArgValues, Info))
1947 return false;
1948
Richard Smith745f5142012-01-27 01:14:48 +00001949 if (!Info.CheckCallLimit(CallLoc))
1950 return false;
1951
1952 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00001953
1954 // If it's a delegating constructor, just delegate.
1955 if (Definition->isDelegatingConstructor()) {
1956 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1957 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1958 }
1959
Richard Smith610a60c2012-01-10 04:32:03 +00001960 // For a trivial copy or move constructor, perform an APValue copy. This is
1961 // essential for unions, where the operations performed by the constructor
1962 // cannot be represented by ctor-initializers.
Richard Smith180f4792011-11-10 06:34:14 +00001963 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith610a60c2012-01-10 04:32:03 +00001964 if (Definition->isDefaulted() &&
1965 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
1966 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
1967 LValue RHS;
1968 RHS.setFrom(ArgValues[0]);
1969 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00001970 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
1971 RHS, Value))
1972 return false;
1973 assert((Value.isStruct() || Value.isUnion()) &&
1974 "trivial copy/move from non-class type?");
1975 // Any CCValue of class type must already be a constant expression.
1976 Result = Value;
1977 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00001978 }
1979
1980 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00001981 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00001982 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1983 std::distance(RD->field_begin(), RD->field_end()));
1984
1985 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1986
Richard Smith745f5142012-01-27 01:14:48 +00001987 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001988 unsigned BasesSeen = 0;
1989#ifndef NDEBUG
1990 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1991#endif
1992 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1993 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00001994 LValue Subobject = This;
1995 APValue *Value = &Result;
1996
1997 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00001998 if ((*I)->isBaseInitializer()) {
1999 QualType BaseType((*I)->getBaseClass(), 0);
2000#ifndef NDEBUG
2001 // Non-virtual base classes are initialized in the order in the class
2002 // definition. We cannot have a virtual base class for a literal type.
2003 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2004 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2005 "base class initializers not in expected order");
2006 ++BaseIt;
2007#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002008 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002009 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002010 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002011 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002012 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002013 if (RD->isUnion()) {
2014 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002015 Value = &Result.getUnionValue();
2016 } else {
2017 Value = &Result.getStructField(FD->getFieldIndex());
2018 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002019 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002020 // Walk the indirect field decl's chain to find the object to initialize,
2021 // and make sure we've initialized every step along it.
2022 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2023 CE = IFD->chain_end();
2024 C != CE; ++C) {
2025 FieldDecl *FD = cast<FieldDecl>(*C);
2026 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2027 // Switch the union field if it differs. This happens if we had
2028 // preceding zero-initialization, and we're now initializing a union
2029 // subobject other than the first.
2030 // FIXME: In this case, the values of the other subobjects are
2031 // specified, since zero-initialization sets all padding bits to zero.
2032 if (Value->isUninit() ||
2033 (Value->isUnion() && Value->getUnionField() != FD)) {
2034 if (CD->isUnion())
2035 *Value = APValue(FD);
2036 else
2037 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2038 std::distance(CD->field_begin(), CD->field_end()));
2039 }
Richard Smith745f5142012-01-27 01:14:48 +00002040 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002041 if (CD->isUnion())
2042 Value = &Value->getUnionValue();
2043 else
2044 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002045 }
Richard Smith180f4792011-11-10 06:34:14 +00002046 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002047 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002048 }
Richard Smith745f5142012-01-27 01:14:48 +00002049
2050 if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
2051 (*I)->isBaseInitializer()
2052 ? CCEK_Constant : CCEK_MemberInit)) {
2053 // If we're checking for a potential constant expression, evaluate all
2054 // initializers even if some of them fail.
2055 if (!Info.keepEvaluatingAfterFailure())
2056 return false;
2057 Success = false;
2058 }
Richard Smith180f4792011-11-10 06:34:14 +00002059 }
2060
Richard Smith745f5142012-01-27 01:14:48 +00002061 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002062}
2063
Richard Smithd0dccea2011-10-28 22:34:42 +00002064namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002065class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002066 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002067 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002068public:
2069
Richard Smith1e12c592011-10-16 21:26:27 +00002070 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002071
2072 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002073 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002074 return true;
2075 }
2076
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002077 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2078 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002079 return Visit(E->getResultExpr());
2080 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002081 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002082 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002083 return true;
2084 return false;
2085 }
John McCallf85e1932011-06-15 23:02:42 +00002086 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002087 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002088 return true;
2089 return false;
2090 }
2091 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002092 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002093 return true;
2094 return false;
2095 }
2096
Mike Stumpc4c90452009-10-27 22:09:17 +00002097 // We don't want to evaluate BlockExprs multiple times, as they generate
2098 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002099 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2100 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2101 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002102 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002103 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2104 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2105 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2106 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2107 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2108 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002109 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002110 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002111 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002112 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002113 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002114 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2115 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2116 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2117 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002118 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002119 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2120 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2121 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2122 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2123 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002124 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002125 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002126 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002127 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002128 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002129
2130 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002131 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002132 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2133 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002134 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002135 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002136 return false;
2137 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002138
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002139 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002140};
2141
John McCall56ca35d2011-02-17 10:25:35 +00002142class OpaqueValueEvaluation {
2143 EvalInfo &info;
2144 OpaqueValueExpr *opaqueValue;
2145
2146public:
2147 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2148 Expr *value)
2149 : info(info), opaqueValue(opaqueValue) {
2150
2151 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002152 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002153 this->opaqueValue = 0;
2154 return;
2155 }
John McCall56ca35d2011-02-17 10:25:35 +00002156 }
2157
2158 bool hasError() const { return opaqueValue == 0; }
2159
2160 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00002161 // FIXME: This will not work for recursive constexpr functions using opaque
2162 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00002163 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2164 }
2165};
2166
Mike Stumpc4c90452009-10-27 22:09:17 +00002167} // end anonymous namespace
2168
Eli Friedman4efaa272008-11-12 09:44:48 +00002169//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002170// Generic Evaluation
2171//===----------------------------------------------------------------------===//
2172namespace {
2173
Richard Smithf48fdb02011-12-09 22:58:01 +00002174// FIXME: RetTy is always bool. Remove it.
2175template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002176class ExprEvaluatorBase
2177 : public ConstStmtVisitor<Derived, RetTy> {
2178private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002179 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002180 return static_cast<Derived*>(this)->Success(V, E);
2181 }
Richard Smith51201882011-12-30 21:15:51 +00002182 RetTy DerivedZeroInitialization(const Expr *E) {
2183 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002184 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002185
2186protected:
2187 EvalInfo &Info;
2188 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2189 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2190
Richard Smithdd1f29b2011-12-12 09:28:41 +00002191 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002192 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002193 }
2194
2195 /// Report an evaluation error. This should only be called when an error is
2196 /// first discovered. When propagating an error, just return false.
2197 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002198 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002199 return false;
2200 }
2201 bool Error(const Expr *E) {
2202 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2203 }
2204
Richard Smith51201882011-12-30 21:15:51 +00002205 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002206
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002207public:
2208 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2209
2210 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002211 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002212 }
2213 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002214 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002215 }
2216
2217 RetTy VisitParenExpr(const ParenExpr *E)
2218 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2219 RetTy VisitUnaryExtension(const UnaryOperator *E)
2220 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2221 RetTy VisitUnaryPlus(const UnaryOperator *E)
2222 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2223 RetTy VisitChooseExpr(const ChooseExpr *E)
2224 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2225 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2226 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002227 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2228 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002229 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2230 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002231 // We cannot create any objects for which cleanups are required, so there is
2232 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2233 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2234 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002235
Richard Smithc216a012011-12-12 12:46:16 +00002236 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2237 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2238 return static_cast<Derived*>(this)->VisitCastExpr(E);
2239 }
2240 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2241 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2242 return static_cast<Derived*>(this)->VisitCastExpr(E);
2243 }
2244
Richard Smithe24f5fc2011-11-17 22:56:20 +00002245 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2246 switch (E->getOpcode()) {
2247 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002248 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002249
2250 case BO_Comma:
2251 VisitIgnoredValue(E->getLHS());
2252 return StmtVisitorTy::Visit(E->getRHS());
2253
2254 case BO_PtrMemD:
2255 case BO_PtrMemI: {
2256 LValue Obj;
2257 if (!HandleMemberPointerAccess(Info, E, Obj))
2258 return false;
2259 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002260 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002261 return false;
2262 return DerivedSuccess(Result, E);
2263 }
2264 }
2265 }
2266
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002267 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2268 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2269 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002270 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002271
2272 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002273 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002274 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002275
2276 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2277 }
2278
2279 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2280 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002281 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002282 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002283
Richard Smithc49bd112011-10-28 17:51:58 +00002284 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002285 return StmtVisitorTy::Visit(EvalExpr);
2286 }
2287
2288 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002289 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002290 if (!Value) {
2291 const Expr *Source = E->getSourceExpr();
2292 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002293 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002294 if (Source == E) { // sanity checking.
2295 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002296 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002297 }
2298 return StmtVisitorTy::Visit(Source);
2299 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002300 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002301 }
Richard Smithf10d9172011-10-11 21:43:33 +00002302
Richard Smithd0dccea2011-10-28 22:34:42 +00002303 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002304 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002305 QualType CalleeType = Callee->getType();
2306
Richard Smithd0dccea2011-10-28 22:34:42 +00002307 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002308 LValue *This = 0, ThisVal;
2309 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002310
Richard Smith59efe262011-11-11 04:05:33 +00002311 // Extract function decl and 'this' pointer from the callee.
2312 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002313 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002314 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2315 // Explicit bound member calls, such as x.f() or p->g();
2316 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002317 return false;
2318 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002319 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002320 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2321 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002322 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2323 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002324 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002325 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002326 return Error(Callee);
2327
2328 FD = dyn_cast<FunctionDecl>(Member);
2329 if (!FD)
2330 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002331 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002332 LValue Call;
2333 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002334 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002335
Richard Smithb4e85ed2012-01-06 16:39:00 +00002336 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002337 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002338 FD = dyn_cast_or_null<FunctionDecl>(
2339 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002340 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002341 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002342
2343 // Overloaded operator calls to member functions are represented as normal
2344 // calls with '*this' as the first argument.
2345 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2346 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002347 // FIXME: When selecting an implicit conversion for an overloaded
2348 // operator delete, we sometimes try to evaluate calls to conversion
2349 // operators without a 'this' parameter!
2350 if (Args.empty())
2351 return Error(E);
2352
Richard Smith59efe262011-11-11 04:05:33 +00002353 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2354 return false;
2355 This = &ThisVal;
2356 Args = Args.slice(1);
2357 }
2358
2359 // Don't call function pointers which have been cast to some other type.
2360 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002361 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002362 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002363 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002364
Richard Smithc1c5f272011-12-13 06:39:58 +00002365 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002366 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002367 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002368
Richard Smithc1c5f272011-12-13 06:39:58 +00002369 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002370 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2371 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002372 return false;
2373
Richard Smithb4e85ed2012-01-06 16:39:00 +00002374 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002375 }
2376
Richard Smithc49bd112011-10-28 17:51:58 +00002377 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2378 return StmtVisitorTy::Visit(E->getInitializer());
2379 }
Richard Smithf10d9172011-10-11 21:43:33 +00002380 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002381 if (E->getNumInits() == 0)
2382 return DerivedZeroInitialization(E);
2383 if (E->getNumInits() == 1)
2384 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002385 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002386 }
2387 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002388 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002389 }
2390 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002391 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002392 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002393 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002394 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002395 }
Richard Smithf10d9172011-10-11 21:43:33 +00002396
Richard Smith180f4792011-11-10 06:34:14 +00002397 /// A member expression where the object is a prvalue is itself a prvalue.
2398 RetTy VisitMemberExpr(const MemberExpr *E) {
2399 assert(!E->isArrow() && "missing call to bound member function?");
2400
2401 CCValue Val;
2402 if (!Evaluate(Val, Info, E->getBase()))
2403 return false;
2404
2405 QualType BaseTy = E->getBase()->getType();
2406
2407 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002408 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002409 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2410 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2411 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2412
Richard Smithb4e85ed2012-01-06 16:39:00 +00002413 SubobjectDesignator Designator(BaseTy);
2414 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002415
Richard Smithf48fdb02011-12-09 22:58:01 +00002416 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002417 DerivedSuccess(Val, E);
2418 }
2419
Richard Smithc49bd112011-10-28 17:51:58 +00002420 RetTy VisitCastExpr(const CastExpr *E) {
2421 switch (E->getCastKind()) {
2422 default:
2423 break;
2424
David Chisnall7a7ee302012-01-16 17:27:18 +00002425 case CK_AtomicToNonAtomic:
2426 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002427 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002428 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002429 return StmtVisitorTy::Visit(E->getSubExpr());
2430
2431 case CK_LValueToRValue: {
2432 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002433 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2434 return false;
2435 CCValue RVal;
2436 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2437 return false;
2438 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002439 }
2440 }
2441
Richard Smithf48fdb02011-12-09 22:58:01 +00002442 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002443 }
2444
Richard Smith8327fad2011-10-24 18:44:57 +00002445 /// Visit a value which is evaluated, but whose value is ignored.
2446 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002447 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002448 if (!Evaluate(Scratch, Info, E))
2449 Info.EvalStatus.HasSideEffects = true;
2450 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002451};
2452
2453}
2454
2455//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002456// Common base class for lvalue and temporary evaluation.
2457//===----------------------------------------------------------------------===//
2458namespace {
2459template<class Derived>
2460class LValueExprEvaluatorBase
2461 : public ExprEvaluatorBase<Derived, bool> {
2462protected:
2463 LValue &Result;
2464 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2465 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2466
2467 bool Success(APValue::LValueBase B) {
2468 Result.set(B);
2469 return true;
2470 }
2471
2472public:
2473 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2474 ExprEvaluatorBaseTy(Info), Result(Result) {}
2475
2476 bool Success(const CCValue &V, const Expr *E) {
2477 Result.setFrom(V);
2478 return true;
2479 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002480
Richard Smithe24f5fc2011-11-17 22:56:20 +00002481 bool VisitMemberExpr(const MemberExpr *E) {
2482 // Handle non-static data members.
2483 QualType BaseTy;
2484 if (E->isArrow()) {
2485 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2486 return false;
2487 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002488 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002489 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002490 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2491 return false;
2492 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002493 } else {
2494 if (!this->Visit(E->getBase()))
2495 return false;
2496 BaseTy = E->getBase()->getType();
2497 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002498
Richard Smithd9b02e72012-01-25 22:15:11 +00002499 const ValueDecl *MD = E->getMemberDecl();
2500 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2501 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2502 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2503 (void)BaseTy;
2504 HandleLValueMember(this->Info, E, Result, FD);
2505 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2506 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2507 } else
2508 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002509
Richard Smithd9b02e72012-01-25 22:15:11 +00002510 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002511 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002512 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002513 RefValue))
2514 return false;
2515 return Success(RefValue, E);
2516 }
2517 return true;
2518 }
2519
2520 bool VisitBinaryOperator(const BinaryOperator *E) {
2521 switch (E->getOpcode()) {
2522 default:
2523 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2524
2525 case BO_PtrMemD:
2526 case BO_PtrMemI:
2527 return HandleMemberPointerAccess(this->Info, E, Result);
2528 }
2529 }
2530
2531 bool VisitCastExpr(const CastExpr *E) {
2532 switch (E->getCastKind()) {
2533 default:
2534 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2535
2536 case CK_DerivedToBase:
2537 case CK_UncheckedDerivedToBase: {
2538 if (!this->Visit(E->getSubExpr()))
2539 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002540
2541 // Now figure out the necessary offset to add to the base LV to get from
2542 // the derived class to the base class.
2543 QualType Type = E->getSubExpr()->getType();
2544
2545 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2546 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002547 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002548 *PathI))
2549 return false;
2550 Type = (*PathI)->getType();
2551 }
2552
2553 return true;
2554 }
2555 }
2556 }
2557};
2558}
2559
2560//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002561// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002562//
2563// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2564// function designators (in C), decl references to void objects (in C), and
2565// temporaries (if building with -Wno-address-of-temporary).
2566//
2567// LValue evaluation produces values comprising a base expression of one of the
2568// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002569// - Declarations
2570// * VarDecl
2571// * FunctionDecl
2572// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002573// * CompoundLiteralExpr in C
2574// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002575// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002576// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002577// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002578// * ObjCEncodeExpr
2579// * AddrLabelExpr
2580// * BlockExpr
2581// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002582// - Locals and temporaries
2583// * Any Expr, with a Frame indicating the function in which the temporary was
2584// evaluated.
2585// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002586//===----------------------------------------------------------------------===//
2587namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002588class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002589 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002590public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002591 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2592 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002593
Richard Smithc49bd112011-10-28 17:51:58 +00002594 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2595
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002596 bool VisitDeclRefExpr(const DeclRefExpr *E);
2597 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002598 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002599 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2600 bool VisitMemberExpr(const MemberExpr *E);
2601 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2602 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002603 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002604 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2605 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002606
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002607 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002608 switch (E->getCastKind()) {
2609 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002610 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002611
Eli Friedmandb924222011-10-11 00:13:24 +00002612 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002613 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002614 if (!Visit(E->getSubExpr()))
2615 return false;
2616 Result.Designator.setInvalid();
2617 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002618
Richard Smithe24f5fc2011-11-17 22:56:20 +00002619 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002620 if (!Visit(E->getSubExpr()))
2621 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002622 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002623 }
2624 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002625
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002626 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002627
Eli Friedman4efaa272008-11-12 09:44:48 +00002628};
2629} // end anonymous namespace
2630
Richard Smithc49bd112011-10-28 17:51:58 +00002631/// Evaluate an expression as an lvalue. This can be legitimately called on
2632/// expressions which are not glvalues, in a few cases:
2633/// * function designators in C,
2634/// * "extern void" objects,
2635/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002636static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002637 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2638 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2639 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002640 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002641}
2642
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002643bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002644 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2645 return Success(FD);
2646 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002647 return VisitVarDecl(E, VD);
2648 return Error(E);
2649}
Richard Smith436c8892011-10-24 23:14:33 +00002650
Richard Smithc49bd112011-10-28 17:51:58 +00002651bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002652 if (!VD->getType()->isReferenceType()) {
2653 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002654 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002655 return true;
2656 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002657 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002658 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002659
Richard Smith47a1eed2011-10-29 20:57:55 +00002660 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002661 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2662 return false;
2663 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002664}
2665
Richard Smithbd552ef2011-10-31 05:52:43 +00002666bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2667 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002668 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002669 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002670 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2671
2672 Result.set(E, Info.CurrentCall);
2673 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2674 Result, E->GetTemporaryExpr());
2675 }
2676
2677 // Materialization of an lvalue temporary occurs when we need to force a copy
2678 // (for instance, if it's a bitfield).
2679 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2680 if (!Visit(E->GetTemporaryExpr()))
2681 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002682 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002683 Info.CurrentCall->Temporaries[E]))
2684 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002685 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002686 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002687}
2688
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002689bool
2690LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002691 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2692 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2693 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002694 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002695}
2696
Richard Smith47d21452011-12-27 12:18:28 +00002697bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2698 if (E->isTypeOperand())
2699 return Success(E);
2700 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2701 if (RD && RD->isPolymorphic()) {
2702 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2703 << E->getExprOperand()->getType()
2704 << E->getExprOperand()->getSourceRange();
2705 return false;
2706 }
2707 return Success(E);
2708}
2709
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002710bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002711 // Handle static data members.
2712 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2713 VisitIgnoredValue(E->getBase());
2714 return VisitVarDecl(E, VD);
2715 }
2716
Richard Smithd0dccea2011-10-28 22:34:42 +00002717 // Handle static member functions.
2718 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2719 if (MD->isStatic()) {
2720 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002721 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002722 }
2723 }
2724
Richard Smith180f4792011-11-10 06:34:14 +00002725 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002726 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002727}
2728
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002729bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002730 // FIXME: Deal with vectors as array subscript bases.
2731 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002732 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002733
Anders Carlsson3068d112008-11-16 19:01:22 +00002734 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002735 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002736
Anders Carlsson3068d112008-11-16 19:01:22 +00002737 APSInt Index;
2738 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002739 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002740 int64_t IndexValue
2741 = Index.isSigned() ? Index.getSExtValue()
2742 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002743
Richard Smithb4e85ed2012-01-06 16:39:00 +00002744 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002745}
Eli Friedman4efaa272008-11-12 09:44:48 +00002746
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002747bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002748 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002749}
2750
Eli Friedman4efaa272008-11-12 09:44:48 +00002751//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002752// Pointer Evaluation
2753//===----------------------------------------------------------------------===//
2754
Anders Carlssonc754aa62008-07-08 05:13:58 +00002755namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002756class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002757 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002758 LValue &Result;
2759
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002760 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002761 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002762 return true;
2763 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002764public:
Mike Stump1eb44332009-09-09 15:08:12 +00002765
John McCallefdb83e2010-05-07 21:00:08 +00002766 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002767 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002768
Richard Smith47a1eed2011-10-29 20:57:55 +00002769 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002770 Result.setFrom(V);
2771 return true;
2772 }
Richard Smith51201882011-12-30 21:15:51 +00002773 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002774 return Success((Expr*)0);
2775 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002776
John McCallefdb83e2010-05-07 21:00:08 +00002777 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002778 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002779 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002780 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002781 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002782 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002783 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002784 bool VisitCallExpr(const CallExpr *E);
2785 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002786 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002787 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002788 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002789 }
Richard Smith180f4792011-11-10 06:34:14 +00002790 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2791 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002792 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002793 Result = *Info.CurrentCall->This;
2794 return true;
2795 }
John McCall56ca35d2011-02-17 10:25:35 +00002796
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002797 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002798};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002799} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002800
John McCallefdb83e2010-05-07 21:00:08 +00002801static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002802 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002803 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002804}
2805
John McCallefdb83e2010-05-07 21:00:08 +00002806bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002807 if (E->getOpcode() != BO_Add &&
2808 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002809 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002810
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002811 const Expr *PExp = E->getLHS();
2812 const Expr *IExp = E->getRHS();
2813 if (IExp->getType()->isPointerType())
2814 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002815
Richard Smith745f5142012-01-27 01:14:48 +00002816 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
2817 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00002818 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002819
John McCallefdb83e2010-05-07 21:00:08 +00002820 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00002821 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00002822 return false;
2823 int64_t AdditionalOffset
2824 = Offset.isSigned() ? Offset.getSExtValue()
2825 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002826 if (E->getOpcode() == BO_Sub)
2827 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002828
Richard Smith180f4792011-11-10 06:34:14 +00002829 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00002830 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2831 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002832}
Eli Friedman4efaa272008-11-12 09:44:48 +00002833
John McCallefdb83e2010-05-07 21:00:08 +00002834bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2835 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002836}
Mike Stump1eb44332009-09-09 15:08:12 +00002837
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002838bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2839 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002840
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002841 switch (E->getCastKind()) {
2842 default:
2843 break;
2844
John McCall2de56d12010-08-25 11:45:40 +00002845 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002846 case CK_CPointerToObjCPointerCast:
2847 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002848 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00002849 if (!Visit(SubExpr))
2850 return false;
Richard Smithc216a012011-12-12 12:46:16 +00002851 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2852 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2853 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002854 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00002855 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002856 if (SubExpr->getType()->isVoidPointerType())
2857 CCEDiag(E, diag::note_constexpr_invalid_cast)
2858 << 3 << SubExpr->getType();
2859 else
2860 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2861 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002862 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002863
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002864 case CK_DerivedToBase:
2865 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002866 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002867 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002868 if (!Result.Base && Result.Offset.isZero())
2869 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002870
Richard Smith180f4792011-11-10 06:34:14 +00002871 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002872 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002873 QualType Type =
2874 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002875
Richard Smith180f4792011-11-10 06:34:14 +00002876 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002877 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002878 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2879 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002880 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002881 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002882 }
2883
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002884 return true;
2885 }
2886
Richard Smithe24f5fc2011-11-17 22:56:20 +00002887 case CK_BaseToDerived:
2888 if (!Visit(E->getSubExpr()))
2889 return false;
2890 if (!Result.Base && Result.Offset.isZero())
2891 return true;
2892 return HandleBaseToDerivedCast(Info, E, Result);
2893
Richard Smith47a1eed2011-10-29 20:57:55 +00002894 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00002895 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002896
John McCall2de56d12010-08-25 11:45:40 +00002897 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002898 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2899
Richard Smith47a1eed2011-10-29 20:57:55 +00002900 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002901 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002902 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002903
John McCallefdb83e2010-05-07 21:00:08 +00002904 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002905 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2906 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002907 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002908 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002909 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002910 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002911 return true;
2912 } else {
2913 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002914 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002915 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002916 }
2917 }
John McCall2de56d12010-08-25 11:45:40 +00002918 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002919 if (SubExpr->isGLValue()) {
2920 if (!EvaluateLValue(SubExpr, Result, Info))
2921 return false;
2922 } else {
2923 Result.set(SubExpr, Info.CurrentCall);
2924 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2925 Info, Result, SubExpr))
2926 return false;
2927 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002928 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002929 if (const ConstantArrayType *CAT
2930 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
2931 Result.addArray(Info, E, CAT);
2932 else
2933 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00002934 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002935
John McCall2de56d12010-08-25 11:45:40 +00002936 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002937 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002938 }
2939
Richard Smithc49bd112011-10-28 17:51:58 +00002940 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002941}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002942
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002943bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002944 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002945 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002946
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002947 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002948}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002949
2950//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002951// Member Pointer Evaluation
2952//===----------------------------------------------------------------------===//
2953
2954namespace {
2955class MemberPointerExprEvaluator
2956 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2957 MemberPtr &Result;
2958
2959 bool Success(const ValueDecl *D) {
2960 Result = MemberPtr(D);
2961 return true;
2962 }
2963public:
2964
2965 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2966 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2967
2968 bool Success(const CCValue &V, const Expr *E) {
2969 Result.setFrom(V);
2970 return true;
2971 }
Richard Smith51201882011-12-30 21:15:51 +00002972 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002973 return Success((const ValueDecl*)0);
2974 }
2975
2976 bool VisitCastExpr(const CastExpr *E);
2977 bool VisitUnaryAddrOf(const UnaryOperator *E);
2978};
2979} // end anonymous namespace
2980
2981static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2982 EvalInfo &Info) {
2983 assert(E->isRValue() && E->getType()->isMemberPointerType());
2984 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2985}
2986
2987bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2988 switch (E->getCastKind()) {
2989 default:
2990 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2991
2992 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00002993 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002994
2995 case CK_BaseToDerivedMemberPointer: {
2996 if (!Visit(E->getSubExpr()))
2997 return false;
2998 if (E->path_empty())
2999 return true;
3000 // Base-to-derived member pointer casts store the path in derived-to-base
3001 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3002 // the wrong end of the derived->base arc, so stagger the path by one class.
3003 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3004 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3005 PathI != PathE; ++PathI) {
3006 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3007 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3008 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003009 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003010 }
3011 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3012 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003013 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003014 return true;
3015 }
3016
3017 case CK_DerivedToBaseMemberPointer:
3018 if (!Visit(E->getSubExpr()))
3019 return false;
3020 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3021 PathE = E->path_end(); PathI != PathE; ++PathI) {
3022 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3023 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3024 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003025 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003026 }
3027 return true;
3028 }
3029}
3030
3031bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3032 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3033 // member can be formed.
3034 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3035}
3036
3037//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003038// Record Evaluation
3039//===----------------------------------------------------------------------===//
3040
3041namespace {
3042 class RecordExprEvaluator
3043 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3044 const LValue &This;
3045 APValue &Result;
3046 public:
3047
3048 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3049 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3050
3051 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003052 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00003053 }
Richard Smith51201882011-12-30 21:15:51 +00003054 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003055
Richard Smith59efe262011-11-11 04:05:33 +00003056 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003057 bool VisitInitListExpr(const InitListExpr *E);
3058 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3059 };
3060}
3061
Richard Smith51201882011-12-30 21:15:51 +00003062/// Perform zero-initialization on an object of non-union class type.
3063/// C++11 [dcl.init]p5:
3064/// To zero-initialize an object or reference of type T means:
3065/// [...]
3066/// -- if T is a (possibly cv-qualified) non-union class type,
3067/// each non-static data member and each base-class subobject is
3068/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003069static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3070 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003071 const LValue &This, APValue &Result) {
3072 assert(!RD->isUnion() && "Expected non-union class type");
3073 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3074 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3075 std::distance(RD->field_begin(), RD->field_end()));
3076
3077 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3078
3079 if (CD) {
3080 unsigned Index = 0;
3081 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003082 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003083 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3084 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003085 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3086 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003087 Result.getStructBase(Index)))
3088 return false;
3089 }
3090 }
3091
Richard Smithb4e85ed2012-01-06 16:39:00 +00003092 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3093 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003094 // -- if T is a reference type, no initialization is performed.
3095 if ((*I)->getType()->isReferenceType())
3096 continue;
3097
3098 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003099 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003100
3101 ImplicitValueInitExpr VIE((*I)->getType());
3102 if (!EvaluateConstantExpression(
3103 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3104 return false;
3105 }
3106
3107 return true;
3108}
3109
3110bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3111 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3112 if (RD->isUnion()) {
3113 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3114 // object's first non-static named data member is zero-initialized
3115 RecordDecl::field_iterator I = RD->field_begin();
3116 if (I == RD->field_end()) {
3117 Result = APValue((const FieldDecl*)0);
3118 return true;
3119 }
3120
3121 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003122 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003123 Result = APValue(*I);
3124 ImplicitValueInitExpr VIE((*I)->getType());
3125 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3126 Subobject, &VIE);
3127 }
3128
Richard Smithb4e85ed2012-01-06 16:39:00 +00003129 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003130}
3131
Richard Smith59efe262011-11-11 04:05:33 +00003132bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3133 switch (E->getCastKind()) {
3134 default:
3135 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3136
3137 case CK_ConstructorConversion:
3138 return Visit(E->getSubExpr());
3139
3140 case CK_DerivedToBase:
3141 case CK_UncheckedDerivedToBase: {
3142 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003143 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003144 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003145 if (!DerivedObject.isStruct())
3146 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003147
3148 // Derived-to-base rvalue conversion: just slice off the derived part.
3149 APValue *Value = &DerivedObject;
3150 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3151 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3152 PathE = E->path_end(); PathI != PathE; ++PathI) {
3153 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3154 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3155 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3156 RD = Base;
3157 }
3158 Result = *Value;
3159 return true;
3160 }
3161 }
3162}
3163
Richard Smith180f4792011-11-10 06:34:14 +00003164bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3165 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3166 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3167
3168 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003169 const FieldDecl *Field = E->getInitializedFieldInUnion();
3170 Result = APValue(Field);
3171 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003172 return true;
Richard Smithec789162012-01-12 18:54:33 +00003173
3174 // If the initializer list for a union does not contain any elements, the
3175 // first element of the union is value-initialized.
3176 ImplicitValueInitExpr VIE(Field->getType());
3177 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3178
Richard Smith180f4792011-11-10 06:34:14 +00003179 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003180 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003181 return EvaluateConstantExpression(Result.getUnionValue(), Info,
Richard Smithec789162012-01-12 18:54:33 +00003182 Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003183 }
3184
3185 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3186 "initializer list for class with base classes");
3187 Result = APValue(APValue::UninitStruct(), 0,
3188 std::distance(RD->field_begin(), RD->field_end()));
3189 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003190 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003191 for (RecordDecl::field_iterator Field = RD->field_begin(),
3192 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3193 // Anonymous bit-fields are not considered members of the class for
3194 // purposes of aggregate initialization.
3195 if (Field->isUnnamedBitfield())
3196 continue;
3197
3198 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003199
Richard Smith745f5142012-01-27 01:14:48 +00003200 bool HaveInit = ElementNo < E->getNumInits();
3201
3202 // FIXME: Diagnostics here should point to the end of the initializer
3203 // list, not the start.
3204 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3205 *Field, &Layout);
3206
3207 // Perform an implicit value-initialization for members beyond the end of
3208 // the initializer list.
3209 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3210
3211 if (!EvaluateConstantExpression(
3212 Result.getStructField((*Field)->getFieldIndex()),
3213 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3214 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003215 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003216 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003217 }
3218 }
3219
Richard Smith745f5142012-01-27 01:14:48 +00003220 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003221}
3222
3223bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3224 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003225 bool ZeroInit = E->requiresZeroInitialization();
3226 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003227 // If we've already performed zero-initialization, we're already done.
3228 if (!Result.isUninit())
3229 return true;
3230
Richard Smith51201882011-12-30 21:15:51 +00003231 if (ZeroInit)
3232 return ZeroInitialization(E);
3233
Richard Smith61802452011-12-22 02:22:31 +00003234 const CXXRecordDecl *RD = FD->getParent();
3235 if (RD->isUnion())
3236 Result = APValue((FieldDecl*)0);
3237 else
3238 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3239 std::distance(RD->field_begin(), RD->field_end()));
3240 return true;
3241 }
3242
Richard Smith180f4792011-11-10 06:34:14 +00003243 const FunctionDecl *Definition = 0;
3244 FD->getBody(Definition);
3245
Richard Smithc1c5f272011-12-13 06:39:58 +00003246 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3247 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003248
Richard Smith610a60c2012-01-10 04:32:03 +00003249 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003250 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003251 if (const MaterializeTemporaryExpr *ME
3252 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3253 return Visit(ME->GetTemporaryExpr());
3254
Richard Smith51201882011-12-30 21:15:51 +00003255 if (ZeroInit && !ZeroInitialization(E))
3256 return false;
3257
Richard Smith180f4792011-11-10 06:34:14 +00003258 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003259 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003260 cast<CXXConstructorDecl>(Definition), Info,
3261 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003262}
3263
3264static bool EvaluateRecord(const Expr *E, const LValue &This,
3265 APValue &Result, EvalInfo &Info) {
3266 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003267 "can't evaluate expression as a record rvalue");
3268 return RecordExprEvaluator(Info, This, Result).Visit(E);
3269}
3270
3271//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003272// Temporary Evaluation
3273//
3274// Temporaries are represented in the AST as rvalues, but generally behave like
3275// lvalues. The full-object of which the temporary is a subobject is implicitly
3276// materialized so that a reference can bind to it.
3277//===----------------------------------------------------------------------===//
3278namespace {
3279class TemporaryExprEvaluator
3280 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3281public:
3282 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3283 LValueExprEvaluatorBaseTy(Info, Result) {}
3284
3285 /// Visit an expression which constructs the value of this temporary.
3286 bool VisitConstructExpr(const Expr *E) {
3287 Result.set(E, Info.CurrentCall);
3288 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3289 Result, E);
3290 }
3291
3292 bool VisitCastExpr(const CastExpr *E) {
3293 switch (E->getCastKind()) {
3294 default:
3295 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3296
3297 case CK_ConstructorConversion:
3298 return VisitConstructExpr(E->getSubExpr());
3299 }
3300 }
3301 bool VisitInitListExpr(const InitListExpr *E) {
3302 return VisitConstructExpr(E);
3303 }
3304 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3305 return VisitConstructExpr(E);
3306 }
3307 bool VisitCallExpr(const CallExpr *E) {
3308 return VisitConstructExpr(E);
3309 }
3310};
3311} // end anonymous namespace
3312
3313/// Evaluate an expression of record type as a temporary.
3314static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003315 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003316 return TemporaryExprEvaluator(Info, Result).Visit(E);
3317}
3318
3319//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003320// Vector Evaluation
3321//===----------------------------------------------------------------------===//
3322
3323namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003324 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003325 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3326 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003327 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003328
Richard Smith07fc6572011-10-22 21:10:00 +00003329 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3330 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003331
Richard Smith07fc6572011-10-22 21:10:00 +00003332 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3333 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3334 // FIXME: remove this APValue copy.
3335 Result = APValue(V.data(), V.size());
3336 return true;
3337 }
Richard Smith69c2c502011-11-04 05:33:44 +00003338 bool Success(const CCValue &V, const Expr *E) {
3339 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003340 Result = V;
3341 return true;
3342 }
Richard Smith51201882011-12-30 21:15:51 +00003343 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003344
Richard Smith07fc6572011-10-22 21:10:00 +00003345 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003346 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003347 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003348 bool VisitInitListExpr(const InitListExpr *E);
3349 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003350 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003351 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003352 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003353 };
3354} // end anonymous namespace
3355
3356static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003357 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003358 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003359}
3360
Richard Smith07fc6572011-10-22 21:10:00 +00003361bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3362 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003363 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003364
Richard Smithd62ca372011-12-06 22:44:34 +00003365 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003366 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003367
Eli Friedman46a52322011-03-25 00:43:55 +00003368 switch (E->getCastKind()) {
3369 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003370 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003371 if (SETy->isIntegerType()) {
3372 APSInt IntResult;
3373 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003374 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003375 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003376 } else if (SETy->isRealFloatingType()) {
3377 APFloat F(0.0);
3378 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003379 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003380 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003381 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003382 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003383 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003384
3385 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003386 SmallVector<APValue, 4> Elts(NElts, Val);
3387 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003388 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003389 case CK_BitCast: {
3390 // Evaluate the operand into an APInt we can extract from.
3391 llvm::APInt SValInt;
3392 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3393 return false;
3394 // Extract the elements
3395 QualType EltTy = VTy->getElementType();
3396 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3397 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3398 SmallVector<APValue, 4> Elts;
3399 if (EltTy->isRealFloatingType()) {
3400 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3401 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3402 unsigned FloatEltSize = EltSize;
3403 if (&Sem == &APFloat::x87DoubleExtended)
3404 FloatEltSize = 80;
3405 for (unsigned i = 0; i < NElts; i++) {
3406 llvm::APInt Elt;
3407 if (BigEndian)
3408 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3409 else
3410 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3411 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3412 }
3413 } else if (EltTy->isIntegerType()) {
3414 for (unsigned i = 0; i < NElts; i++) {
3415 llvm::APInt Elt;
3416 if (BigEndian)
3417 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3418 else
3419 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3420 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3421 }
3422 } else {
3423 return Error(E);
3424 }
3425 return Success(Elts, E);
3426 }
Eli Friedman46a52322011-03-25 00:43:55 +00003427 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003428 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003429 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003430}
3431
Richard Smith07fc6572011-10-22 21:10:00 +00003432bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003433VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003434 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003435 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003436 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003437
Nate Begeman59b5da62009-01-18 03:20:47 +00003438 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003439 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003440
Eli Friedman3edd5a92012-01-03 23:24:20 +00003441 // The number of initializers can be less than the number of
3442 // vector elements. For OpenCL, this can be due to nested vector
3443 // initialization. For GCC compatibility, missing trailing elements
3444 // should be initialized with zeroes.
3445 unsigned CountInits = 0, CountElts = 0;
3446 while (CountElts < NumElements) {
3447 // Handle nested vector initialization.
3448 if (CountInits < NumInits
3449 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3450 APValue v;
3451 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3452 return Error(E);
3453 unsigned vlen = v.getVectorLength();
3454 for (unsigned j = 0; j < vlen; j++)
3455 Elements.push_back(v.getVectorElt(j));
3456 CountElts += vlen;
3457 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003458 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003459 if (CountInits < NumInits) {
3460 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3461 return Error(E);
3462 } else // trailing integer zero.
3463 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3464 Elements.push_back(APValue(sInt));
3465 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003466 } else {
3467 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003468 if (CountInits < NumInits) {
3469 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3470 return Error(E);
3471 } else // trailing float zero.
3472 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3473 Elements.push_back(APValue(f));
3474 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003475 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003476 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003477 }
Richard Smith07fc6572011-10-22 21:10:00 +00003478 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003479}
3480
Richard Smith07fc6572011-10-22 21:10:00 +00003481bool
Richard Smith51201882011-12-30 21:15:51 +00003482VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003483 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003484 QualType EltTy = VT->getElementType();
3485 APValue ZeroElement;
3486 if (EltTy->isIntegerType())
3487 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3488 else
3489 ZeroElement =
3490 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3491
Chris Lattner5f9e2722011-07-23 10:55:15 +00003492 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003493 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003494}
3495
Richard Smith07fc6572011-10-22 21:10:00 +00003496bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003497 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003498 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003499}
3500
Nate Begeman59b5da62009-01-18 03:20:47 +00003501//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003502// Array Evaluation
3503//===----------------------------------------------------------------------===//
3504
3505namespace {
3506 class ArrayExprEvaluator
3507 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003508 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003509 APValue &Result;
3510 public:
3511
Richard Smith180f4792011-11-10 06:34:14 +00003512 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3513 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003514
3515 bool Success(const APValue &V, const Expr *E) {
3516 assert(V.isArray() && "Expected array type");
3517 Result = V;
3518 return true;
3519 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003520
Richard Smith51201882011-12-30 21:15:51 +00003521 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003522 const ConstantArrayType *CAT =
3523 Info.Ctx.getAsConstantArrayType(E->getType());
3524 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003525 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003526
3527 Result = APValue(APValue::UninitArray(), 0,
3528 CAT->getSize().getZExtValue());
3529 if (!Result.hasArrayFiller()) return true;
3530
Richard Smith51201882011-12-30 21:15:51 +00003531 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003532 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003533 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003534 ImplicitValueInitExpr VIE(CAT->getElementType());
3535 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3536 Subobject, &VIE);
3537 }
3538
Richard Smithcc5d4f62011-11-07 09:22:26 +00003539 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003540 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003541 };
3542} // end anonymous namespace
3543
Richard Smith180f4792011-11-10 06:34:14 +00003544static bool EvaluateArray(const Expr *E, const LValue &This,
3545 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003546 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003547 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003548}
3549
3550bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3551 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3552 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003553 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003554
Richard Smith974c5f92011-12-22 01:07:19 +00003555 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3556 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003557 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003558 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3559 LValue LV;
3560 if (!EvaluateLValue(E->getInit(0), LV, Info))
3561 return false;
3562 uint64_t NumElements = CAT->getSize().getZExtValue();
3563 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3564
3565 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003566 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003567 for (uint64_t I = 0; I < NumElements; ++I) {
3568 CCValue Char;
3569 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
Richard Smith745f5142012-01-27 01:14:48 +00003570 CAT->getElementType(), LV, Char) ||
3571 !CheckConstantExpression(Info, E->getInit(0), Char,
3572 Result.getArrayInitializedElt(I)) ||
3573 !HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
Richard Smithb4e85ed2012-01-06 16:39:00 +00003574 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003575 return false;
3576 }
3577 return true;
3578 }
3579
Richard Smith745f5142012-01-27 01:14:48 +00003580 bool Success = true;
3581
Richard Smithcc5d4f62011-11-07 09:22:26 +00003582 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3583 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003584 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003585 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003586 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003587 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003588 I != End; ++I, ++Index) {
3589 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
Richard Smith745f5142012-01-27 01:14:48 +00003590 Info, Subobject, cast<Expr>(*I)) ||
3591 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3592 CAT->getElementType(), 1)) {
3593 if (!Info.keepEvaluatingAfterFailure())
3594 return false;
3595 Success = false;
3596 }
Richard Smith180f4792011-11-10 06:34:14 +00003597 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003598
Richard Smith745f5142012-01-27 01:14:48 +00003599 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003600 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003601 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3602 // but sometimes does:
3603 // struct S { constexpr S() : p(&p) {} void *p; };
3604 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003605 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith745f5142012-01-27 01:14:48 +00003606 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003607}
3608
Richard Smithe24f5fc2011-11-17 22:56:20 +00003609bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3610 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3611 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003612 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003613
Richard Smithec789162012-01-12 18:54:33 +00003614 bool HadZeroInit = !Result.isUninit();
3615 if (!HadZeroInit)
3616 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003617 if (!Result.hasArrayFiller())
3618 return true;
3619
3620 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003621
Richard Smith51201882011-12-30 21:15:51 +00003622 bool ZeroInit = E->requiresZeroInitialization();
3623 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003624 if (HadZeroInit)
3625 return true;
3626
Richard Smith51201882011-12-30 21:15:51 +00003627 if (ZeroInit) {
3628 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003629 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003630 ImplicitValueInitExpr VIE(CAT->getElementType());
3631 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3632 Subobject, &VIE);
3633 }
3634
Richard Smith61802452011-12-22 02:22:31 +00003635 const CXXRecordDecl *RD = FD->getParent();
3636 if (RD->isUnion())
3637 Result.getArrayFiller() = APValue((FieldDecl*)0);
3638 else
3639 Result.getArrayFiller() =
3640 APValue(APValue::UninitStruct(), RD->getNumBases(),
3641 std::distance(RD->field_begin(), RD->field_end()));
3642 return true;
3643 }
3644
Richard Smithe24f5fc2011-11-17 22:56:20 +00003645 const FunctionDecl *Definition = 0;
3646 FD->getBody(Definition);
3647
Richard Smithc1c5f272011-12-13 06:39:58 +00003648 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3649 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003650
3651 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3652 // but sometimes does:
3653 // struct S { constexpr S() : p(&p) {} void *p; };
3654 // S s[10];
3655 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003656 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003657
Richard Smithec789162012-01-12 18:54:33 +00003658 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003659 ImplicitValueInitExpr VIE(CAT->getElementType());
3660 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3661 &VIE))
3662 return false;
3663 }
3664
Richard Smithe24f5fc2011-11-17 22:56:20 +00003665 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003666 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003667 cast<CXXConstructorDecl>(Definition),
3668 Info, Result.getArrayFiller());
3669}
3670
Richard Smithcc5d4f62011-11-07 09:22:26 +00003671//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003672// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003673//
3674// As a GNU extension, we support casting pointers to sufficiently-wide integer
3675// types and back in constant folding. Integer values are thus represented
3676// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003677//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003678
3679namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003680class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003681 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003682 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003683public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003684 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003685 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003686
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003687 bool Success(const llvm::APSInt &SI, const Expr *E) {
3688 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003689 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003690 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003691 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003692 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003693 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003694 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003695 return true;
3696 }
3697
Daniel Dunbar131eb432009-02-19 09:06:44 +00003698 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003699 assert(E->getType()->isIntegralOrEnumerationType() &&
3700 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003701 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003702 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003703 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003704 Result.getInt().setIsUnsigned(
3705 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003706 return true;
3707 }
3708
3709 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003710 assert(E->getType()->isIntegralOrEnumerationType() &&
3711 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003712 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003713 return true;
3714 }
3715
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003716 bool Success(CharUnits Size, const Expr *E) {
3717 return Success(Size.getQuantity(), E);
3718 }
3719
Richard Smith47a1eed2011-10-29 20:57:55 +00003720 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003721 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003722 Result = V;
3723 return true;
3724 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003725 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003726 }
Mike Stump1eb44332009-09-09 15:08:12 +00003727
Richard Smith51201882011-12-30 21:15:51 +00003728 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003729
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003730 //===--------------------------------------------------------------------===//
3731 // Visitor Methods
3732 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003733
Chris Lattner4c4867e2008-07-12 00:38:25 +00003734 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003735 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003736 }
3737 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003738 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003739 }
Eli Friedman04309752009-11-24 05:28:59 +00003740
3741 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3742 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003743 if (CheckReferencedDecl(E, E->getDecl()))
3744 return true;
3745
3746 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003747 }
3748 bool VisitMemberExpr(const MemberExpr *E) {
3749 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003750 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003751 return true;
3752 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003753
3754 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003755 }
3756
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003757 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003758 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003759 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003760 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003761
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003762 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003763 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003764
Anders Carlsson3068d112008-11-16 19:01:22 +00003765 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003766 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003767 }
Mike Stump1eb44332009-09-09 15:08:12 +00003768
Richard Smithf10d9172011-10-11 21:43:33 +00003769 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003770 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003771 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003772 }
3773
Sebastian Redl64b45f72009-01-05 20:52:13 +00003774 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003775 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003776 }
3777
Francois Pichet6ad6f282010-12-07 00:08:36 +00003778 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3779 return Success(E->getValue(), E);
3780 }
3781
John Wiegley21ff2e52011-04-28 00:16:57 +00003782 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3783 return Success(E->getValue(), E);
3784 }
3785
John Wiegley55262202011-04-25 06:54:41 +00003786 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3787 return Success(E->getValue(), E);
3788 }
3789
Eli Friedman722c7172009-02-28 03:59:05 +00003790 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003791 bool VisitUnaryImag(const UnaryOperator *E);
3792
Sebastian Redl295995c2010-09-10 20:55:47 +00003793 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003794 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003795
Chris Lattnerfcee0012008-07-11 21:24:13 +00003796private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003797 CharUnits GetAlignOfExpr(const Expr *E);
3798 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003799 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003800 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003801 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003802};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003803} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003804
Richard Smithc49bd112011-10-28 17:51:58 +00003805/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3806/// produce either the integer value or a pointer.
3807///
3808/// GCC has a heinous extension which folds casts between pointer types and
3809/// pointer-sized integral types. We support this by allowing the evaluation of
3810/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3811/// Some simple arithmetic on such values is supported (they are treated much
3812/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003813static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003814 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003815 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003816 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003817}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003818
Richard Smithf48fdb02011-12-09 22:58:01 +00003819static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003820 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003821 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003822 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003823 if (!Val.isInt()) {
3824 // FIXME: It would be better to produce the diagnostic for casting
3825 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003826 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003827 return false;
3828 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003829 Result = Val.getInt();
3830 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003831}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003832
Richard Smithf48fdb02011-12-09 22:58:01 +00003833/// Check whether the given declaration can be directly converted to an integral
3834/// rvalue. If not, no diagnostic is produced; there are other things we can
3835/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003836bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003837 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003838 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003839 // Check for signedness/width mismatches between E type and ECD value.
3840 bool SameSign = (ECD->getInitVal().isSigned()
3841 == E->getType()->isSignedIntegerOrEnumerationType());
3842 bool SameWidth = (ECD->getInitVal().getBitWidth()
3843 == Info.Ctx.getIntWidth(E->getType()));
3844 if (SameSign && SameWidth)
3845 return Success(ECD->getInitVal(), E);
3846 else {
3847 // Get rid of mismatch (otherwise Success assertions will fail)
3848 // by computing a new value matching the type of E.
3849 llvm::APSInt Val = ECD->getInitVal();
3850 if (!SameSign)
3851 Val.setIsSigned(!ECD->getInitVal().isSigned());
3852 if (!SameWidth)
3853 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3854 return Success(Val, E);
3855 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003856 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003857 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003858}
3859
Chris Lattnera4d55d82008-10-06 06:40:35 +00003860/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3861/// as GCC.
3862static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3863 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003864 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003865 enum gcc_type_class {
3866 no_type_class = -1,
3867 void_type_class, integer_type_class, char_type_class,
3868 enumeral_type_class, boolean_type_class,
3869 pointer_type_class, reference_type_class, offset_type_class,
3870 real_type_class, complex_type_class,
3871 function_type_class, method_type_class,
3872 record_type_class, union_type_class,
3873 array_type_class, string_type_class,
3874 lang_type_class
3875 };
Mike Stump1eb44332009-09-09 15:08:12 +00003876
3877 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003878 // ideal, however it is what gcc does.
3879 if (E->getNumArgs() == 0)
3880 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003881
Chris Lattnera4d55d82008-10-06 06:40:35 +00003882 QualType ArgTy = E->getArg(0)->getType();
3883 if (ArgTy->isVoidType())
3884 return void_type_class;
3885 else if (ArgTy->isEnumeralType())
3886 return enumeral_type_class;
3887 else if (ArgTy->isBooleanType())
3888 return boolean_type_class;
3889 else if (ArgTy->isCharType())
3890 return string_type_class; // gcc doesn't appear to use char_type_class
3891 else if (ArgTy->isIntegerType())
3892 return integer_type_class;
3893 else if (ArgTy->isPointerType())
3894 return pointer_type_class;
3895 else if (ArgTy->isReferenceType())
3896 return reference_type_class;
3897 else if (ArgTy->isRealType())
3898 return real_type_class;
3899 else if (ArgTy->isComplexType())
3900 return complex_type_class;
3901 else if (ArgTy->isFunctionType())
3902 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003903 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003904 return record_type_class;
3905 else if (ArgTy->isUnionType())
3906 return union_type_class;
3907 else if (ArgTy->isArrayType())
3908 return array_type_class;
3909 else if (ArgTy->isUnionType())
3910 return union_type_class;
3911 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003912 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003913}
3914
Richard Smith80d4b552011-12-28 19:48:30 +00003915/// EvaluateBuiltinConstantPForLValue - Determine the result of
3916/// __builtin_constant_p when applied to the given lvalue.
3917///
3918/// An lvalue is only "constant" if it is a pointer or reference to the first
3919/// character of a string literal.
3920template<typename LValue>
3921static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3922 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3923 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3924}
3925
3926/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3927/// GCC as we can manage.
3928static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3929 QualType ArgType = Arg->getType();
3930
3931 // __builtin_constant_p always has one operand. The rules which gcc follows
3932 // are not precisely documented, but are as follows:
3933 //
3934 // - If the operand is of integral, floating, complex or enumeration type,
3935 // and can be folded to a known value of that type, it returns 1.
3936 // - If the operand and can be folded to a pointer to the first character
3937 // of a string literal (or such a pointer cast to an integral type), it
3938 // returns 1.
3939 //
3940 // Otherwise, it returns 0.
3941 //
3942 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3943 // its support for this does not currently work.
3944 if (ArgType->isIntegralOrEnumerationType()) {
3945 Expr::EvalResult Result;
3946 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3947 return false;
3948
3949 APValue &V = Result.Val;
3950 if (V.getKind() == APValue::Int)
3951 return true;
3952
3953 return EvaluateBuiltinConstantPForLValue(V);
3954 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3955 return Arg->isEvaluatable(Ctx);
3956 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3957 LValue LV;
3958 Expr::EvalStatus Status;
3959 EvalInfo Info(Ctx, Status);
3960 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3961 : EvaluatePointer(Arg, LV, Info)) &&
3962 !Status.HasSideEffects)
3963 return EvaluateBuiltinConstantPForLValue(LV);
3964 }
3965
3966 // Anything else isn't considered to be sufficiently constant.
3967 return false;
3968}
3969
John McCall42c8f872010-05-10 23:27:23 +00003970/// Retrieves the "underlying object type" of the given expression,
3971/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003972QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3973 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3974 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003975 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003976 } else if (const Expr *E = B.get<const Expr*>()) {
3977 if (isa<CompoundLiteralExpr>(E))
3978 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003979 }
3980
3981 return QualType();
3982}
3983
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003984bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003985 // TODO: Perhaps we should let LLVM lower this?
3986 LValue Base;
3987 if (!EvaluatePointer(E->getArg(0), Base, Info))
3988 return false;
3989
3990 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003991 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003992
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003993 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003994 if (T.isNull() ||
3995 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00003996 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00003997 T->isVariablyModifiedType() ||
3998 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003999 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004000
4001 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4002 CharUnits Offset = Base.getLValueOffset();
4003
4004 if (!Offset.isNegative() && Offset <= Size)
4005 Size -= Offset;
4006 else
4007 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004008 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004009}
4010
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004011bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004012 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004013 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004014 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004015
4016 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004017 if (TryEvaluateBuiltinObjectSize(E))
4018 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004019
Eric Christopherb2aaf512010-01-19 22:58:35 +00004020 // If evaluating the argument has side-effects we can't determine
4021 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004022 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004023 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004024 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004025 return Success(0, E);
4026 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004027
Richard Smithf48fdb02011-12-09 22:58:01 +00004028 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004029 }
4030
Chris Lattner019f4e82008-10-06 05:28:25 +00004031 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004032 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004033
Richard Smith80d4b552011-12-28 19:48:30 +00004034 case Builtin::BI__builtin_constant_p:
4035 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004036
Chris Lattner21fb98e2009-09-23 06:06:36 +00004037 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004038 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004039 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004040 return Success(Operand, E);
4041 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004042
4043 case Builtin::BI__builtin_expect:
4044 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004045
Douglas Gregor5726d402010-09-10 06:27:15 +00004046 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004047 // A call to strlen is not a constant expression.
4048 if (Info.getLangOpts().CPlusPlus0x)
4049 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4050 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4051 else
4052 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4053 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004054 case Builtin::BI__builtin_strlen:
4055 // As an extension, we support strlen() and __builtin_strlen() as constant
4056 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004057 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004058 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4059 // The string literal may have embedded null characters. Find the first
4060 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004061 StringRef Str = S->getString();
4062 StringRef::size_type Pos = Str.find(0);
4063 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004064 Str = Str.substr(0, Pos);
4065
4066 return Success(Str.size(), E);
4067 }
4068
Richard Smithf48fdb02011-12-09 22:58:01 +00004069 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004070
4071 case Builtin::BI__atomic_is_lock_free: {
4072 APSInt SizeVal;
4073 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4074 return false;
4075
4076 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4077 // of two less than the maximum inline atomic width, we know it is
4078 // lock-free. If the size isn't a power of two, or greater than the
4079 // maximum alignment where we promote atomics, we know it is not lock-free
4080 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4081 // the answer can only be determined at runtime; for example, 16-byte
4082 // atomics have lock-free implementations on some, but not all,
4083 // x86-64 processors.
4084
4085 // Check power-of-two.
4086 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4087 if (!Size.isPowerOfTwo())
4088#if 0
4089 // FIXME: Suppress this folding until the ABI for the promotion width
4090 // settles.
4091 return Success(0, E);
4092#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004093 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004094#endif
4095
4096#if 0
4097 // Check against promotion width.
4098 // FIXME: Suppress this folding until the ABI for the promotion width
4099 // settles.
4100 unsigned PromoteWidthBits =
4101 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4102 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4103 return Success(0, E);
4104#endif
4105
4106 // Check against inlining width.
4107 unsigned InlineWidthBits =
4108 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4109 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4110 return Success(1, E);
4111
Richard Smithf48fdb02011-12-09 22:58:01 +00004112 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004113 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004114 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004115}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004116
Richard Smith625b8072011-10-31 01:37:14 +00004117static bool HasSameBase(const LValue &A, const LValue &B) {
4118 if (!A.getLValueBase())
4119 return !B.getLValueBase();
4120 if (!B.getLValueBase())
4121 return false;
4122
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004123 if (A.getLValueBase().getOpaqueValue() !=
4124 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004125 const Decl *ADecl = GetLValueBaseDecl(A);
4126 if (!ADecl)
4127 return false;
4128 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004129 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004130 return false;
4131 }
4132
4133 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00004134 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00004135}
4136
Chris Lattnerb542afe2008-07-11 19:10:17 +00004137bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004138 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004139 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004140
John McCall2de56d12010-08-25 11:45:40 +00004141 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004142 VisitIgnoredValue(E->getLHS());
4143 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004144 }
4145
4146 if (E->isLogicalOp()) {
4147 // These need to be handled specially because the operands aren't
4148 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004149 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004150
Richard Smithc49bd112011-10-28 17:51:58 +00004151 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004152 // We were able to evaluate the LHS, see if we can get away with not
4153 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004154 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004155 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004156
Richard Smithc49bd112011-10-28 17:51:58 +00004157 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004158 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004159 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004160 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004161 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004162 }
4163 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004164 // FIXME: If both evaluations fail, we should produce the diagnostic from
4165 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4166 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00004167 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004168 // We can't evaluate the LHS; however, sometimes the result
4169 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00004170 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004171 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004172 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00004173 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004174
4175 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004176 }
4177 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004178 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004179
Eli Friedmana6afa762008-11-13 06:09:17 +00004180 return false;
4181 }
4182
Anders Carlsson286f85e2008-11-16 07:17:21 +00004183 QualType LHSTy = E->getLHS()->getType();
4184 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004185
4186 if (LHSTy->isAnyComplexType()) {
4187 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004188 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004189
Richard Smith745f5142012-01-27 01:14:48 +00004190 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4191 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004192 return false;
4193
Richard Smith745f5142012-01-27 01:14:48 +00004194 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004195 return false;
4196
4197 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004198 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004199 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004200 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004201 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4202
John McCall2de56d12010-08-25 11:45:40 +00004203 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004204 return Success((CR_r == APFloat::cmpEqual &&
4205 CR_i == APFloat::cmpEqual), E);
4206 else {
John McCall2de56d12010-08-25 11:45:40 +00004207 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004208 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004209 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004210 CR_r == APFloat::cmpLessThan ||
4211 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004212 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004213 CR_i == APFloat::cmpLessThan ||
4214 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004215 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004216 } else {
John McCall2de56d12010-08-25 11:45:40 +00004217 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004218 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4219 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4220 else {
John McCall2de56d12010-08-25 11:45:40 +00004221 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004222 "Invalid compex comparison.");
4223 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4224 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4225 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004226 }
4227 }
Mike Stump1eb44332009-09-09 15:08:12 +00004228
Anders Carlsson286f85e2008-11-16 07:17:21 +00004229 if (LHSTy->isRealFloatingType() &&
4230 RHSTy->isRealFloatingType()) {
4231 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004232
Richard Smith745f5142012-01-27 01:14:48 +00004233 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4234 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004235 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004236
Richard Smith745f5142012-01-27 01:14:48 +00004237 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004238 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004239
Anders Carlsson286f85e2008-11-16 07:17:21 +00004240 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004241
Anders Carlsson286f85e2008-11-16 07:17:21 +00004242 switch (E->getOpcode()) {
4243 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004244 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004245 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004246 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004247 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004248 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004249 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004250 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004251 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004252 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004253 E);
John McCall2de56d12010-08-25 11:45:40 +00004254 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004255 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004256 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004257 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004258 || CR == APFloat::cmpLessThan
4259 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004260 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004261 }
Mike Stump1eb44332009-09-09 15:08:12 +00004262
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004263 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004264 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004265 LValue LHSValue, RHSValue;
4266
4267 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4268 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004269 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004270
Richard Smith745f5142012-01-27 01:14:48 +00004271 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004272 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004273
Richard Smith625b8072011-10-31 01:37:14 +00004274 // Reject differing bases from the normal codepath; we special-case
4275 // comparisons to null.
4276 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004277 if (E->getOpcode() == BO_Sub) {
4278 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004279 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4280 return false;
4281 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4282 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4283 if (!LHSExpr || !RHSExpr)
4284 return false;
4285 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4286 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4287 if (!LHSAddrExpr || !RHSAddrExpr)
4288 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004289 // Make sure both labels come from the same function.
4290 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4291 RHSAddrExpr->getLabel()->getDeclContext())
4292 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004293 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4294 return true;
4295 }
Richard Smith9e36b532011-10-31 05:11:32 +00004296 // Inequalities and subtractions between unrelated pointers have
4297 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004298 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004299 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004300 // A constant address may compare equal to the address of a symbol.
4301 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004302 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004303 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4304 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004305 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004306 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004307 // distinct addresses. In clang, the result of such a comparison is
4308 // unspecified, so it is not a constant expression. However, we do know
4309 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004310 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4311 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004312 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004313 // We can't tell whether weak symbols will end up pointing to the same
4314 // object.
4315 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004316 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004317 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004318 // (Note that clang defaults to -fmerge-all-constants, which can
4319 // lead to inconsistent results for comparisons involving the address
4320 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004321 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004322 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004323
Richard Smithcc5d4f62011-11-07 09:22:26 +00004324 // FIXME: Implement the C++11 restrictions:
4325 // - Pointer subtractions must be on elements of the same array.
4326 // - Pointer comparisons must be between members with the same access.
4327
John McCall2de56d12010-08-25 11:45:40 +00004328 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00004329 QualType Type = E->getLHS()->getType();
4330 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004331
Richard Smith180f4792011-11-10 06:34:14 +00004332 CharUnits ElementSize;
4333 if (!HandleSizeof(Info, ElementType, ElementSize))
4334 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004335
Richard Smith180f4792011-11-10 06:34:14 +00004336 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00004337 RHSValue.getLValueOffset();
4338 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004339 }
Richard Smith625b8072011-10-31 01:37:14 +00004340
4341 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4342 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith82f28582012-01-31 06:41:30 +00004343
4344 // C++11 [expr.rel]p3:
4345 // Pointers to void (after pointer conversions) can be compared, with a
4346 // result defined as follows: If both pointers represent the same
4347 // address or are both the null pointer value, the result is true if the
4348 // operator is <= or >= and false otherwise; otherwise the result is
4349 // unspecified.
4350 // We interpret this as applying to pointers to *cv* void.
4351 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
4352 E->getOpcode() != BO_EQ && E->getOpcode() != BO_NE)
4353 CCEDiag(E, diag::note_constexpr_void_comparison);
4354
Richard Smith625b8072011-10-31 01:37:14 +00004355 switch (E->getOpcode()) {
4356 default: llvm_unreachable("missing comparison operator");
4357 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4358 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4359 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4360 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4361 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4362 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004363 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004364 }
4365 }
Richard Smithb02e4622012-02-01 01:42:44 +00004366
4367 if (LHSTy->isMemberPointerType()) {
4368 assert(E->isEqualityOp() && "unexpected member pointer operation");
4369 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4370
4371 MemberPtr LHSValue, RHSValue;
4372
4373 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4374 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4375 return false;
4376
4377 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4378 return false;
4379
4380 // C++11 [expr.eq]p2:
4381 // If both operands are null, they compare equal. Otherwise if only one is
4382 // null, they compare unequal.
4383 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4384 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4385 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4386 }
4387
4388 // Otherwise if either is a pointer to a virtual member function, the
4389 // result is unspecified.
4390 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4391 if (MD->isVirtual())
4392 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4393 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4394 if (MD->isVirtual())
4395 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4396
4397 // Otherwise they compare equal if and only if they would refer to the
4398 // same member of the same most derived object or the same subobject if
4399 // they were dereferenced with a hypothetical object of the associated
4400 // class type.
4401 bool Equal = LHSValue == RHSValue;
4402 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4403 }
4404
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004405 if (!LHSTy->isIntegralOrEnumerationType() ||
4406 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004407 // We can't continue from here for non-integral types.
4408 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004409 }
4410
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004411 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004412 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004413
4414 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4415 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004416 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004417
Richard Smith745f5142012-01-27 01:14:48 +00004418 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004419 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004420
Richard Smith47a1eed2011-10-29 20:57:55 +00004421 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004422
4423 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004424 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004425 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4426 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004427 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004428 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004429 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004430 LHSVal.getLValueOffset() -= AdditionalOffset;
4431 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004432 return true;
4433 }
4434
4435 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004436 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004437 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004438 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4439 LHSVal.getInt().getZExtValue());
4440 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004441 return true;
4442 }
4443
Eli Friedman65639282012-01-04 23:13:47 +00004444 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4445 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004446 if (!LHSVal.getLValueOffset().isZero() ||
4447 !RHSVal.getLValueOffset().isZero())
4448 return false;
4449 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4450 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4451 if (!LHSExpr || !RHSExpr)
4452 return false;
4453 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4454 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4455 if (!LHSAddrExpr || !RHSAddrExpr)
4456 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004457 // Make sure both labels come from the same function.
4458 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4459 RHSAddrExpr->getLabel()->getDeclContext())
4460 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004461 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4462 return true;
4463 }
4464
Eli Friedman42edd0d2009-03-24 01:14:50 +00004465 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004466 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004467 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004468
Richard Smithc49bd112011-10-28 17:51:58 +00004469 APSInt &LHS = LHSVal.getInt();
4470 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004471
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004472 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004473 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004474 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004475 case BO_Mul: return Success(LHS * RHS, E);
4476 case BO_Add: return Success(LHS + RHS, E);
4477 case BO_Sub: return Success(LHS - RHS, E);
4478 case BO_And: return Success(LHS & RHS, E);
4479 case BO_Xor: return Success(LHS ^ RHS, E);
4480 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004481 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004482 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004483 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004484 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004485 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4486 // actually undefined behavior in C++11 due to a language defect.
4487 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4488 LHS.isSigned() && LHS.isMinSignedValue())
4489 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4490 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004491 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004492 // During constant-folding, a negative shift is an opposite shift. Such a
4493 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004494 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004495 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004496 RHS = -RHS;
4497 goto shift_right;
4498 }
4499
4500 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004501 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4502 // shifted type.
4503 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4504 if (SA != RHS) {
4505 CCEDiag(E, diag::note_constexpr_large_shift)
4506 << RHS << E->getType() << LHS.getBitWidth();
4507 } else if (LHS.isSigned()) {
4508 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4509 // operand, and must not overflow.
4510 if (LHS.isNegative())
4511 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4512 else if (LHS.countLeadingZeros() <= SA)
4513 HandleOverflow(Info, E, LHS.extend(LHS.getBitWidth() + SA) << SA,
4514 E->getType());
4515 }
4516
Richard Smithc49bd112011-10-28 17:51:58 +00004517 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004518 }
John McCall2de56d12010-08-25 11:45:40 +00004519 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004520 // During constant-folding, a negative shift is an opposite shift. Such a
4521 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004522 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004523 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004524 RHS = -RHS;
4525 goto shift_left;
4526 }
4527
4528 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004529 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4530 // shifted type.
4531 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4532 if (SA != RHS)
4533 CCEDiag(E, diag::note_constexpr_large_shift)
4534 << RHS << E->getType() << LHS.getBitWidth();
4535
Richard Smithc49bd112011-10-28 17:51:58 +00004536 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004537 }
Mike Stump1eb44332009-09-09 15:08:12 +00004538
Richard Smithc49bd112011-10-28 17:51:58 +00004539 case BO_LT: return Success(LHS < RHS, E);
4540 case BO_GT: return Success(LHS > RHS, E);
4541 case BO_LE: return Success(LHS <= RHS, E);
4542 case BO_GE: return Success(LHS >= RHS, E);
4543 case BO_EQ: return Success(LHS == RHS, E);
4544 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004545 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004546}
4547
Ken Dyck8b752f12010-01-27 17:10:57 +00004548CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004549 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4550 // the result is the size of the referenced type."
4551 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4552 // result shall be the alignment of the referenced type."
4553 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4554 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004555
4556 // __alignof is defined to return the preferred alignment.
4557 return Info.Ctx.toCharUnitsFromBits(
4558 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004559}
4560
Ken Dyck8b752f12010-01-27 17:10:57 +00004561CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004562 E = E->IgnoreParens();
4563
4564 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004565 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004566 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004567 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4568 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004569
Chris Lattneraf707ab2009-01-24 21:53:27 +00004570 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004571 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4572 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004573
Chris Lattnere9feb472009-01-24 21:09:06 +00004574 return GetAlignOfType(E->getType());
4575}
4576
4577
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004578/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4579/// a result as the expression's type.
4580bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4581 const UnaryExprOrTypeTraitExpr *E) {
4582 switch(E->getKind()) {
4583 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004584 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004585 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004586 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004587 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004588 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004589
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004590 case UETT_VecStep: {
4591 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004592
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004593 if (Ty->isVectorType()) {
4594 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004595
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004596 // The vec_step built-in functions that take a 3-component
4597 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4598 if (n == 3)
4599 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004600
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004601 return Success(n, E);
4602 } else
4603 return Success(1, E);
4604 }
4605
4606 case UETT_SizeOf: {
4607 QualType SrcTy = E->getTypeOfArgument();
4608 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4609 // the result is the size of the referenced type."
4610 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4611 // result shall be the alignment of the referenced type."
4612 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4613 SrcTy = Ref->getPointeeType();
4614
Richard Smith180f4792011-11-10 06:34:14 +00004615 CharUnits Sizeof;
4616 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004617 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004618 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004619 }
4620 }
4621
4622 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004623}
4624
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004625bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004626 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004627 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004628 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004629 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004630 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004631 for (unsigned i = 0; i != n; ++i) {
4632 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4633 switch (ON.getKind()) {
4634 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004635 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004636 APSInt IdxResult;
4637 if (!EvaluateInteger(Idx, IdxResult, Info))
4638 return false;
4639 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4640 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004641 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004642 CurrentType = AT->getElementType();
4643 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4644 Result += IdxResult.getSExtValue() * ElementSize;
4645 break;
4646 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004647
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004648 case OffsetOfExpr::OffsetOfNode::Field: {
4649 FieldDecl *MemberDecl = ON.getField();
4650 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004651 if (!RT)
4652 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004653 RecordDecl *RD = RT->getDecl();
4654 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004655 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004656 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004657 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004658 CurrentType = MemberDecl->getType().getNonReferenceType();
4659 break;
4660 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004661
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004662 case OffsetOfExpr::OffsetOfNode::Identifier:
4663 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004664
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004665 case OffsetOfExpr::OffsetOfNode::Base: {
4666 CXXBaseSpecifier *BaseSpec = ON.getBase();
4667 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004668 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004669
4670 // Find the layout of the class whose base we are looking into.
4671 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004672 if (!RT)
4673 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004674 RecordDecl *RD = RT->getDecl();
4675 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4676
4677 // Find the base class itself.
4678 CurrentType = BaseSpec->getType();
4679 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4680 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004681 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004682
4683 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004684 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004685 break;
4686 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004687 }
4688 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004689 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004690}
4691
Chris Lattnerb542afe2008-07-11 19:10:17 +00004692bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004693 switch (E->getOpcode()) {
4694 default:
4695 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4696 // See C99 6.6p3.
4697 return Error(E);
4698 case UO_Extension:
4699 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4700 // If so, we could clear the diagnostic ID.
4701 return Visit(E->getSubExpr());
4702 case UO_Plus:
4703 // The result is just the value.
4704 return Visit(E->getSubExpr());
4705 case UO_Minus: {
4706 if (!Visit(E->getSubExpr()))
4707 return false;
4708 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00004709 const APSInt &Value = Result.getInt();
4710 if (Value.isSigned() && Value.isMinSignedValue())
4711 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
4712 E->getType());
4713 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00004714 }
4715 case UO_Not: {
4716 if (!Visit(E->getSubExpr()))
4717 return false;
4718 if (!Result.isInt()) return Error(E);
4719 return Success(~Result.getInt(), E);
4720 }
4721 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004722 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004723 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004724 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004725 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004726 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004727 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004728}
Mike Stump1eb44332009-09-09 15:08:12 +00004729
Chris Lattner732b2232008-07-12 01:15:53 +00004730/// HandleCast - This is used to evaluate implicit or explicit casts where the
4731/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004732bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4733 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004734 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004735 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004736
Eli Friedman46a52322011-03-25 00:43:55 +00004737 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004738 case CK_BaseToDerived:
4739 case CK_DerivedToBase:
4740 case CK_UncheckedDerivedToBase:
4741 case CK_Dynamic:
4742 case CK_ToUnion:
4743 case CK_ArrayToPointerDecay:
4744 case CK_FunctionToPointerDecay:
4745 case CK_NullToPointer:
4746 case CK_NullToMemberPointer:
4747 case CK_BaseToDerivedMemberPointer:
4748 case CK_DerivedToBaseMemberPointer:
4749 case CK_ConstructorConversion:
4750 case CK_IntegralToPointer:
4751 case CK_ToVoid:
4752 case CK_VectorSplat:
4753 case CK_IntegralToFloating:
4754 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004755 case CK_CPointerToObjCPointerCast:
4756 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004757 case CK_AnyPointerToBlockPointerCast:
4758 case CK_ObjCObjectLValueCast:
4759 case CK_FloatingRealToComplex:
4760 case CK_FloatingComplexToReal:
4761 case CK_FloatingComplexCast:
4762 case CK_FloatingComplexToIntegralComplex:
4763 case CK_IntegralRealToComplex:
4764 case CK_IntegralComplexCast:
4765 case CK_IntegralComplexToFloatingComplex:
4766 llvm_unreachable("invalid cast kind for integral value");
4767
Eli Friedmane50c2972011-03-25 19:07:11 +00004768 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004769 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004770 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00004771 case CK_ARCProduceObject:
4772 case CK_ARCConsumeObject:
4773 case CK_ARCReclaimReturnedObject:
4774 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004775 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004776
Richard Smith7d580a42012-01-17 21:17:26 +00004777 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00004778 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00004779 case CK_AtomicToNonAtomic:
4780 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00004781 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004782 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004783
4784 case CK_MemberPointerToBoolean:
4785 case CK_PointerToBoolean:
4786 case CK_IntegralToBoolean:
4787 case CK_FloatingToBoolean:
4788 case CK_FloatingComplexToBoolean:
4789 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004790 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004791 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004792 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004793 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004794 }
4795
Eli Friedman46a52322011-03-25 00:43:55 +00004796 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004797 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004798 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004799
Eli Friedmanbe265702009-02-20 01:15:07 +00004800 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00004801 // Allow casts of address-of-label differences if they are no-ops
4802 // or narrowing. (The narrowing case isn't actually guaranteed to
4803 // be constant-evaluatable except in some narrow cases which are hard
4804 // to detect here. We let it through on the assumption the user knows
4805 // what they are doing.)
4806 if (Result.isAddrLabelDiff())
4807 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00004808 // Only allow casts of lvalues if they are lossless.
4809 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4810 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004811
Richard Smithf72fccf2012-01-30 22:27:01 +00004812 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
4813 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00004814 }
Mike Stump1eb44332009-09-09 15:08:12 +00004815
Eli Friedman46a52322011-03-25 00:43:55 +00004816 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00004817 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4818
John McCallefdb83e2010-05-07 21:00:08 +00004819 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00004820 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004821 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00004822
Daniel Dunbardd211642009-02-19 22:24:01 +00004823 if (LV.getLValueBase()) {
4824 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00004825 // FIXME: Allow a larger integer size than the pointer size, and allow
4826 // narrowing back down to pointer width in subsequent integral casts.
4827 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00004828 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00004829 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004830
Richard Smithb755a9d2011-11-16 07:18:12 +00004831 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004832 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00004833 return true;
4834 }
4835
Ken Dycka7305832010-01-15 12:37:54 +00004836 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4837 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00004838 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00004839 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004840
Eli Friedman46a52322011-03-25 00:43:55 +00004841 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00004842 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00004843 if (!EvaluateComplex(SubExpr, C, Info))
4844 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00004845 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00004846 }
Eli Friedman2217c872009-02-22 11:46:18 +00004847
Eli Friedman46a52322011-03-25 00:43:55 +00004848 case CK_FloatingToIntegral: {
4849 APFloat F(0.0);
4850 if (!EvaluateFloat(SubExpr, F, Info))
4851 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00004852
Richard Smithc1c5f272011-12-13 06:39:58 +00004853 APSInt Value;
4854 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4855 return false;
4856 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00004857 }
4858 }
Mike Stump1eb44332009-09-09 15:08:12 +00004859
Eli Friedman46a52322011-03-25 00:43:55 +00004860 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004861}
Anders Carlsson2bad1682008-07-08 14:30:00 +00004862
Eli Friedman722c7172009-02-28 03:59:05 +00004863bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4864 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004865 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004866 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4867 return false;
4868 if (!LV.isComplexInt())
4869 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004870 return Success(LV.getComplexIntReal(), E);
4871 }
4872
4873 return Visit(E->getSubExpr());
4874}
4875
Eli Friedman664a1042009-02-27 04:45:43 +00004876bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004877 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004878 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004879 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4880 return false;
4881 if (!LV.isComplexInt())
4882 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004883 return Success(LV.getComplexIntImag(), E);
4884 }
4885
Richard Smith8327fad2011-10-24 18:44:57 +00004886 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004887 return Success(0, E);
4888}
4889
Douglas Gregoree8aff02011-01-04 17:33:58 +00004890bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4891 return Success(E->getPackLength(), E);
4892}
4893
Sebastian Redl295995c2010-09-10 20:55:47 +00004894bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4895 return Success(E->getValue(), E);
4896}
4897
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004898//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004899// Float Evaluation
4900//===----------------------------------------------------------------------===//
4901
4902namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004903class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004904 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004905 APFloat &Result;
4906public:
4907 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004908 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004909
Richard Smith47a1eed2011-10-29 20:57:55 +00004910 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004911 Result = V.getFloat();
4912 return true;
4913 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004914
Richard Smith51201882011-12-30 21:15:51 +00004915 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00004916 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4917 return true;
4918 }
4919
Chris Lattner019f4e82008-10-06 05:28:25 +00004920 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004921
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004922 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004923 bool VisitBinaryOperator(const BinaryOperator *E);
4924 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004925 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004926
John McCallabd3a852010-05-07 22:08:54 +00004927 bool VisitUnaryReal(const UnaryOperator *E);
4928 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004929
Richard Smith51201882011-12-30 21:15:51 +00004930 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004931};
4932} // end anonymous namespace
4933
4934static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004935 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004936 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004937}
4938
Jay Foad4ba2a172011-01-12 09:06:06 +00004939static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004940 QualType ResultTy,
4941 const Expr *Arg,
4942 bool SNaN,
4943 llvm::APFloat &Result) {
4944 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4945 if (!S) return false;
4946
4947 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4948
4949 llvm::APInt fill;
4950
4951 // Treat empty strings as if they were zero.
4952 if (S->getString().empty())
4953 fill = llvm::APInt(32, 0);
4954 else if (S->getString().getAsInteger(0, fill))
4955 return false;
4956
4957 if (SNaN)
4958 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4959 else
4960 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4961 return true;
4962}
4963
Chris Lattner019f4e82008-10-06 05:28:25 +00004964bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004965 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004966 default:
4967 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4968
Chris Lattner019f4e82008-10-06 05:28:25 +00004969 case Builtin::BI__builtin_huge_val:
4970 case Builtin::BI__builtin_huge_valf:
4971 case Builtin::BI__builtin_huge_vall:
4972 case Builtin::BI__builtin_inf:
4973 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004974 case Builtin::BI__builtin_infl: {
4975 const llvm::fltSemantics &Sem =
4976 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00004977 Result = llvm::APFloat::getInf(Sem);
4978 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004979 }
Mike Stump1eb44332009-09-09 15:08:12 +00004980
John McCalldb7b72a2010-02-28 13:00:19 +00004981 case Builtin::BI__builtin_nans:
4982 case Builtin::BI__builtin_nansf:
4983 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00004984 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4985 true, Result))
4986 return Error(E);
4987 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00004988
Chris Lattner9e621712008-10-06 06:31:58 +00004989 case Builtin::BI__builtin_nan:
4990 case Builtin::BI__builtin_nanf:
4991 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00004992 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00004993 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00004994 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4995 false, Result))
4996 return Error(E);
4997 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004998
4999 case Builtin::BI__builtin_fabs:
5000 case Builtin::BI__builtin_fabsf:
5001 case Builtin::BI__builtin_fabsl:
5002 if (!EvaluateFloat(E->getArg(0), Result, Info))
5003 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005004
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005005 if (Result.isNegative())
5006 Result.changeSign();
5007 return true;
5008
Mike Stump1eb44332009-09-09 15:08:12 +00005009 case Builtin::BI__builtin_copysign:
5010 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005011 case Builtin::BI__builtin_copysignl: {
5012 APFloat RHS(0.);
5013 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5014 !EvaluateFloat(E->getArg(1), RHS, Info))
5015 return false;
5016 Result.copySign(RHS);
5017 return true;
5018 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005019 }
5020}
5021
John McCallabd3a852010-05-07 22:08:54 +00005022bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005023 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5024 ComplexValue CV;
5025 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5026 return false;
5027 Result = CV.FloatReal;
5028 return true;
5029 }
5030
5031 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005032}
5033
5034bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005035 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5036 ComplexValue CV;
5037 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5038 return false;
5039 Result = CV.FloatImag;
5040 return true;
5041 }
5042
Richard Smith8327fad2011-10-24 18:44:57 +00005043 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005044 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5045 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005046 return true;
5047}
5048
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005049bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005050 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005051 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005052 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005053 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005054 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005055 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5056 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005057 Result.changeSign();
5058 return true;
5059 }
5060}
Chris Lattner019f4e82008-10-06 05:28:25 +00005061
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005062bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005063 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5064 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005065
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005066 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005067 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5068 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005069 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005070 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005071 return false;
5072
5073 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005074 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005075 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005076 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
5077 return true;
John McCall2de56d12010-08-25 11:45:40 +00005078 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005079 Result.add(RHS, APFloat::rmNearestTiesToEven);
5080 return true;
John McCall2de56d12010-08-25 11:45:40 +00005081 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005082 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
5083 return true;
John McCall2de56d12010-08-25 11:45:40 +00005084 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005085 Result.divide(RHS, APFloat::rmNearestTiesToEven);
5086 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005087 }
5088}
5089
5090bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5091 Result = E->getValue();
5092 return true;
5093}
5094
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005095bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5096 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005097
Eli Friedman2a523ee2011-03-25 00:54:52 +00005098 switch (E->getCastKind()) {
5099 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005100 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005101
5102 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005103 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005104 return EvaluateInteger(SubExpr, IntResult, Info) &&
5105 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5106 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005107 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005108
5109 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005110 if (!Visit(SubExpr))
5111 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005112 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5113 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005114 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005115
Eli Friedman2a523ee2011-03-25 00:54:52 +00005116 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005117 ComplexValue V;
5118 if (!EvaluateComplex(SubExpr, V, Info))
5119 return false;
5120 Result = V.getComplexFloatReal();
5121 return true;
5122 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005123 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005124}
5125
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005126//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005127// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005128//===----------------------------------------------------------------------===//
5129
5130namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005131class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005132 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005133 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005134
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005135public:
John McCallf4cf1a12010-05-07 17:22:02 +00005136 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005137 : ExprEvaluatorBaseTy(info), Result(Result) {}
5138
Richard Smith47a1eed2011-10-29 20:57:55 +00005139 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005140 Result.setFrom(V);
5141 return true;
5142 }
Mike Stump1eb44332009-09-09 15:08:12 +00005143
Eli Friedman7ead5c72012-01-10 04:58:17 +00005144 bool ZeroInitialization(const Expr *E);
5145
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005146 //===--------------------------------------------------------------------===//
5147 // Visitor Methods
5148 //===--------------------------------------------------------------------===//
5149
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005150 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005151 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005152 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005153 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005154 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005155};
5156} // end anonymous namespace
5157
John McCallf4cf1a12010-05-07 17:22:02 +00005158static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5159 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005160 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005161 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005162}
5163
Eli Friedman7ead5c72012-01-10 04:58:17 +00005164bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005165 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005166 if (ElemTy->isRealFloatingType()) {
5167 Result.makeComplexFloat();
5168 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5169 Result.FloatReal = Zero;
5170 Result.FloatImag = Zero;
5171 } else {
5172 Result.makeComplexInt();
5173 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5174 Result.IntReal = Zero;
5175 Result.IntImag = Zero;
5176 }
5177 return true;
5178}
5179
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005180bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5181 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005182
5183 if (SubExpr->getType()->isRealFloatingType()) {
5184 Result.makeComplexFloat();
5185 APFloat &Imag = Result.FloatImag;
5186 if (!EvaluateFloat(SubExpr, Imag, Info))
5187 return false;
5188
5189 Result.FloatReal = APFloat(Imag.getSemantics());
5190 return true;
5191 } else {
5192 assert(SubExpr->getType()->isIntegerType() &&
5193 "Unexpected imaginary literal.");
5194
5195 Result.makeComplexInt();
5196 APSInt &Imag = Result.IntImag;
5197 if (!EvaluateInteger(SubExpr, Imag, Info))
5198 return false;
5199
5200 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5201 return true;
5202 }
5203}
5204
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005205bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005206
John McCall8786da72010-12-14 17:51:41 +00005207 switch (E->getCastKind()) {
5208 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005209 case CK_BaseToDerived:
5210 case CK_DerivedToBase:
5211 case CK_UncheckedDerivedToBase:
5212 case CK_Dynamic:
5213 case CK_ToUnion:
5214 case CK_ArrayToPointerDecay:
5215 case CK_FunctionToPointerDecay:
5216 case CK_NullToPointer:
5217 case CK_NullToMemberPointer:
5218 case CK_BaseToDerivedMemberPointer:
5219 case CK_DerivedToBaseMemberPointer:
5220 case CK_MemberPointerToBoolean:
5221 case CK_ConstructorConversion:
5222 case CK_IntegralToPointer:
5223 case CK_PointerToIntegral:
5224 case CK_PointerToBoolean:
5225 case CK_ToVoid:
5226 case CK_VectorSplat:
5227 case CK_IntegralCast:
5228 case CK_IntegralToBoolean:
5229 case CK_IntegralToFloating:
5230 case CK_FloatingToIntegral:
5231 case CK_FloatingToBoolean:
5232 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005233 case CK_CPointerToObjCPointerCast:
5234 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005235 case CK_AnyPointerToBlockPointerCast:
5236 case CK_ObjCObjectLValueCast:
5237 case CK_FloatingComplexToReal:
5238 case CK_FloatingComplexToBoolean:
5239 case CK_IntegralComplexToReal:
5240 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005241 case CK_ARCProduceObject:
5242 case CK_ARCConsumeObject:
5243 case CK_ARCReclaimReturnedObject:
5244 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005245 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005246
John McCall8786da72010-12-14 17:51:41 +00005247 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005248 case CK_AtomicToNonAtomic:
5249 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005250 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005251 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005252
5253 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005254 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005255 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005256 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005257
5258 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005259 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005260 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005261 return false;
5262
John McCall8786da72010-12-14 17:51:41 +00005263 Result.makeComplexFloat();
5264 Result.FloatImag = APFloat(Real.getSemantics());
5265 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005266 }
5267
John McCall8786da72010-12-14 17:51:41 +00005268 case CK_FloatingComplexCast: {
5269 if (!Visit(E->getSubExpr()))
5270 return false;
5271
5272 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5273 QualType From
5274 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5275
Richard Smithc1c5f272011-12-13 06:39:58 +00005276 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5277 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005278 }
5279
5280 case CK_FloatingComplexToIntegralComplex: {
5281 if (!Visit(E->getSubExpr()))
5282 return false;
5283
5284 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5285 QualType From
5286 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5287 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005288 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5289 To, Result.IntReal) &&
5290 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5291 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005292 }
5293
5294 case CK_IntegralRealToComplex: {
5295 APSInt &Real = Result.IntReal;
5296 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5297 return false;
5298
5299 Result.makeComplexInt();
5300 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5301 return true;
5302 }
5303
5304 case CK_IntegralComplexCast: {
5305 if (!Visit(E->getSubExpr()))
5306 return false;
5307
5308 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5309 QualType From
5310 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5311
Richard Smithf72fccf2012-01-30 22:27:01 +00005312 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5313 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005314 return true;
5315 }
5316
5317 case CK_IntegralComplexToFloatingComplex: {
5318 if (!Visit(E->getSubExpr()))
5319 return false;
5320
5321 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5322 QualType From
5323 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5324 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005325 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5326 To, Result.FloatReal) &&
5327 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5328 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005329 }
5330 }
5331
5332 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005333}
5334
John McCallf4cf1a12010-05-07 17:22:02 +00005335bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005336 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005337 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5338
Richard Smith745f5142012-01-27 01:14:48 +00005339 bool LHSOK = Visit(E->getLHS());
5340 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005341 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005342
John McCallf4cf1a12010-05-07 17:22:02 +00005343 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005344 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005345 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005346
Daniel Dunbar3f279872009-01-29 01:32:56 +00005347 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5348 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005349 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005350 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005351 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005352 if (Result.isComplexFloat()) {
5353 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5354 APFloat::rmNearestTiesToEven);
5355 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5356 APFloat::rmNearestTiesToEven);
5357 } else {
5358 Result.getComplexIntReal() += RHS.getComplexIntReal();
5359 Result.getComplexIntImag() += RHS.getComplexIntImag();
5360 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005361 break;
John McCall2de56d12010-08-25 11:45:40 +00005362 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005363 if (Result.isComplexFloat()) {
5364 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5365 APFloat::rmNearestTiesToEven);
5366 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5367 APFloat::rmNearestTiesToEven);
5368 } else {
5369 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5370 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5371 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005372 break;
John McCall2de56d12010-08-25 11:45:40 +00005373 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005374 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005375 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005376 APFloat &LHS_r = LHS.getComplexFloatReal();
5377 APFloat &LHS_i = LHS.getComplexFloatImag();
5378 APFloat &RHS_r = RHS.getComplexFloatReal();
5379 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005380
Daniel Dunbar3f279872009-01-29 01:32:56 +00005381 APFloat Tmp = LHS_r;
5382 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5383 Result.getComplexFloatReal() = Tmp;
5384 Tmp = LHS_i;
5385 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5386 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5387
5388 Tmp = LHS_r;
5389 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5390 Result.getComplexFloatImag() = Tmp;
5391 Tmp = LHS_i;
5392 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5393 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5394 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005395 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005396 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005397 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5398 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005399 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005400 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5401 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5402 }
5403 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005404 case BO_Div:
5405 if (Result.isComplexFloat()) {
5406 ComplexValue LHS = Result;
5407 APFloat &LHS_r = LHS.getComplexFloatReal();
5408 APFloat &LHS_i = LHS.getComplexFloatImag();
5409 APFloat &RHS_r = RHS.getComplexFloatReal();
5410 APFloat &RHS_i = RHS.getComplexFloatImag();
5411 APFloat &Res_r = Result.getComplexFloatReal();
5412 APFloat &Res_i = Result.getComplexFloatImag();
5413
5414 APFloat Den = RHS_r;
5415 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5416 APFloat Tmp = RHS_i;
5417 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5418 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5419
5420 Res_r = LHS_r;
5421 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5422 Tmp = LHS_i;
5423 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5424 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5425 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5426
5427 Res_i = LHS_i;
5428 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5429 Tmp = LHS_r;
5430 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5431 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5432 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5433 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005434 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5435 return Error(E, diag::note_expr_divide_by_zero);
5436
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005437 ComplexValue LHS = Result;
5438 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5439 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5440 Result.getComplexIntReal() =
5441 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5442 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5443 Result.getComplexIntImag() =
5444 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5445 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5446 }
5447 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005448 }
5449
John McCallf4cf1a12010-05-07 17:22:02 +00005450 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005451}
5452
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005453bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5454 // Get the operand value into 'Result'.
5455 if (!Visit(E->getSubExpr()))
5456 return false;
5457
5458 switch (E->getOpcode()) {
5459 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005460 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005461 case UO_Extension:
5462 return true;
5463 case UO_Plus:
5464 // The result is always just the subexpr.
5465 return true;
5466 case UO_Minus:
5467 if (Result.isComplexFloat()) {
5468 Result.getComplexFloatReal().changeSign();
5469 Result.getComplexFloatImag().changeSign();
5470 }
5471 else {
5472 Result.getComplexIntReal() = -Result.getComplexIntReal();
5473 Result.getComplexIntImag() = -Result.getComplexIntImag();
5474 }
5475 return true;
5476 case UO_Not:
5477 if (Result.isComplexFloat())
5478 Result.getComplexFloatImag().changeSign();
5479 else
5480 Result.getComplexIntImag() = -Result.getComplexIntImag();
5481 return true;
5482 }
5483}
5484
Eli Friedman7ead5c72012-01-10 04:58:17 +00005485bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5486 if (E->getNumInits() == 2) {
5487 if (E->getType()->isComplexType()) {
5488 Result.makeComplexFloat();
5489 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5490 return false;
5491 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5492 return false;
5493 } else {
5494 Result.makeComplexInt();
5495 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5496 return false;
5497 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5498 return false;
5499 }
5500 return true;
5501 }
5502 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5503}
5504
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005505//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005506// Void expression evaluation, primarily for a cast to void on the LHS of a
5507// comma operator
5508//===----------------------------------------------------------------------===//
5509
5510namespace {
5511class VoidExprEvaluator
5512 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5513public:
5514 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5515
5516 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005517
5518 bool VisitCastExpr(const CastExpr *E) {
5519 switch (E->getCastKind()) {
5520 default:
5521 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5522 case CK_ToVoid:
5523 VisitIgnoredValue(E->getSubExpr());
5524 return true;
5525 }
5526 }
5527};
5528} // end anonymous namespace
5529
5530static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5531 assert(E->isRValue() && E->getType()->isVoidType());
5532 return VoidExprEvaluator(Info).Visit(E);
5533}
5534
5535//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005536// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005537//===----------------------------------------------------------------------===//
5538
Richard Smith47a1eed2011-10-29 20:57:55 +00005539static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005540 // In C, function designators are not lvalues, but we evaluate them as if they
5541 // are.
5542 if (E->isGLValue() || E->getType()->isFunctionType()) {
5543 LValue LV;
5544 if (!EvaluateLValue(E, LV, Info))
5545 return false;
5546 LV.moveInto(Result);
5547 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005548 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005549 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005550 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005551 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005552 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005553 } else if (E->getType()->hasPointerRepresentation()) {
5554 LValue LV;
5555 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005556 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005557 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005558 } else if (E->getType()->isRealFloatingType()) {
5559 llvm::APFloat F(0.0);
5560 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005561 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005562 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005563 } else if (E->getType()->isAnyComplexType()) {
5564 ComplexValue C;
5565 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005566 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005567 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005568 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005569 MemberPtr P;
5570 if (!EvaluateMemberPointer(E, P, Info))
5571 return false;
5572 P.moveInto(Result);
5573 return true;
Richard Smith51201882011-12-30 21:15:51 +00005574 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005575 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005576 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005577 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005578 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005579 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005580 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005581 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005582 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005583 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5584 return false;
5585 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005586 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005587 if (Info.getLangOpts().CPlusPlus0x)
5588 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5589 << E->getType();
5590 else
5591 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005592 if (!EvaluateVoid(E, Info))
5593 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005594 } else if (Info.getLangOpts().CPlusPlus0x) {
5595 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5596 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005597 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005598 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005599 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005600 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005601
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005602 return true;
5603}
5604
Richard Smith69c2c502011-11-04 05:33:44 +00005605/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5606/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5607/// since later initializers for an object can indirectly refer to subobjects
5608/// which were initialized earlier.
5609static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005610 const LValue &This, const Expr *E,
5611 CheckConstantExpressionKind CCEK) {
Richard Smith51201882011-12-30 21:15:51 +00005612 if (!CheckLiteralType(Info, E))
5613 return false;
5614
5615 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005616 // Evaluate arrays and record types in-place, so that later initializers can
5617 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005618 if (E->getType()->isArrayType())
5619 return EvaluateArray(E, This, Result, Info);
5620 else if (E->getType()->isRecordType())
5621 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005622 }
5623
5624 // For any other type, in-place evaluation is unimportant.
5625 CCValue CoreConstResult;
5626 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005627 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005628}
5629
Richard Smithf48fdb02011-12-09 22:58:01 +00005630/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5631/// lvalue-to-rvalue cast if it is an lvalue.
5632static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005633 if (!CheckLiteralType(Info, E))
5634 return false;
5635
Richard Smithf48fdb02011-12-09 22:58:01 +00005636 CCValue Value;
5637 if (!::Evaluate(Value, Info, E))
5638 return false;
5639
5640 if (E->isGLValue()) {
5641 LValue LV;
5642 LV.setFrom(Value);
5643 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5644 return false;
5645 }
5646
5647 // Check this core constant expression is a constant expression, and if so,
5648 // convert it to one.
5649 return CheckConstantExpression(Info, E, Value, Result);
5650}
Richard Smithc49bd112011-10-28 17:51:58 +00005651
Richard Smith51f47082011-10-29 00:50:52 +00005652/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005653/// any crazy technique (that has nothing to do with language standards) that
5654/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005655/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5656/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005657bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005658 // Fast-path evaluations of integer literals, since we sometimes see files
5659 // containing vast quantities of these.
5660 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5661 Result.Val = APValue(APSInt(L->getValue(),
5662 L->getType()->isUnsignedIntegerType()));
5663 return true;
5664 }
5665
Richard Smith2d6a5672012-01-14 04:30:29 +00005666 // FIXME: Evaluating values of large array and record types can cause
5667 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005668 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5669 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005670 return false;
5671
Richard Smithf48fdb02011-12-09 22:58:01 +00005672 EvalInfo Info(Ctx, Result);
5673 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005674}
5675
Jay Foad4ba2a172011-01-12 09:06:06 +00005676bool Expr::EvaluateAsBooleanCondition(bool &Result,
5677 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005678 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005679 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00005680 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5681 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005682 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005683}
5684
Richard Smith80d4b552011-12-28 19:48:30 +00005685bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5686 SideEffectsKind AllowSideEffects) const {
5687 if (!getType()->isIntegralOrEnumerationType())
5688 return false;
5689
Richard Smithc49bd112011-10-28 17:51:58 +00005690 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00005691 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5692 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00005693 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005694
Richard Smithc49bd112011-10-28 17:51:58 +00005695 Result = ExprResult.Val.getInt();
5696 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005697}
5698
Jay Foad4ba2a172011-01-12 09:06:06 +00005699bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005700 EvalInfo Info(Ctx, Result);
5701
John McCallefdb83e2010-05-07 21:00:08 +00005702 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005703 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005704 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5705 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005706}
5707
Richard Smith099e7f62011-12-19 06:19:21 +00005708bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5709 const VarDecl *VD,
5710 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00005711 // FIXME: Evaluating initializers for large array and record types can cause
5712 // performance problems. Only do so in C++11 for now.
5713 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5714 !Ctx.getLangOptions().CPlusPlus0x)
5715 return false;
5716
Richard Smith099e7f62011-12-19 06:19:21 +00005717 Expr::EvalStatus EStatus;
5718 EStatus.Diag = &Notes;
5719
5720 EvalInfo InitInfo(Ctx, EStatus);
5721 InitInfo.setEvaluatingDecl(VD, Value);
5722
Richard Smith51201882011-12-30 21:15:51 +00005723 if (!CheckLiteralType(InitInfo, this))
5724 return false;
5725
Richard Smith099e7f62011-12-19 06:19:21 +00005726 LValue LVal;
5727 LVal.set(VD);
5728
Richard Smith51201882011-12-30 21:15:51 +00005729 // C++11 [basic.start.init]p2:
5730 // Variables with static storage duration or thread storage duration shall be
5731 // zero-initialized before any other initialization takes place.
5732 // This behavior is not present in C.
5733 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5734 !VD->getType()->isReferenceType()) {
5735 ImplicitValueInitExpr VIE(VD->getType());
5736 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5737 return false;
5738 }
5739
Richard Smith099e7f62011-12-19 06:19:21 +00005740 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5741 !EStatus.HasSideEffects;
5742}
5743
Richard Smith51f47082011-10-29 00:50:52 +00005744/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5745/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005746bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005747 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005748 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005749}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005750
Jay Foad4ba2a172011-01-12 09:06:06 +00005751bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005752 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005753}
5754
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005755APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005756 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005757 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005758 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005759 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005760 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005761
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005762 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005763}
John McCalld905f5a2010-05-07 05:32:02 +00005764
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005765 bool Expr::EvalResult::isGlobalLValue() const {
5766 assert(Val.isLValue());
5767 return IsGlobalLValue(Val.getLValueBase());
5768 }
5769
5770
John McCalld905f5a2010-05-07 05:32:02 +00005771/// isIntegerConstantExpr - this recursive routine will test if an expression is
5772/// an integer constant expression.
5773
5774/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5775/// comma, etc
5776///
5777/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5778/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5779/// cast+dereference.
5780
5781// CheckICE - This function does the fundamental ICE checking: the returned
5782// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5783// Note that to reduce code duplication, this helper does no evaluation
5784// itself; the caller checks whether the expression is evaluatable, and
5785// in the rare cases where CheckICE actually cares about the evaluated
5786// value, it calls into Evalute.
5787//
5788// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005789// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005790// 1: This expression is not an ICE, but if it isn't evaluated, it's
5791// a legal subexpression for an ICE. This return value is used to handle
5792// the comma operator in C99 mode.
5793// 2: This expression is not an ICE, and is not a legal subexpression for one.
5794
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005795namespace {
5796
John McCalld905f5a2010-05-07 05:32:02 +00005797struct ICEDiag {
5798 unsigned Val;
5799 SourceLocation Loc;
5800
5801 public:
5802 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5803 ICEDiag() : Val(0) {}
5804};
5805
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005806}
5807
5808static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00005809
5810static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5811 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005812 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005813 !EVResult.Val.isInt()) {
5814 return ICEDiag(2, E->getLocStart());
5815 }
5816 return NoDiag();
5817}
5818
5819static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5820 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005821 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00005822 return ICEDiag(2, E->getLocStart());
5823 }
5824
5825 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00005826#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00005827#define STMT(Node, Base) case Expr::Node##Class:
5828#define EXPR(Node, Base)
5829#include "clang/AST/StmtNodes.inc"
5830 case Expr::PredefinedExprClass:
5831 case Expr::FloatingLiteralClass:
5832 case Expr::ImaginaryLiteralClass:
5833 case Expr::StringLiteralClass:
5834 case Expr::ArraySubscriptExprClass:
5835 case Expr::MemberExprClass:
5836 case Expr::CompoundAssignOperatorClass:
5837 case Expr::CompoundLiteralExprClass:
5838 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005839 case Expr::DesignatedInitExprClass:
5840 case Expr::ImplicitValueInitExprClass:
5841 case Expr::ParenListExprClass:
5842 case Expr::VAArgExprClass:
5843 case Expr::AddrLabelExprClass:
5844 case Expr::StmtExprClass:
5845 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00005846 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005847 case Expr::CXXDynamicCastExprClass:
5848 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00005849 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005850 case Expr::CXXNullPtrLiteralExprClass:
5851 case Expr::CXXThisExprClass:
5852 case Expr::CXXThrowExprClass:
5853 case Expr::CXXNewExprClass:
5854 case Expr::CXXDeleteExprClass:
5855 case Expr::CXXPseudoDestructorExprClass:
5856 case Expr::UnresolvedLookupExprClass:
5857 case Expr::DependentScopeDeclRefExprClass:
5858 case Expr::CXXConstructExprClass:
5859 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00005860 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00005861 case Expr::CXXTemporaryObjectExprClass:
5862 case Expr::CXXUnresolvedConstructExprClass:
5863 case Expr::CXXDependentScopeMemberExprClass:
5864 case Expr::UnresolvedMemberExprClass:
5865 case Expr::ObjCStringLiteralClass:
5866 case Expr::ObjCEncodeExprClass:
5867 case Expr::ObjCMessageExprClass:
5868 case Expr::ObjCSelectorExprClass:
5869 case Expr::ObjCProtocolExprClass:
5870 case Expr::ObjCIvarRefExprClass:
5871 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005872 case Expr::ObjCIsaExprClass:
5873 case Expr::ShuffleVectorExprClass:
5874 case Expr::BlockExprClass:
5875 case Expr::BlockDeclRefExprClass:
5876 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00005877 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00005878 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00005879 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005880 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005881 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00005882 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00005883 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00005884 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005885 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005886 return ICEDiag(2, E->getLocStart());
5887
Douglas Gregoree8aff02011-01-04 17:33:58 +00005888 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005889 case Expr::GNUNullExprClass:
5890 // GCC considers the GNU __null value to be an integral constant expression.
5891 return NoDiag();
5892
John McCall91a57552011-07-15 05:09:51 +00005893 case Expr::SubstNonTypeTemplateParmExprClass:
5894 return
5895 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5896
John McCalld905f5a2010-05-07 05:32:02 +00005897 case Expr::ParenExprClass:
5898 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00005899 case Expr::GenericSelectionExprClass:
5900 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005901 case Expr::IntegerLiteralClass:
5902 case Expr::CharacterLiteralClass:
5903 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00005904 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005905 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00005906 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00005907 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00005908 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00005909 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005910 return NoDiag();
5911 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00005912 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00005913 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5914 // constant expressions, but they can never be ICEs because an ICE cannot
5915 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00005916 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00005917 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00005918 return CheckEvalInICE(E, Ctx);
5919 return ICEDiag(2, E->getLocStart());
5920 }
5921 case Expr::DeclRefExprClass:
5922 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5923 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00005924 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00005925 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5926
5927 // Parameter variables are never constants. Without this check,
5928 // getAnyInitializer() can find a default argument, which leads
5929 // to chaos.
5930 if (isa<ParmVarDecl>(D))
5931 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5932
5933 // C++ 7.1.5.1p2
5934 // A variable of non-volatile const-qualified integral or enumeration
5935 // type initialized by an ICE can be used in ICEs.
5936 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00005937 if (!Dcl->getType()->isIntegralOrEnumerationType())
5938 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5939
Richard Smith099e7f62011-12-19 06:19:21 +00005940 const VarDecl *VD;
5941 // Look for a declaration of this variable that has an initializer, and
5942 // check whether it is an ICE.
5943 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5944 return NoDiag();
5945 else
5946 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00005947 }
5948 }
5949 return ICEDiag(2, E->getLocStart());
5950 case Expr::UnaryOperatorClass: {
5951 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5952 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005953 case UO_PostInc:
5954 case UO_PostDec:
5955 case UO_PreInc:
5956 case UO_PreDec:
5957 case UO_AddrOf:
5958 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00005959 // C99 6.6/3 allows increment and decrement within unevaluated
5960 // subexpressions of constant expressions, but they can never be ICEs
5961 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005962 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00005963 case UO_Extension:
5964 case UO_LNot:
5965 case UO_Plus:
5966 case UO_Minus:
5967 case UO_Not:
5968 case UO_Real:
5969 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00005970 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005971 }
5972
5973 // OffsetOf falls through here.
5974 }
5975 case Expr::OffsetOfExprClass: {
5976 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00005977 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00005978 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00005979 // compliance: we should warn earlier for offsetof expressions with
5980 // array subscripts that aren't ICEs, and if the array subscripts
5981 // are ICEs, the value of the offsetof must be an integer constant.
5982 return CheckEvalInICE(E, Ctx);
5983 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005984 case Expr::UnaryExprOrTypeTraitExprClass: {
5985 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5986 if ((Exp->getKind() == UETT_SizeOf) &&
5987 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00005988 return ICEDiag(2, E->getLocStart());
5989 return NoDiag();
5990 }
5991 case Expr::BinaryOperatorClass: {
5992 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5993 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005994 case BO_PtrMemD:
5995 case BO_PtrMemI:
5996 case BO_Assign:
5997 case BO_MulAssign:
5998 case BO_DivAssign:
5999 case BO_RemAssign:
6000 case BO_AddAssign:
6001 case BO_SubAssign:
6002 case BO_ShlAssign:
6003 case BO_ShrAssign:
6004 case BO_AndAssign:
6005 case BO_XorAssign:
6006 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006007 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6008 // constant expressions, but they can never be ICEs because an ICE cannot
6009 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006010 return ICEDiag(2, E->getLocStart());
6011
John McCall2de56d12010-08-25 11:45:40 +00006012 case BO_Mul:
6013 case BO_Div:
6014 case BO_Rem:
6015 case BO_Add:
6016 case BO_Sub:
6017 case BO_Shl:
6018 case BO_Shr:
6019 case BO_LT:
6020 case BO_GT:
6021 case BO_LE:
6022 case BO_GE:
6023 case BO_EQ:
6024 case BO_NE:
6025 case BO_And:
6026 case BO_Xor:
6027 case BO_Or:
6028 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006029 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6030 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006031 if (Exp->getOpcode() == BO_Div ||
6032 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006033 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006034 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006035 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006036 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006037 if (REval == 0)
6038 return ICEDiag(1, E->getLocStart());
6039 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006040 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006041 if (LEval.isMinSignedValue())
6042 return ICEDiag(1, E->getLocStart());
6043 }
6044 }
6045 }
John McCall2de56d12010-08-25 11:45:40 +00006046 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006047 if (Ctx.getLangOptions().C99) {
6048 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6049 // if it isn't evaluated.
6050 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6051 return ICEDiag(1, E->getLocStart());
6052 } else {
6053 // In both C89 and C++, commas in ICEs are illegal.
6054 return ICEDiag(2, E->getLocStart());
6055 }
6056 }
6057 if (LHSResult.Val >= RHSResult.Val)
6058 return LHSResult;
6059 return RHSResult;
6060 }
John McCall2de56d12010-08-25 11:45:40 +00006061 case BO_LAnd:
6062 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006063 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6064 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6065 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6066 // Rare case where the RHS has a comma "side-effect"; we need
6067 // to actually check the condition to see whether the side
6068 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006069 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006070 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006071 return RHSResult;
6072 return NoDiag();
6073 }
6074
6075 if (LHSResult.Val >= RHSResult.Val)
6076 return LHSResult;
6077 return RHSResult;
6078 }
6079 }
6080 }
6081 case Expr::ImplicitCastExprClass:
6082 case Expr::CStyleCastExprClass:
6083 case Expr::CXXFunctionalCastExprClass:
6084 case Expr::CXXStaticCastExprClass:
6085 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006086 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006087 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006088 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006089 if (isa<ExplicitCastExpr>(E)) {
6090 if (const FloatingLiteral *FL
6091 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6092 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6093 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6094 APSInt IgnoredVal(DestWidth, !DestSigned);
6095 bool Ignored;
6096 // If the value does not fit in the destination type, the behavior is
6097 // undefined, so we are not required to treat it as a constant
6098 // expression.
6099 if (FL->getValue().convertToInteger(IgnoredVal,
6100 llvm::APFloat::rmTowardZero,
6101 &Ignored) & APFloat::opInvalidOp)
6102 return ICEDiag(2, E->getLocStart());
6103 return NoDiag();
6104 }
6105 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006106 switch (cast<CastExpr>(E)->getCastKind()) {
6107 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006108 case CK_AtomicToNonAtomic:
6109 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006110 case CK_NoOp:
6111 case CK_IntegralToBoolean:
6112 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006113 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006114 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006115 return ICEDiag(2, E->getLocStart());
6116 }
John McCalld905f5a2010-05-07 05:32:02 +00006117 }
John McCall56ca35d2011-02-17 10:25:35 +00006118 case Expr::BinaryConditionalOperatorClass: {
6119 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6120 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6121 if (CommonResult.Val == 2) return CommonResult;
6122 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6123 if (FalseResult.Val == 2) return FalseResult;
6124 if (CommonResult.Val == 1) return CommonResult;
6125 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006126 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006127 return FalseResult;
6128 }
John McCalld905f5a2010-05-07 05:32:02 +00006129 case Expr::ConditionalOperatorClass: {
6130 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6131 // If the condition (ignoring parens) is a __builtin_constant_p call,
6132 // then only the true side is actually considered in an integer constant
6133 // expression, and it is fully evaluated. This is an important GNU
6134 // extension. See GCC PR38377 for discussion.
6135 if (const CallExpr *CallCE
6136 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006137 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6138 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006139 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006140 if (CondResult.Val == 2)
6141 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006142
Richard Smithf48fdb02011-12-09 22:58:01 +00006143 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6144 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006145
John McCalld905f5a2010-05-07 05:32:02 +00006146 if (TrueResult.Val == 2)
6147 return TrueResult;
6148 if (FalseResult.Val == 2)
6149 return FalseResult;
6150 if (CondResult.Val == 1)
6151 return CondResult;
6152 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6153 return NoDiag();
6154 // Rare case where the diagnostics depend on which side is evaluated
6155 // Note that if we get here, CondResult is 0, and at least one of
6156 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006157 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006158 return FalseResult;
6159 }
6160 return TrueResult;
6161 }
6162 case Expr::CXXDefaultArgExprClass:
6163 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6164 case Expr::ChooseExprClass: {
6165 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6166 }
6167 }
6168
David Blaikie30263482012-01-20 21:50:17 +00006169 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006170}
6171
Richard Smithf48fdb02011-12-09 22:58:01 +00006172/// Evaluate an expression as a C++11 integral constant expression.
6173static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6174 const Expr *E,
6175 llvm::APSInt *Value,
6176 SourceLocation *Loc) {
6177 if (!E->getType()->isIntegralOrEnumerationType()) {
6178 if (Loc) *Loc = E->getExprLoc();
6179 return false;
6180 }
6181
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006182 APValue Result;
6183 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006184 return false;
6185
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006186 assert(Result.isInt() && "pointer cast to int is not an ICE");
6187 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006188 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006189}
6190
Richard Smithdd1f29b2011-12-12 09:28:41 +00006191bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006192 if (Ctx.getLangOptions().CPlusPlus0x)
6193 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6194
John McCalld905f5a2010-05-07 05:32:02 +00006195 ICEDiag d = CheckICE(this, Ctx);
6196 if (d.Val != 0) {
6197 if (Loc) *Loc = d.Loc;
6198 return false;
6199 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006200 return true;
6201}
6202
6203bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6204 SourceLocation *Loc, bool isEvaluated) const {
6205 if (Ctx.getLangOptions().CPlusPlus0x)
6206 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6207
6208 if (!isIntegerConstantExpr(Ctx, Loc))
6209 return false;
6210 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006211 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006212 return true;
6213}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006214
6215bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6216 SourceLocation *Loc) const {
6217 // We support this checking in C++98 mode in order to diagnose compatibility
6218 // issues.
6219 assert(Ctx.getLangOptions().CPlusPlus);
6220
6221 Expr::EvalStatus Status;
6222 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6223 Status.Diag = &Diags;
6224 EvalInfo Info(Ctx, Status);
6225
6226 APValue Scratch;
6227 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6228
6229 if (!Diags.empty()) {
6230 IsConstExpr = false;
6231 if (Loc) *Loc = Diags[0].first;
6232 } else if (!IsConstExpr) {
6233 // FIXME: This shouldn't happen.
6234 if (Loc) *Loc = getExprLoc();
6235 }
6236
6237 return IsConstExpr;
6238}
Richard Smith745f5142012-01-27 01:14:48 +00006239
6240bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6241 llvm::SmallVectorImpl<
6242 PartialDiagnosticAt> &Diags) {
6243 // FIXME: It would be useful to check constexpr function templates, but at the
6244 // moment the constant expression evaluator cannot cope with the non-rigorous
6245 // ASTs which we build for dependent expressions.
6246 if (FD->isDependentContext())
6247 return true;
6248
6249 Expr::EvalStatus Status;
6250 Status.Diag = &Diags;
6251
6252 EvalInfo Info(FD->getASTContext(), Status);
6253 Info.CheckingPotentialConstantExpression = true;
6254
6255 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6256 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6257
6258 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6259 // is a temporary being used as the 'this' pointer.
6260 LValue This;
6261 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6262 This.set(&VIE, Info.CurrentCall);
6263
6264 APValue Scratch;
6265 ArrayRef<const Expr*> Args;
6266
6267 SourceLocation Loc = FD->getLocation();
6268
6269 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
6270 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6271 } else
6272 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6273 Args, FD->getBody(), Info, Scratch);
6274
6275 return Diags.empty();
6276}