blob: 50e96bdd4b554bd8c6f9283fdf9fbb10ff158c3b [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 }
351 };
352
Richard Smithbd552ef2011-10-31 05:52:43 +0000353 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000354 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000355
356 /// EvalStatus - Contains information about the evaluation.
357 Expr::EvalStatus &EvalStatus;
358
359 /// CurrentCall - The top of the constexpr call stack.
360 CallStackFrame *CurrentCall;
361
Richard Smithbd552ef2011-10-31 05:52:43 +0000362 /// CallStackDepth - The number of calls in the call stack right now.
363 unsigned CallStackDepth;
364
365 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
366 /// OpaqueValues - Values used as the common expression in a
367 /// BinaryConditionalOperator.
368 MapTy OpaqueValues;
369
370 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000371 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000372 CallStackFrame BottomFrame;
373
Richard Smith180f4792011-11-10 06:34:14 +0000374 /// EvaluatingDecl - This is the declaration whose initializer is being
375 /// evaluated, if any.
376 const VarDecl *EvaluatingDecl;
377
378 /// EvaluatingDeclValue - This is the value being constructed for the
379 /// declaration whose initializer is being evaluated, if any.
380 APValue *EvaluatingDeclValue;
381
Richard Smithc1c5f272011-12-13 06:39:58 +0000382 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
383 /// notes attached to it will also be stored, otherwise they will not be.
384 bool HasActiveDiagnostic;
385
Richard Smith745f5142012-01-27 01:14:48 +0000386 /// CheckingPotentialConstantExpression - Are we checking whether the
387 /// expression is a potential constant expression? If so, some diagnostics
388 /// are suppressed.
389 bool CheckingPotentialConstantExpression;
390
Richard Smithbd552ef2011-10-31 05:52:43 +0000391
392 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000393 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith08d6e032011-12-16 19:06:07 +0000394 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000395 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
396 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000397
Richard Smithbd552ef2011-10-31 05:52:43 +0000398 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
399 MapTy::const_iterator i = OpaqueValues.find(e);
400 if (i == OpaqueValues.end()) return 0;
401 return &i->second;
402 }
403
Richard Smith180f4792011-11-10 06:34:14 +0000404 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
405 EvaluatingDecl = VD;
406 EvaluatingDeclValue = &Value;
407 }
408
Richard Smithc18c4232011-11-21 19:36:32 +0000409 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
410
Richard Smithc1c5f272011-12-13 06:39:58 +0000411 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000412 // Don't perform any constexpr calls (other than the call we're checking)
413 // when checking a potential constant expression.
414 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
415 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +0000416 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
417 return true;
418 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
419 << getLangOpts().ConstexprCallDepth;
420 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000421 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000422
Richard Smithc1c5f272011-12-13 06:39:58 +0000423 private:
424 /// Add a diagnostic to the diagnostics list.
425 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
426 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
427 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
428 return EvalStatus.Diag->back().second;
429 }
430
Richard Smith08d6e032011-12-16 19:06:07 +0000431 /// Add notes containing a call stack to the current point of evaluation.
432 void addCallStack(unsigned Limit);
433
Richard Smithc1c5f272011-12-13 06:39:58 +0000434 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000435 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000436 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
437 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000438 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000439 // If we have a prior diagnostic, it will be noting that the expression
440 // isn't a constant expression. This diagnostic is more important.
441 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000442 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000443 unsigned CallStackNotes = CallStackDepth - 1;
444 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
445 if (Limit)
446 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000447 if (CheckingPotentialConstantExpression)
448 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000449
Richard Smithc1c5f272011-12-13 06:39:58 +0000450 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000451 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000452 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
453 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000454 if (!CheckingPotentialConstantExpression)
455 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000456 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000457 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000458 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000459 return OptionalDiagnostic();
460 }
461
462 /// Diagnose that the evaluation does not produce a C++11 core constant
463 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000464 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
465 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000466 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000467 // Don't override a previous diagnostic.
468 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
469 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000470 return Diag(Loc, DiagId, ExtraNotes);
471 }
472
473 /// Add a note to a prior diagnostic.
474 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
475 if (!HasActiveDiagnostic)
476 return OptionalDiagnostic();
477 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000478 }
Richard Smith099e7f62011-12-19 06:19:21 +0000479
480 /// Add a stack of notes to a prior diagnostic.
481 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
482 if (HasActiveDiagnostic) {
483 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
484 Diags.begin(), Diags.end());
485 }
486 }
Richard Smith745f5142012-01-27 01:14:48 +0000487
488 /// Should we continue evaluation as much as possible after encountering a
489 /// construct which can't be folded?
490 bool keepEvaluatingAfterFailure() {
491 return CheckingPotentialConstantExpression && EvalStatus.Diag->empty();
492 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000493 };
Richard Smith08d6e032011-12-16 19:06:07 +0000494}
Richard Smithbd552ef2011-10-31 05:52:43 +0000495
Richard Smithb4e85ed2012-01-06 16:39:00 +0000496bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
497 CheckSubobjectKind CSK) {
498 if (Invalid)
499 return false;
500 if (isOnePastTheEnd()) {
501 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
502 << CSK;
503 setInvalid();
504 return false;
505 }
506 return true;
507}
508
509void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
510 const Expr *E, uint64_t N) {
511 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
512 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
513 << static_cast<int>(N) << /*array*/ 0
514 << static_cast<unsigned>(MostDerivedArraySize);
515 else
516 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
517 << static_cast<int>(N) << /*non-array*/ 1;
518 setInvalid();
519}
520
Richard Smith08d6e032011-12-16 19:06:07 +0000521CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
522 const FunctionDecl *Callee, const LValue *This,
523 const CCValue *Arguments)
524 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
525 This(This), Arguments(Arguments) {
526 Info.CurrentCall = this;
527 ++Info.CallStackDepth;
528}
529
530CallStackFrame::~CallStackFrame() {
531 assert(Info.CurrentCall == this && "calls retired out of order");
532 --Info.CallStackDepth;
533 Info.CurrentCall = Caller;
534}
535
536/// Produce a string describing the given constexpr call.
537static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
538 unsigned ArgIndex = 0;
539 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
540 !isa<CXXConstructorDecl>(Frame->Callee);
541
542 if (!IsMemberCall)
543 Out << *Frame->Callee << '(';
544
545 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
546 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000547 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000548 Out << ", ";
549
550 const ParmVarDecl *Param = *I;
551 const CCValue &Arg = Frame->Arguments[ArgIndex];
552 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
553 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
554 else {
555 // Deliberately slice off the frame to form an APValue we can print.
556 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
557 Arg.getLValueDesignator().Entries,
Richard Smithb4e85ed2012-01-06 16:39:00 +0000558 Arg.getLValueDesignator().IsOnePastTheEnd);
Richard Smith08d6e032011-12-16 19:06:07 +0000559 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
560 }
561
562 if (ArgIndex == 0 && IsMemberCall)
563 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000564 }
565
Richard Smith08d6e032011-12-16 19:06:07 +0000566 Out << ')';
567}
568
569void EvalInfo::addCallStack(unsigned Limit) {
570 // Determine which calls to skip, if any.
571 unsigned ActiveCalls = CallStackDepth - 1;
572 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
573 if (Limit && Limit < ActiveCalls) {
574 SkipStart = Limit / 2 + Limit % 2;
575 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000576 }
577
Richard Smith08d6e032011-12-16 19:06:07 +0000578 // Walk the call stack and add the diagnostics.
579 unsigned CallIdx = 0;
580 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
581 Frame = Frame->Caller, ++CallIdx) {
582 // Skip this call?
583 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
584 if (CallIdx == SkipStart) {
585 // Note that we're skipping calls.
586 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
587 << unsigned(ActiveCalls - Limit);
588 }
589 continue;
590 }
591
592 llvm::SmallVector<char, 128> Buffer;
593 llvm::raw_svector_ostream Out(Buffer);
594 describeCall(Frame, Out);
595 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
596 }
597}
598
599namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000600 struct ComplexValue {
601 private:
602 bool IsInt;
603
604 public:
605 APSInt IntReal, IntImag;
606 APFloat FloatReal, FloatImag;
607
608 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
609
610 void makeComplexFloat() { IsInt = false; }
611 bool isComplexFloat() const { return !IsInt; }
612 APFloat &getComplexFloatReal() { return FloatReal; }
613 APFloat &getComplexFloatImag() { return FloatImag; }
614
615 void makeComplexInt() { IsInt = true; }
616 bool isComplexInt() const { return IsInt; }
617 APSInt &getComplexIntReal() { return IntReal; }
618 APSInt &getComplexIntImag() { return IntImag; }
619
Richard Smith47a1eed2011-10-29 20:57:55 +0000620 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000621 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000622 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000623 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000624 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000625 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000626 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000627 assert(v.isComplexFloat() || v.isComplexInt());
628 if (v.isComplexFloat()) {
629 makeComplexFloat();
630 FloatReal = v.getComplexFloatReal();
631 FloatImag = v.getComplexFloatImag();
632 } else {
633 makeComplexInt();
634 IntReal = v.getComplexIntReal();
635 IntImag = v.getComplexIntImag();
636 }
637 }
John McCallf4cf1a12010-05-07 17:22:02 +0000638 };
John McCallefdb83e2010-05-07 21:00:08 +0000639
640 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000641 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000642 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000643 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000644 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000645
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000646 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000647 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000648 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000649 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000650 SubobjectDesignator &getLValueDesignator() { return Designator; }
651 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000652
Richard Smith47a1eed2011-10-29 20:57:55 +0000653 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000654 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000655 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000656 void setFrom(const CCValue &V) {
657 assert(V.isLValue());
658 Base = V.getLValueBase();
659 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000660 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000661 Designator = V.getLValueDesignator();
662 }
663
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000664 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
665 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000666 Offset = CharUnits::Zero();
667 Frame = F;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000668 Designator = SubobjectDesignator(getType(B));
669 }
670
671 // Check that this LValue is not based on a null pointer. If it is, produce
672 // a diagnostic and mark the designator as invalid.
673 bool checkNullPointer(EvalInfo &Info, const Expr *E,
674 CheckSubobjectKind CSK) {
675 if (Designator.Invalid)
676 return false;
677 if (!Base) {
678 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
679 << CSK;
680 Designator.setInvalid();
681 return false;
682 }
683 return true;
684 }
685
686 // Check this LValue refers to an object. If not, set the designator to be
687 // invalid and emit a diagnostic.
688 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
689 return checkNullPointer(Info, E, CSK) &&
690 Designator.checkSubobject(Info, E, CSK);
691 }
692
693 void addDecl(EvalInfo &Info, const Expr *E,
694 const Decl *D, bool Virtual = false) {
695 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
696 Designator.addDeclUnchecked(D, Virtual);
697 }
698 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
699 checkSubobject(Info, E, CSK_ArrayToPointer);
700 Designator.addArrayUnchecked(CAT);
701 }
702 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
703 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
704 return;
705 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000706 }
John McCallefdb83e2010-05-07 21:00:08 +0000707 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000708
709 struct MemberPtr {
710 MemberPtr() {}
711 explicit MemberPtr(const ValueDecl *Decl) :
712 DeclAndIsDerivedMember(Decl, false), Path() {}
713
714 /// The member or (direct or indirect) field referred to by this member
715 /// pointer, or 0 if this is a null member pointer.
716 const ValueDecl *getDecl() const {
717 return DeclAndIsDerivedMember.getPointer();
718 }
719 /// Is this actually a member of some type derived from the relevant class?
720 bool isDerivedMember() const {
721 return DeclAndIsDerivedMember.getInt();
722 }
723 /// Get the class which the declaration actually lives in.
724 const CXXRecordDecl *getContainingRecord() const {
725 return cast<CXXRecordDecl>(
726 DeclAndIsDerivedMember.getPointer()->getDeclContext());
727 }
728
729 void moveInto(CCValue &V) const {
730 V = CCValue(getDecl(), isDerivedMember(), Path);
731 }
732 void setFrom(const CCValue &V) {
733 assert(V.isMemberPointer());
734 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
735 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
736 Path.clear();
737 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
738 Path.insert(Path.end(), P.begin(), P.end());
739 }
740
741 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
742 /// whether the member is a member of some class derived from the class type
743 /// of the member pointer.
744 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
745 /// Path - The path of base/derived classes from the member declaration's
746 /// class (exclusive) to the class type of the member pointer (inclusive).
747 SmallVector<const CXXRecordDecl*, 4> Path;
748
749 /// Perform a cast towards the class of the Decl (either up or down the
750 /// hierarchy).
751 bool castBack(const CXXRecordDecl *Class) {
752 assert(!Path.empty());
753 const CXXRecordDecl *Expected;
754 if (Path.size() >= 2)
755 Expected = Path[Path.size() - 2];
756 else
757 Expected = getContainingRecord();
758 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
759 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
760 // if B does not contain the original member and is not a base or
761 // derived class of the class containing the original member, the result
762 // of the cast is undefined.
763 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
764 // (D::*). We consider that to be a language defect.
765 return false;
766 }
767 Path.pop_back();
768 return true;
769 }
770 /// Perform a base-to-derived member pointer cast.
771 bool castToDerived(const CXXRecordDecl *Derived) {
772 if (!getDecl())
773 return true;
774 if (!isDerivedMember()) {
775 Path.push_back(Derived);
776 return true;
777 }
778 if (!castBack(Derived))
779 return false;
780 if (Path.empty())
781 DeclAndIsDerivedMember.setInt(false);
782 return true;
783 }
784 /// Perform a derived-to-base member pointer cast.
785 bool castToBase(const CXXRecordDecl *Base) {
786 if (!getDecl())
787 return true;
788 if (Path.empty())
789 DeclAndIsDerivedMember.setInt(true);
790 if (isDerivedMember()) {
791 Path.push_back(Base);
792 return true;
793 }
794 return castBack(Base);
795 }
796 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000797
798 /// Kinds of constant expression checking, for diagnostics.
799 enum CheckConstantExpressionKind {
800 CCEK_Constant, ///< A normal constant.
801 CCEK_ReturnValue, ///< A constexpr function return value.
802 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
803 };
John McCallf4cf1a12010-05-07 17:22:02 +0000804}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000805
Richard Smith47a1eed2011-10-29 20:57:55 +0000806static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000807static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000808 const LValue &This, const Expr *E,
809 CheckConstantExpressionKind CCEK
810 = CCEK_Constant);
John McCallefdb83e2010-05-07 21:00:08 +0000811static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
812static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000813static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
814 EvalInfo &Info);
815static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000816static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000817static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000818 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000819static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000820static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000821
822//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000823// Misc utilities
824//===----------------------------------------------------------------------===//
825
Richard Smith180f4792011-11-10 06:34:14 +0000826/// Should this call expression be treated as a string literal?
827static bool IsStringLiteralCall(const CallExpr *E) {
828 unsigned Builtin = E->isBuiltinCall();
829 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
830 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
831}
832
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000833static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000834 // C++11 [expr.const]p3 An address constant expression is a prvalue core
835 // constant expression of pointer type that evaluates to...
836
837 // ... a null pointer value, or a prvalue core constant expression of type
838 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000839 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000840
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000841 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
842 // ... the address of an object with static storage duration,
843 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
844 return VD->hasGlobalStorage();
845 // ... the address of a function,
846 return isa<FunctionDecl>(D);
847 }
848
849 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000850 switch (E->getStmtClass()) {
851 default:
852 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000853 case Expr::CompoundLiteralExprClass:
854 return cast<CompoundLiteralExpr>(E)->isFileScope();
855 // A string literal has static storage duration.
856 case Expr::StringLiteralClass:
857 case Expr::PredefinedExprClass:
858 case Expr::ObjCStringLiteralClass:
859 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000860 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000861 return true;
862 case Expr::CallExprClass:
863 return IsStringLiteralCall(cast<CallExpr>(E));
864 // For GCC compatibility, &&label has static storage duration.
865 case Expr::AddrLabelExprClass:
866 return true;
867 // A Block literal expression may be used as the initialization value for
868 // Block variables at global or local static scope.
869 case Expr::BlockExprClass:
870 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000871 case Expr::ImplicitValueInitExprClass:
872 // FIXME:
873 // We can never form an lvalue with an implicit value initialization as its
874 // base through expression evaluation, so these only appear in one case: the
875 // implicit variable declaration we invent when checking whether a constexpr
876 // constructor can produce a constant expression. We must assume that such
877 // an expression might be a global lvalue.
878 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000879 }
John McCall42c8f872010-05-10 23:27:23 +0000880}
881
Richard Smith9a17a682011-11-07 05:07:52 +0000882/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000883/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000884/// either LValue or CCValue. Return true if we can fold this expression,
885/// whether or not it's a constant expression.
Richard Smith9a17a682011-11-07 05:07:52 +0000886template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000887static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000888 const T &LVal, APValue &Value,
889 CheckConstantExpressionKind CCEK) {
890 APValue::LValueBase Base = LVal.getLValueBase();
891 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
892
893 if (!IsGlobalLValue(Base)) {
894 if (Info.getLangOpts().CPlusPlus0x) {
895 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
896 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
897 << E->isGLValue() << !Designator.Entries.empty()
898 << !!VD << CCEK << VD;
899 if (VD)
900 Info.Note(VD->getLocation(), diag::note_declared_at);
901 else
902 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
903 diag::note_constexpr_temporary_here);
904 } else {
Richard Smith7098cbd2011-12-21 05:04:46 +0000905 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000906 }
Richard Smith61e61622012-01-12 06:08:57 +0000907 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000908 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000909 }
Richard Smith9a17a682011-11-07 05:07:52 +0000910
Richard Smithb4e85ed2012-01-06 16:39:00 +0000911 bool IsReferenceType = E->isGLValue();
912
913 if (Designator.Invalid) {
Richard Smith61e61622012-01-12 06:08:57 +0000914 // This is not a core constant expression. An appropriate diagnostic will
915 // have already been produced.
Richard Smith9a17a682011-11-07 05:07:52 +0000916 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
917 APValue::NoLValuePath());
918 return true;
919 }
920
Richard Smithb4e85ed2012-01-06 16:39:00 +0000921 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
922 Designator.Entries, Designator.IsOnePastTheEnd);
923
924 // Allow address constant expressions to be past-the-end pointers. This is
925 // an extension: the standard requires them to point to an object.
926 if (!IsReferenceType)
927 return true;
928
929 // A reference constant expression must refer to an object.
930 if (!Base) {
931 // FIXME: diagnostic
932 Info.CCEDiag(E->getExprLoc());
Richard Smith61e61622012-01-12 06:08:57 +0000933 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000934 }
935
Richard Smithc1c5f272011-12-13 06:39:58 +0000936 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +0000937 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000938 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
939 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
940 << !Designator.Entries.empty() << !!VD << VD;
941 if (VD)
942 Info.Note(VD->getLocation(), diag::note_declared_at);
943 else
944 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
945 diag::note_constexpr_temporary_here);
Richard Smithc1c5f272011-12-13 06:39:58 +0000946 }
947
Richard Smith9a17a682011-11-07 05:07:52 +0000948 return true;
949}
950
Richard Smith51201882011-12-30 21:15:51 +0000951/// Check that this core constant expression is of literal type, and if not,
952/// produce an appropriate diagnostic.
953static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
954 if (!E->isRValue() || E->getType()->isLiteralType())
955 return true;
956
957 // Prvalue constant expressions must be of literal types.
958 if (Info.getLangOpts().CPlusPlus0x)
959 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
960 << E->getType();
961 else
962 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
963 return false;
964}
965
Richard Smith47a1eed2011-10-29 20:57:55 +0000966/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000967/// constant expression, and if it is, produce the corresponding constant value.
Richard Smith51201882011-12-30 21:15:51 +0000968/// If not, report an appropriate diagnostic. Does not check that the expression
969/// is of literal type.
Richard Smithf48fdb02011-12-09 22:58:01 +0000970static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000971 const CCValue &CCValue, APValue &Value,
972 CheckConstantExpressionKind CCEK
973 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +0000974 if (!CCValue.isLValue()) {
975 Value = CCValue;
976 return true;
977 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000978 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +0000979}
980
Richard Smith9e36b532011-10-31 05:11:32 +0000981const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000982 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +0000983}
984
985static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000986 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +0000987}
988
Richard Smith65ac5982011-11-01 21:06:14 +0000989static bool IsWeakLValue(const LValue &Value) {
990 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +0000991 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +0000992}
993
Richard Smithe24f5fc2011-11-17 22:56:20 +0000994static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +0000995 // A null base expression indicates a null pointer. These are always
996 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000997 if (!Value.getLValueBase()) {
998 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +0000999 return true;
1000 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001001
Richard Smithe24f5fc2011-11-17 22:56:20 +00001002 // We have a non-null base. These are generally known to be true, but if it's
1003 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001004 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001005 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001006 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001007}
1008
Richard Smith47a1eed2011-10-29 20:57:55 +00001009static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001010 switch (Val.getKind()) {
1011 case APValue::Uninitialized:
1012 return false;
1013 case APValue::Int:
1014 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001015 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001016 case APValue::Float:
1017 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001018 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001019 case APValue::ComplexInt:
1020 Result = Val.getComplexIntReal().getBoolValue() ||
1021 Val.getComplexIntImag().getBoolValue();
1022 return true;
1023 case APValue::ComplexFloat:
1024 Result = !Val.getComplexFloatReal().isZero() ||
1025 !Val.getComplexFloatImag().isZero();
1026 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001027 case APValue::LValue:
1028 return EvalPointerValueAsBool(Val, Result);
1029 case APValue::MemberPointer:
1030 Result = Val.getMemberPointerDecl();
1031 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001032 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001033 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001034 case APValue::Struct:
1035 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001036 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001037 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001038 }
1039
Richard Smithc49bd112011-10-28 17:51:58 +00001040 llvm_unreachable("unknown APValue kind");
1041}
1042
1043static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1044 EvalInfo &Info) {
1045 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001046 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001047 if (!Evaluate(Val, Info, E))
1048 return false;
1049 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001050}
1051
Richard Smithc1c5f272011-12-13 06:39:58 +00001052template<typename T>
1053static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1054 const T &SrcValue, QualType DestType) {
1055 llvm::SmallVector<char, 32> Buffer;
1056 SrcValue.toString(Buffer);
1057 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
1058 << StringRef(Buffer.data(), Buffer.size()) << DestType;
1059 return false;
1060}
1061
1062static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1063 QualType SrcType, const APFloat &Value,
1064 QualType DestType, APSInt &Result) {
1065 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001066 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001067 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Richard Smithc1c5f272011-12-13 06:39:58 +00001069 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001070 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001071 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1072 & APFloat::opInvalidOp)
1073 return HandleOverflow(Info, E, Value, DestType);
1074 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001075}
1076
Richard Smithc1c5f272011-12-13 06:39:58 +00001077static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1078 QualType SrcType, QualType DestType,
1079 APFloat &Result) {
1080 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001081 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001082 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1083 APFloat::rmNearestTiesToEven, &ignored)
1084 & APFloat::opOverflow)
1085 return HandleOverflow(Info, E, Value, DestType);
1086 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001087}
1088
Richard Smithf72fccf2012-01-30 22:27:01 +00001089static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1090 QualType DestType, QualType SrcType,
1091 APSInt &Value) {
1092 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001093 APSInt Result = Value;
1094 // Figure out if this is a truncate, extend or noop cast.
1095 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001096 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001097 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001098 return Result;
1099}
1100
Richard Smithc1c5f272011-12-13 06:39:58 +00001101static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1102 QualType SrcType, const APSInt &Value,
1103 QualType DestType, APFloat &Result) {
1104 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1105 if (Result.convertFromAPInt(Value, Value.isSigned(),
1106 APFloat::rmNearestTiesToEven)
1107 & APFloat::opOverflow)
1108 return HandleOverflow(Info, E, Value, DestType);
1109 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001110}
1111
Eli Friedmane6a24e82011-12-22 03:51:45 +00001112static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1113 llvm::APInt &Res) {
1114 CCValue SVal;
1115 if (!Evaluate(SVal, Info, E))
1116 return false;
1117 if (SVal.isInt()) {
1118 Res = SVal.getInt();
1119 return true;
1120 }
1121 if (SVal.isFloat()) {
1122 Res = SVal.getFloat().bitcastToAPInt();
1123 return true;
1124 }
1125 if (SVal.isVector()) {
1126 QualType VecTy = E->getType();
1127 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1128 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1129 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1130 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1131 Res = llvm::APInt::getNullValue(VecSize);
1132 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1133 APValue &Elt = SVal.getVectorElt(i);
1134 llvm::APInt EltAsInt;
1135 if (Elt.isInt()) {
1136 EltAsInt = Elt.getInt();
1137 } else if (Elt.isFloat()) {
1138 EltAsInt = Elt.getFloat().bitcastToAPInt();
1139 } else {
1140 // Don't try to handle vectors of anything other than int or float
1141 // (not sure if it's possible to hit this case).
1142 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1143 return false;
1144 }
1145 unsigned BaseEltSize = EltAsInt.getBitWidth();
1146 if (BigEndian)
1147 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1148 else
1149 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1150 }
1151 return true;
1152 }
1153 // Give up if the input isn't an int, float, or vector. For example, we
1154 // reject "(v4i16)(intptr_t)&a".
1155 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1156 return false;
1157}
1158
Richard Smithb4e85ed2012-01-06 16:39:00 +00001159/// Cast an lvalue referring to a base subobject to a derived class, by
1160/// truncating the lvalue's path to the given length.
1161static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1162 const RecordDecl *TruncatedType,
1163 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001164 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001165
1166 // Check we actually point to a derived class object.
1167 if (TruncatedElements == D.Entries.size())
1168 return true;
1169 assert(TruncatedElements >= D.MostDerivedPathLength &&
1170 "not casting to a derived class");
1171 if (!Result.checkSubobject(Info, E, CSK_Derived))
1172 return false;
1173
1174 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001175 const RecordDecl *RD = TruncatedType;
1176 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001177 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1178 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001179 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001180 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001181 else
Richard Smith180f4792011-11-10 06:34:14 +00001182 Result.Offset -= Layout.getBaseClassOffset(Base);
1183 RD = Base;
1184 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001185 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001186 return true;
1187}
1188
Richard Smithb4e85ed2012-01-06 16:39:00 +00001189static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001190 const CXXRecordDecl *Derived,
1191 const CXXRecordDecl *Base,
1192 const ASTRecordLayout *RL = 0) {
1193 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1194 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001195 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001196}
1197
Richard Smithb4e85ed2012-01-06 16:39:00 +00001198static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001199 const CXXRecordDecl *DerivedDecl,
1200 const CXXBaseSpecifier *Base) {
1201 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1202
1203 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001204 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001205 return true;
1206 }
1207
Richard Smithb4e85ed2012-01-06 16:39:00 +00001208 SubobjectDesignator &D = Obj.Designator;
1209 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001210 return false;
1211
Richard Smithb4e85ed2012-01-06 16:39:00 +00001212 // Extract most-derived object and corresponding type.
1213 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1214 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1215 return false;
1216
1217 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001218 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1219 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001220 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001221 return true;
1222}
1223
1224/// Update LVal to refer to the given field, which must be a member of the type
1225/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001226static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001227 const FieldDecl *FD,
1228 const ASTRecordLayout *RL = 0) {
1229 if (!RL)
1230 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1231
1232 unsigned I = FD->getFieldIndex();
1233 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001234 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001235}
1236
Richard Smithd9b02e72012-01-25 22:15:11 +00001237/// Update LVal to refer to the given indirect field.
1238static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1239 LValue &LVal,
1240 const IndirectFieldDecl *IFD) {
1241 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1242 CE = IFD->chain_end(); C != CE; ++C)
1243 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1244}
1245
Richard Smith180f4792011-11-10 06:34:14 +00001246/// Get the size of the given type in char units.
1247static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1248 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1249 // extension.
1250 if (Type->isVoidType() || Type->isFunctionType()) {
1251 Size = CharUnits::One();
1252 return true;
1253 }
1254
1255 if (!Type->isConstantSizeType()) {
1256 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001257 // FIXME: Diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001258 return false;
1259 }
1260
1261 Size = Info.Ctx.getTypeSizeInChars(Type);
1262 return true;
1263}
1264
1265/// Update a pointer value to model pointer arithmetic.
1266/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001267/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001268/// \param LVal - The pointer value to be updated.
1269/// \param EltTy - The pointee type represented by LVal.
1270/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001271static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1272 LValue &LVal, QualType EltTy,
1273 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001274 CharUnits SizeOfPointee;
1275 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1276 return false;
1277
1278 // Compute the new offset in the appropriate width.
1279 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001280 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001281 return true;
1282}
1283
Richard Smith03f96112011-10-24 17:54:18 +00001284/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001285static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1286 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001287 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001288 // If this is a parameter to an active constexpr function call, perform
1289 // argument substitution.
1290 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001291 // Assume arguments of a potential constant expression are unknown
1292 // constant expressions.
1293 if (Info.CheckingPotentialConstantExpression)
1294 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001295 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001296 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001297 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001298 }
Richard Smith177dce72011-11-01 16:57:24 +00001299 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1300 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001301 }
Richard Smith03f96112011-10-24 17:54:18 +00001302
Richard Smith099e7f62011-12-19 06:19:21 +00001303 // Dig out the initializer, and use the declaration which it's attached to.
1304 const Expr *Init = VD->getAnyInitializer(VD);
1305 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001306 // If we're checking a potential constant expression, the variable could be
1307 // initialized later.
1308 if (!Info.CheckingPotentialConstantExpression)
1309 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001310 return false;
1311 }
1312
Richard Smith180f4792011-11-10 06:34:14 +00001313 // If we're currently evaluating the initializer of this declaration, use that
1314 // in-flight value.
1315 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001316 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1317 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001318 return !Result.isUninit();
1319 }
1320
Richard Smith65ac5982011-11-01 21:06:14 +00001321 // Never evaluate the initializer of a weak variable. We can't be sure that
1322 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001323 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001324 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001325 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001326 }
Richard Smith65ac5982011-11-01 21:06:14 +00001327
Richard Smith099e7f62011-12-19 06:19:21 +00001328 // Check that we can fold the initializer. In C++, we will have already done
1329 // this in the cases where it matters for conformance.
1330 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1331 if (!VD->evaluateValue(Notes)) {
1332 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1333 Notes.size() + 1) << VD;
1334 Info.Note(VD->getLocation(), diag::note_declared_at);
1335 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001336 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001337 } else if (!VD->checkInitIsICE()) {
1338 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1339 Notes.size() + 1) << VD;
1340 Info.Note(VD->getLocation(), diag::note_declared_at);
1341 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001342 }
Richard Smith03f96112011-10-24 17:54:18 +00001343
Richard Smithb4e85ed2012-01-06 16:39:00 +00001344 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001345 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001346}
1347
Richard Smithc49bd112011-10-28 17:51:58 +00001348static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001349 Qualifiers Quals = T.getQualifiers();
1350 return Quals.hasConst() && !Quals.hasVolatile();
1351}
1352
Richard Smith59efe262011-11-11 04:05:33 +00001353/// Get the base index of the given base class within an APValue representing
1354/// the given derived class.
1355static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1356 const CXXRecordDecl *Base) {
1357 Base = Base->getCanonicalDecl();
1358 unsigned Index = 0;
1359 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1360 E = Derived->bases_end(); I != E; ++I, ++Index) {
1361 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1362 return Index;
1363 }
1364
1365 llvm_unreachable("base class missing from derived class's bases list");
1366}
1367
Richard Smithcc5d4f62011-11-07 09:22:26 +00001368/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001369static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1370 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001371 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001372 if (Sub.Invalid)
1373 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001374 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001375 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001376 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001377 (unsigned)diag::note_constexpr_read_past_end :
1378 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001379 return false;
1380 }
Richard Smithf64699e2011-11-11 08:28:03 +00001381 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001382 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001383 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1384 // This object might be initialized later.
1385 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001386
1387 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1388 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001389 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001390 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001391 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001392 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001393 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001394 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001395 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001396 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001397 // Note, it should not be possible to form a pointer with a valid
1398 // designator which points more than one past the end of the array.
1399 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001400 (unsigned)diag::note_constexpr_read_past_end :
1401 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001402 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001403 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001404 if (O->getArrayInitializedElts() > Index)
1405 O = &O->getArrayInitializedElt(Index);
1406 else
1407 O = &O->getArrayFiller();
1408 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001409 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1410 // Next subobject is a class, struct or union field.
1411 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1412 if (RD->isUnion()) {
1413 const FieldDecl *UnionField = O->getUnionField();
1414 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001415 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001416 Info.Diag(E->getExprLoc(),
1417 diag::note_constexpr_read_inactive_union_member)
1418 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001419 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001420 }
Richard Smith180f4792011-11-10 06:34:14 +00001421 O = &O->getUnionValue();
1422 } else
1423 O = &O->getStructField(Field->getFieldIndex());
1424 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001425
1426 if (ObjType.isVolatileQualified()) {
1427 if (Info.getLangOpts().CPlusPlus) {
1428 // FIXME: Include a description of the path to the volatile subobject.
1429 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1430 << 2 << Field;
1431 Info.Note(Field->getLocation(), diag::note_declared_at);
1432 } else {
1433 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1434 }
1435 return false;
1436 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001437 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001438 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001439 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1440 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1441 O = &O->getStructBase(getBaseIndex(Derived, Base));
1442 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001443 }
Richard Smith180f4792011-11-10 06:34:14 +00001444
Richard Smithf48fdb02011-12-09 22:58:01 +00001445 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001446 if (!Info.CheckingPotentialConstantExpression)
1447 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001448 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001449 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001450 }
1451
Richard Smithb4e85ed2012-01-06 16:39:00 +00001452 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001453 return true;
1454}
1455
Richard Smith180f4792011-11-10 06:34:14 +00001456/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1457/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1458/// for looking up the glvalue referred to by an entity of reference type.
1459///
1460/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001461/// \param Conv - The expression for which we are performing the conversion.
1462/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001463/// \param Type - The type we expect this conversion to produce.
1464/// \param LVal - The glvalue on which we are attempting to perform this action.
1465/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001466static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1467 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001468 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001469 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1470 if (!Info.getLangOpts().CPlusPlus)
1471 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1472
Richard Smithb4e85ed2012-01-06 16:39:00 +00001473 if (LVal.Designator.Invalid)
1474 // A diagnostic will have already been produced.
1475 return false;
1476
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001477 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001478 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001479 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001480
Richard Smithf48fdb02011-12-09 22:58:01 +00001481 if (!LVal.Base) {
1482 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001483 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1484 return false;
1485 }
1486
1487 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1488 // is not a constant expression (even if the object is non-volatile). We also
1489 // apply this rule to C++98, in order to conform to the expected 'volatile'
1490 // semantics.
1491 if (Type.isVolatileQualified()) {
1492 if (Info.getLangOpts().CPlusPlus)
1493 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1494 else
1495 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001496 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001497 }
Richard Smithc49bd112011-10-28 17:51:58 +00001498
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001499 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001500 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1501 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001502 // expressions are constant expressions too. Inside constexpr functions,
1503 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001504 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001505 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001506 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001507 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001508 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001509 }
1510
Richard Smith7098cbd2011-12-21 05:04:46 +00001511 // DR1313: If the object is volatile-qualified but the glvalue was not,
1512 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001513 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001514 if (VT.isVolatileQualified()) {
1515 if (Info.getLangOpts().CPlusPlus) {
1516 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1517 Info.Note(VD->getLocation(), diag::note_declared_at);
1518 } else {
1519 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001520 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001521 return false;
1522 }
1523
1524 if (!isa<ParmVarDecl>(VD)) {
1525 if (VD->isConstexpr()) {
1526 // OK, we can read this variable.
1527 } else if (VT->isIntegralOrEnumerationType()) {
1528 if (!VT.isConstQualified()) {
1529 if (Info.getLangOpts().CPlusPlus) {
1530 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1531 Info.Note(VD->getLocation(), diag::note_declared_at);
1532 } else {
1533 Info.Diag(Loc);
1534 }
1535 return false;
1536 }
1537 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1538 // We support folding of const floating-point types, in order to make
1539 // static const data members of such types (supported as an extension)
1540 // more useful.
1541 if (Info.getLangOpts().CPlusPlus0x) {
1542 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1543 Info.Note(VD->getLocation(), diag::note_declared_at);
1544 } else {
1545 Info.CCEDiag(Loc);
1546 }
1547 } else {
1548 // FIXME: Allow folding of values of any literal type in all languages.
1549 if (Info.getLangOpts().CPlusPlus0x) {
1550 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1551 Info.Note(VD->getLocation(), diag::note_declared_at);
1552 } else {
1553 Info.Diag(Loc);
1554 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001555 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001556 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001557 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001558
Richard Smithf48fdb02011-12-09 22:58:01 +00001559 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001560 return false;
1561
Richard Smith47a1eed2011-10-29 20:57:55 +00001562 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001563 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001564
1565 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1566 // conversion. This happens when the declaration and the lvalue should be
1567 // considered synonymous, for instance when initializing an array of char
1568 // from a string literal. Continue as if the initializer lvalue was the
1569 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001570 assert(RVal.getLValueOffset().isZero() &&
1571 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001572 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001573 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001574 }
1575
Richard Smith7098cbd2011-12-21 05:04:46 +00001576 // Volatile temporary objects cannot be read in constant expressions.
1577 if (Base->getType().isVolatileQualified()) {
1578 if (Info.getLangOpts().CPlusPlus) {
1579 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1580 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1581 } else {
1582 Info.Diag(Loc);
1583 }
1584 return false;
1585 }
1586
Richard Smith0a3bdb62011-11-04 02:25:55 +00001587 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1588 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1589 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001590 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001591 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001592 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001593 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001594
1595 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001596 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001597 const ConstantArrayType *CAT =
1598 Info.Ctx.getAsConstantArrayType(S->getType());
1599 if (Index >= CAT->getSize().getZExtValue()) {
1600 // Note, it should not be possible to form a pointer which points more
1601 // than one past the end of the array without producing a prior const expr
1602 // diagnostic.
1603 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001604 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001605 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001606 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1607 Type->isUnsignedIntegerType());
1608 if (Index < S->getLength())
1609 Value = S->getCodeUnit(Index);
1610 RVal = CCValue(Value);
1611 return true;
1612 }
1613
Richard Smithcc5d4f62011-11-07 09:22:26 +00001614 if (Frame) {
1615 // If this is a temporary expression with a nontrivial initializer, grab the
1616 // value from the relevant stack frame.
1617 RVal = Frame->Temporaries[Base];
1618 } else if (const CompoundLiteralExpr *CLE
1619 = dyn_cast<CompoundLiteralExpr>(Base)) {
1620 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1621 // initializer until now for such expressions. Such an expression can't be
1622 // an ICE in C, so this only matters for fold.
1623 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1624 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1625 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001626 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001627 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001628 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001629 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001630
Richard Smithf48fdb02011-12-09 22:58:01 +00001631 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1632 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001633}
1634
Richard Smith59efe262011-11-11 04:05:33 +00001635/// Build an lvalue for the object argument of a member function call.
1636static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1637 LValue &This) {
1638 if (Object->getType()->isPointerType())
1639 return EvaluatePointer(Object, This, Info);
1640
1641 if (Object->isGLValue())
1642 return EvaluateLValue(Object, This, Info);
1643
Richard Smithe24f5fc2011-11-17 22:56:20 +00001644 if (Object->getType()->isLiteralType())
1645 return EvaluateTemporary(Object, This, Info);
1646
1647 return false;
1648}
1649
1650/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1651/// lvalue referring to the result.
1652///
1653/// \param Info - Information about the ongoing evaluation.
1654/// \param BO - The member pointer access operation.
1655/// \param LV - Filled in with a reference to the resulting object.
1656/// \param IncludeMember - Specifies whether the member itself is included in
1657/// the resulting LValue subobject designator. This is not possible when
1658/// creating a bound member function.
1659/// \return The field or method declaration to which the member pointer refers,
1660/// or 0 if evaluation fails.
1661static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1662 const BinaryOperator *BO,
1663 LValue &LV,
1664 bool IncludeMember = true) {
1665 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1666
Richard Smith745f5142012-01-27 01:14:48 +00001667 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1668 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001669 return 0;
1670
1671 MemberPtr MemPtr;
1672 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1673 return 0;
1674
1675 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1676 // member value, the behavior is undefined.
1677 if (!MemPtr.getDecl())
1678 return 0;
1679
Richard Smith745f5142012-01-27 01:14:48 +00001680 if (!EvalObjOK)
1681 return 0;
1682
Richard Smithe24f5fc2011-11-17 22:56:20 +00001683 if (MemPtr.isDerivedMember()) {
1684 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001685 // The end of the derived-to-base path for the base object must match the
1686 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001687 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001688 LV.Designator.Entries.size())
1689 return 0;
1690 unsigned PathLengthToMember =
1691 LV.Designator.Entries.size() - MemPtr.Path.size();
1692 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1693 const CXXRecordDecl *LVDecl = getAsBaseClass(
1694 LV.Designator.Entries[PathLengthToMember + I]);
1695 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1696 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1697 return 0;
1698 }
1699
1700 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001701 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1702 PathLengthToMember))
1703 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001704 } else if (!MemPtr.Path.empty()) {
1705 // Extend the LValue path with the member pointer's path.
1706 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1707 MemPtr.Path.size() + IncludeMember);
1708
1709 // Walk down to the appropriate base class.
1710 QualType LVType = BO->getLHS()->getType();
1711 if (const PointerType *PT = LVType->getAs<PointerType>())
1712 LVType = PT->getPointeeType();
1713 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1714 assert(RD && "member pointer access on non-class-type expression");
1715 // The first class in the path is that of the lvalue.
1716 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1717 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001718 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001719 RD = Base;
1720 }
1721 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001722 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001723 }
1724
1725 // Add the member. Note that we cannot build bound member functions here.
1726 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001727 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1728 HandleLValueMember(Info, BO, LV, FD);
1729 else if (const IndirectFieldDecl *IFD =
1730 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1731 HandleLValueIndirectMember(Info, BO, LV, IFD);
1732 else
1733 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001734 }
1735
1736 return MemPtr.getDecl();
1737}
1738
1739/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1740/// the provided lvalue, which currently refers to the base object.
1741static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1742 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001743 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001744 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001745 return false;
1746
Richard Smithb4e85ed2012-01-06 16:39:00 +00001747 QualType TargetQT = E->getType();
1748 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1749 TargetQT = PT->getPointeeType();
1750
1751 // Check this cast lands within the final derived-to-base subobject path.
1752 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1753 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1754 << D.MostDerivedType << TargetQT;
1755 return false;
1756 }
1757
Richard Smithe24f5fc2011-11-17 22:56:20 +00001758 // Check the type of the final cast. We don't need to check the path,
1759 // since a cast can only be formed if the path is unique.
1760 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001761 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1762 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001763 if (NewEntriesSize == D.MostDerivedPathLength)
1764 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1765 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001766 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001767 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1768 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1769 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001770 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001771 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001772
1773 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001774 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001775}
1776
Mike Stumpc4c90452009-10-27 22:09:17 +00001777namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001778enum EvalStmtResult {
1779 /// Evaluation failed.
1780 ESR_Failed,
1781 /// Hit a 'return' statement.
1782 ESR_Returned,
1783 /// Evaluation succeeded.
1784 ESR_Succeeded
1785};
1786}
1787
1788// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001789static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001790 const Stmt *S) {
1791 switch (S->getStmtClass()) {
1792 default:
1793 return ESR_Failed;
1794
1795 case Stmt::NullStmtClass:
1796 case Stmt::DeclStmtClass:
1797 return ESR_Succeeded;
1798
Richard Smithc1c5f272011-12-13 06:39:58 +00001799 case Stmt::ReturnStmtClass: {
1800 CCValue CCResult;
1801 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1802 if (!Evaluate(CCResult, Info, RetExpr) ||
1803 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1804 CCEK_ReturnValue))
1805 return ESR_Failed;
1806 return ESR_Returned;
1807 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001808
1809 case Stmt::CompoundStmtClass: {
1810 const CompoundStmt *CS = cast<CompoundStmt>(S);
1811 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1812 BE = CS->body_end(); BI != BE; ++BI) {
1813 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1814 if (ESR != ESR_Succeeded)
1815 return ESR;
1816 }
1817 return ESR_Succeeded;
1818 }
1819 }
1820}
1821
Richard Smith61802452011-12-22 02:22:31 +00001822/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1823/// default constructor. If so, we'll fold it whether or not it's marked as
1824/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1825/// so we need special handling.
1826static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00001827 const CXXConstructorDecl *CD,
1828 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001829 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1830 return false;
1831
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001832 // Value-initialization does not call a trivial default constructor, so such a
1833 // call is a core constant expression whether or not the constructor is
1834 // constexpr.
1835 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001836 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001837 // FIXME: If DiagDecl is an implicitly-declared special member function,
1838 // we should be much more explicit about why it's not constexpr.
1839 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1840 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1841 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00001842 } else {
1843 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1844 }
1845 }
1846 return true;
1847}
1848
Richard Smithc1c5f272011-12-13 06:39:58 +00001849/// CheckConstexprFunction - Check that a function can be called in a constant
1850/// expression.
1851static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1852 const FunctionDecl *Declaration,
1853 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00001854 // Potential constant expressions can contain calls to declared, but not yet
1855 // defined, constexpr functions.
1856 if (Info.CheckingPotentialConstantExpression && !Definition &&
1857 Declaration->isConstexpr())
1858 return false;
1859
Richard Smithc1c5f272011-12-13 06:39:58 +00001860 // Can we evaluate this function call?
1861 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1862 return true;
1863
1864 if (Info.getLangOpts().CPlusPlus0x) {
1865 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001866 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1867 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001868 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1869 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1870 << DiagDecl;
1871 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1872 } else {
1873 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1874 }
1875 return false;
1876}
1877
Richard Smith180f4792011-11-10 06:34:14 +00001878namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001879typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001880}
1881
1882/// EvaluateArgs - Evaluate the arguments to a function call.
1883static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1884 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00001885 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001886 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00001887 I != E; ++I) {
1888 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
1889 // If we're checking for a potential constant expression, evaluate all
1890 // initializers even if some of them fail.
1891 if (!Info.keepEvaluatingAfterFailure())
1892 return false;
1893 Success = false;
1894 }
1895 }
1896 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00001897}
1898
Richard Smithd0dccea2011-10-28 22:34:42 +00001899/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00001900static bool HandleFunctionCall(SourceLocation CallLoc,
1901 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00001902 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001903 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00001904 ArgVector ArgValues(Args.size());
1905 if (!EvaluateArgs(Args, ArgValues, Info))
1906 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001907
Richard Smith745f5142012-01-27 01:14:48 +00001908 if (!Info.CheckCallLimit(CallLoc))
1909 return false;
1910
1911 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001912 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1913}
1914
Richard Smith180f4792011-11-10 06:34:14 +00001915/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00001916static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001917 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001918 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00001919 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00001920 ArgVector ArgValues(Args.size());
1921 if (!EvaluateArgs(Args, ArgValues, Info))
1922 return false;
1923
Richard Smith745f5142012-01-27 01:14:48 +00001924 if (!Info.CheckCallLimit(CallLoc))
1925 return false;
1926
1927 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00001928
1929 // If it's a delegating constructor, just delegate.
1930 if (Definition->isDelegatingConstructor()) {
1931 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1932 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1933 }
1934
Richard Smith610a60c2012-01-10 04:32:03 +00001935 // For a trivial copy or move constructor, perform an APValue copy. This is
1936 // essential for unions, where the operations performed by the constructor
1937 // cannot be represented by ctor-initializers.
Richard Smith180f4792011-11-10 06:34:14 +00001938 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith610a60c2012-01-10 04:32:03 +00001939 if (Definition->isDefaulted() &&
1940 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
1941 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
1942 LValue RHS;
1943 RHS.setFrom(ArgValues[0]);
1944 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00001945 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
1946 RHS, Value))
1947 return false;
1948 assert((Value.isStruct() || Value.isUnion()) &&
1949 "trivial copy/move from non-class type?");
1950 // Any CCValue of class type must already be a constant expression.
1951 Result = Value;
1952 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00001953 }
1954
1955 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00001956 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00001957 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1958 std::distance(RD->field_begin(), RD->field_end()));
1959
1960 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1961
Richard Smith745f5142012-01-27 01:14:48 +00001962 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001963 unsigned BasesSeen = 0;
1964#ifndef NDEBUG
1965 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1966#endif
1967 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1968 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00001969 LValue Subobject = This;
1970 APValue *Value = &Result;
1971
1972 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00001973 if ((*I)->isBaseInitializer()) {
1974 QualType BaseType((*I)->getBaseClass(), 0);
1975#ifndef NDEBUG
1976 // Non-virtual base classes are initialized in the order in the class
1977 // definition. We cannot have a virtual base class for a literal type.
1978 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1979 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1980 "base class initializers not in expected order");
1981 ++BaseIt;
1982#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00001983 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00001984 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00001985 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00001986 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001987 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00001988 if (RD->isUnion()) {
1989 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00001990 Value = &Result.getUnionValue();
1991 } else {
1992 Value = &Result.getStructField(FD->getFieldIndex());
1993 }
Richard Smithd9b02e72012-01-25 22:15:11 +00001994 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001995 // Walk the indirect field decl's chain to find the object to initialize,
1996 // and make sure we've initialized every step along it.
1997 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1998 CE = IFD->chain_end();
1999 C != CE; ++C) {
2000 FieldDecl *FD = cast<FieldDecl>(*C);
2001 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2002 // Switch the union field if it differs. This happens if we had
2003 // preceding zero-initialization, and we're now initializing a union
2004 // subobject other than the first.
2005 // FIXME: In this case, the values of the other subobjects are
2006 // specified, since zero-initialization sets all padding bits to zero.
2007 if (Value->isUninit() ||
2008 (Value->isUnion() && Value->getUnionField() != FD)) {
2009 if (CD->isUnion())
2010 *Value = APValue(FD);
2011 else
2012 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2013 std::distance(CD->field_begin(), CD->field_end()));
2014 }
Richard Smith745f5142012-01-27 01:14:48 +00002015 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002016 if (CD->isUnion())
2017 Value = &Value->getUnionValue();
2018 else
2019 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002020 }
Richard Smith180f4792011-11-10 06:34:14 +00002021 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002022 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002023 }
Richard Smith745f5142012-01-27 01:14:48 +00002024
2025 if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
2026 (*I)->isBaseInitializer()
2027 ? CCEK_Constant : CCEK_MemberInit)) {
2028 // If we're checking for a potential constant expression, evaluate all
2029 // initializers even if some of them fail.
2030 if (!Info.keepEvaluatingAfterFailure())
2031 return false;
2032 Success = false;
2033 }
Richard Smith180f4792011-11-10 06:34:14 +00002034 }
2035
Richard Smith745f5142012-01-27 01:14:48 +00002036 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002037}
2038
Richard Smithd0dccea2011-10-28 22:34:42 +00002039namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002040class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002041 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002042 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002043public:
2044
Richard Smith1e12c592011-10-16 21:26:27 +00002045 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002046
2047 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002048 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002049 return true;
2050 }
2051
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002052 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2053 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002054 return Visit(E->getResultExpr());
2055 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002056 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002057 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002058 return true;
2059 return false;
2060 }
John McCallf85e1932011-06-15 23:02:42 +00002061 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002062 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002063 return true;
2064 return false;
2065 }
2066 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002067 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002068 return true;
2069 return false;
2070 }
2071
Mike Stumpc4c90452009-10-27 22:09:17 +00002072 // We don't want to evaluate BlockExprs multiple times, as they generate
2073 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002074 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2075 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2076 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002077 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002078 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2079 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2080 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2081 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2082 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2083 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002084 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002085 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002086 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002087 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002088 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002089 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2090 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2091 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2092 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002093 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002094 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2095 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2096 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2097 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2098 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002099 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002100 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002101 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002102 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002103 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002104
2105 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002106 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002107 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2108 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002109 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002110 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002111 return false;
2112 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002113
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002114 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002115};
2116
John McCall56ca35d2011-02-17 10:25:35 +00002117class OpaqueValueEvaluation {
2118 EvalInfo &info;
2119 OpaqueValueExpr *opaqueValue;
2120
2121public:
2122 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2123 Expr *value)
2124 : info(info), opaqueValue(opaqueValue) {
2125
2126 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002127 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002128 this->opaqueValue = 0;
2129 return;
2130 }
John McCall56ca35d2011-02-17 10:25:35 +00002131 }
2132
2133 bool hasError() const { return opaqueValue == 0; }
2134
2135 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00002136 // FIXME: This will not work for recursive constexpr functions using opaque
2137 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00002138 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2139 }
2140};
2141
Mike Stumpc4c90452009-10-27 22:09:17 +00002142} // end anonymous namespace
2143
Eli Friedman4efaa272008-11-12 09:44:48 +00002144//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002145// Generic Evaluation
2146//===----------------------------------------------------------------------===//
2147namespace {
2148
Richard Smithf48fdb02011-12-09 22:58:01 +00002149// FIXME: RetTy is always bool. Remove it.
2150template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002151class ExprEvaluatorBase
2152 : public ConstStmtVisitor<Derived, RetTy> {
2153private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002154 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002155 return static_cast<Derived*>(this)->Success(V, E);
2156 }
Richard Smith51201882011-12-30 21:15:51 +00002157 RetTy DerivedZeroInitialization(const Expr *E) {
2158 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002159 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002160
2161protected:
2162 EvalInfo &Info;
2163 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2164 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2165
Richard Smithdd1f29b2011-12-12 09:28:41 +00002166 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002167 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002168 }
2169
2170 /// Report an evaluation error. This should only be called when an error is
2171 /// first discovered. When propagating an error, just return false.
2172 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002173 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002174 return false;
2175 }
2176 bool Error(const Expr *E) {
2177 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2178 }
2179
Richard Smith51201882011-12-30 21:15:51 +00002180 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002181
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002182public:
2183 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2184
2185 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002186 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002187 }
2188 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002189 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002190 }
2191
2192 RetTy VisitParenExpr(const ParenExpr *E)
2193 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2194 RetTy VisitUnaryExtension(const UnaryOperator *E)
2195 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2196 RetTy VisitUnaryPlus(const UnaryOperator *E)
2197 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2198 RetTy VisitChooseExpr(const ChooseExpr *E)
2199 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2200 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2201 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002202 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2203 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002204 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2205 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002206 // We cannot create any objects for which cleanups are required, so there is
2207 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2208 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2209 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002210
Richard Smithc216a012011-12-12 12:46:16 +00002211 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2212 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2213 return static_cast<Derived*>(this)->VisitCastExpr(E);
2214 }
2215 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2216 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2217 return static_cast<Derived*>(this)->VisitCastExpr(E);
2218 }
2219
Richard Smithe24f5fc2011-11-17 22:56:20 +00002220 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2221 switch (E->getOpcode()) {
2222 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002223 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002224
2225 case BO_Comma:
2226 VisitIgnoredValue(E->getLHS());
2227 return StmtVisitorTy::Visit(E->getRHS());
2228
2229 case BO_PtrMemD:
2230 case BO_PtrMemI: {
2231 LValue Obj;
2232 if (!HandleMemberPointerAccess(Info, E, Obj))
2233 return false;
2234 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002235 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002236 return false;
2237 return DerivedSuccess(Result, E);
2238 }
2239 }
2240 }
2241
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002242 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2243 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2244 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002245 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002246
2247 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002248 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002249 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002250
2251 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2252 }
2253
2254 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2255 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002256 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002257 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002258
Richard Smithc49bd112011-10-28 17:51:58 +00002259 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002260 return StmtVisitorTy::Visit(EvalExpr);
2261 }
2262
2263 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002264 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002265 if (!Value) {
2266 const Expr *Source = E->getSourceExpr();
2267 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002268 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002269 if (Source == E) { // sanity checking.
2270 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002271 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002272 }
2273 return StmtVisitorTy::Visit(Source);
2274 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002275 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002276 }
Richard Smithf10d9172011-10-11 21:43:33 +00002277
Richard Smithd0dccea2011-10-28 22:34:42 +00002278 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002279 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002280 QualType CalleeType = Callee->getType();
2281
Richard Smithd0dccea2011-10-28 22:34:42 +00002282 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002283 LValue *This = 0, ThisVal;
2284 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002285
Richard Smith59efe262011-11-11 04:05:33 +00002286 // Extract function decl and 'this' pointer from the callee.
2287 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002288 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002289 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2290 // Explicit bound member calls, such as x.f() or p->g();
2291 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002292 return false;
2293 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002294 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002295 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2296 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002297 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2298 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002299 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002300 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002301 return Error(Callee);
2302
2303 FD = dyn_cast<FunctionDecl>(Member);
2304 if (!FD)
2305 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002306 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002307 LValue Call;
2308 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002309 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002310
Richard Smithb4e85ed2012-01-06 16:39:00 +00002311 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002312 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002313 FD = dyn_cast_or_null<FunctionDecl>(
2314 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002315 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002316 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002317
2318 // Overloaded operator calls to member functions are represented as normal
2319 // calls with '*this' as the first argument.
2320 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2321 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002322 // FIXME: When selecting an implicit conversion for an overloaded
2323 // operator delete, we sometimes try to evaluate calls to conversion
2324 // operators without a 'this' parameter!
2325 if (Args.empty())
2326 return Error(E);
2327
Richard Smith59efe262011-11-11 04:05:33 +00002328 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2329 return false;
2330 This = &ThisVal;
2331 Args = Args.slice(1);
2332 }
2333
2334 // Don't call function pointers which have been cast to some other type.
2335 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002336 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002337 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002338 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002339
Richard Smithc1c5f272011-12-13 06:39:58 +00002340 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002341 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002342 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002343
Richard Smithc1c5f272011-12-13 06:39:58 +00002344 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002345 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2346 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002347 return false;
2348
Richard Smithb4e85ed2012-01-06 16:39:00 +00002349 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002350 }
2351
Richard Smithc49bd112011-10-28 17:51:58 +00002352 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2353 return StmtVisitorTy::Visit(E->getInitializer());
2354 }
Richard Smithf10d9172011-10-11 21:43:33 +00002355 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002356 if (E->getNumInits() == 0)
2357 return DerivedZeroInitialization(E);
2358 if (E->getNumInits() == 1)
2359 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002360 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002361 }
2362 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002363 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002364 }
2365 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002366 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002367 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002368 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002369 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002370 }
Richard Smithf10d9172011-10-11 21:43:33 +00002371
Richard Smith180f4792011-11-10 06:34:14 +00002372 /// A member expression where the object is a prvalue is itself a prvalue.
2373 RetTy VisitMemberExpr(const MemberExpr *E) {
2374 assert(!E->isArrow() && "missing call to bound member function?");
2375
2376 CCValue Val;
2377 if (!Evaluate(Val, Info, E->getBase()))
2378 return false;
2379
2380 QualType BaseTy = E->getBase()->getType();
2381
2382 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002383 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002384 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2385 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2386 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2387
Richard Smithb4e85ed2012-01-06 16:39:00 +00002388 SubobjectDesignator Designator(BaseTy);
2389 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002390
Richard Smithf48fdb02011-12-09 22:58:01 +00002391 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002392 DerivedSuccess(Val, E);
2393 }
2394
Richard Smithc49bd112011-10-28 17:51:58 +00002395 RetTy VisitCastExpr(const CastExpr *E) {
2396 switch (E->getCastKind()) {
2397 default:
2398 break;
2399
David Chisnall7a7ee302012-01-16 17:27:18 +00002400 case CK_AtomicToNonAtomic:
2401 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002402 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002403 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002404 return StmtVisitorTy::Visit(E->getSubExpr());
2405
2406 case CK_LValueToRValue: {
2407 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002408 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2409 return false;
2410 CCValue RVal;
2411 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2412 return false;
2413 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002414 }
2415 }
2416
Richard Smithf48fdb02011-12-09 22:58:01 +00002417 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002418 }
2419
Richard Smith8327fad2011-10-24 18:44:57 +00002420 /// Visit a value which is evaluated, but whose value is ignored.
2421 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002422 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002423 if (!Evaluate(Scratch, Info, E))
2424 Info.EvalStatus.HasSideEffects = true;
2425 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002426};
2427
2428}
2429
2430//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002431// Common base class for lvalue and temporary evaluation.
2432//===----------------------------------------------------------------------===//
2433namespace {
2434template<class Derived>
2435class LValueExprEvaluatorBase
2436 : public ExprEvaluatorBase<Derived, bool> {
2437protected:
2438 LValue &Result;
2439 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2440 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2441
2442 bool Success(APValue::LValueBase B) {
2443 Result.set(B);
2444 return true;
2445 }
2446
2447public:
2448 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2449 ExprEvaluatorBaseTy(Info), Result(Result) {}
2450
2451 bool Success(const CCValue &V, const Expr *E) {
2452 Result.setFrom(V);
2453 return true;
2454 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002455
Richard Smithe24f5fc2011-11-17 22:56:20 +00002456 bool VisitMemberExpr(const MemberExpr *E) {
2457 // Handle non-static data members.
2458 QualType BaseTy;
2459 if (E->isArrow()) {
2460 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2461 return false;
2462 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002463 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002464 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002465 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2466 return false;
2467 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002468 } else {
2469 if (!this->Visit(E->getBase()))
2470 return false;
2471 BaseTy = E->getBase()->getType();
2472 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002473
Richard Smithd9b02e72012-01-25 22:15:11 +00002474 const ValueDecl *MD = E->getMemberDecl();
2475 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2476 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2477 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2478 (void)BaseTy;
2479 HandleLValueMember(this->Info, E, Result, FD);
2480 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2481 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2482 } else
2483 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002484
Richard Smithd9b02e72012-01-25 22:15:11 +00002485 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002486 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002487 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002488 RefValue))
2489 return false;
2490 return Success(RefValue, E);
2491 }
2492 return true;
2493 }
2494
2495 bool VisitBinaryOperator(const BinaryOperator *E) {
2496 switch (E->getOpcode()) {
2497 default:
2498 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2499
2500 case BO_PtrMemD:
2501 case BO_PtrMemI:
2502 return HandleMemberPointerAccess(this->Info, E, Result);
2503 }
2504 }
2505
2506 bool VisitCastExpr(const CastExpr *E) {
2507 switch (E->getCastKind()) {
2508 default:
2509 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2510
2511 case CK_DerivedToBase:
2512 case CK_UncheckedDerivedToBase: {
2513 if (!this->Visit(E->getSubExpr()))
2514 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002515
2516 // Now figure out the necessary offset to add to the base LV to get from
2517 // the derived class to the base class.
2518 QualType Type = E->getSubExpr()->getType();
2519
2520 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2521 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002522 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002523 *PathI))
2524 return false;
2525 Type = (*PathI)->getType();
2526 }
2527
2528 return true;
2529 }
2530 }
2531 }
2532};
2533}
2534
2535//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002536// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002537//
2538// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2539// function designators (in C), decl references to void objects (in C), and
2540// temporaries (if building with -Wno-address-of-temporary).
2541//
2542// LValue evaluation produces values comprising a base expression of one of the
2543// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002544// - Declarations
2545// * VarDecl
2546// * FunctionDecl
2547// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002548// * CompoundLiteralExpr in C
2549// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002550// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002551// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002552// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002553// * ObjCEncodeExpr
2554// * AddrLabelExpr
2555// * BlockExpr
2556// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002557// - Locals and temporaries
2558// * Any Expr, with a Frame indicating the function in which the temporary was
2559// evaluated.
2560// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002561//===----------------------------------------------------------------------===//
2562namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002563class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002564 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002565public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002566 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2567 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002568
Richard Smithc49bd112011-10-28 17:51:58 +00002569 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2570
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002571 bool VisitDeclRefExpr(const DeclRefExpr *E);
2572 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002573 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002574 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2575 bool VisitMemberExpr(const MemberExpr *E);
2576 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2577 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002578 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002579 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2580 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002581
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002582 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002583 switch (E->getCastKind()) {
2584 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002585 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002586
Eli Friedmandb924222011-10-11 00:13:24 +00002587 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002588 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002589 if (!Visit(E->getSubExpr()))
2590 return false;
2591 Result.Designator.setInvalid();
2592 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002593
Richard Smithe24f5fc2011-11-17 22:56:20 +00002594 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002595 if (!Visit(E->getSubExpr()))
2596 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002597 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002598 }
2599 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002600
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002601 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002602
Eli Friedman4efaa272008-11-12 09:44:48 +00002603};
2604} // end anonymous namespace
2605
Richard Smithc49bd112011-10-28 17:51:58 +00002606/// Evaluate an expression as an lvalue. This can be legitimately called on
2607/// expressions which are not glvalues, in a few cases:
2608/// * function designators in C,
2609/// * "extern void" objects,
2610/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002611static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002612 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2613 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2614 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002615 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002616}
2617
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002618bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002619 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2620 return Success(FD);
2621 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002622 return VisitVarDecl(E, VD);
2623 return Error(E);
2624}
Richard Smith436c8892011-10-24 23:14:33 +00002625
Richard Smithc49bd112011-10-28 17:51:58 +00002626bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002627 if (!VD->getType()->isReferenceType()) {
2628 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002629 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002630 return true;
2631 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002632 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002633 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002634
Richard Smith47a1eed2011-10-29 20:57:55 +00002635 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002636 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2637 return false;
2638 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002639}
2640
Richard Smithbd552ef2011-10-31 05:52:43 +00002641bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2642 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002643 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002644 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002645 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2646
2647 Result.set(E, Info.CurrentCall);
2648 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2649 Result, E->GetTemporaryExpr());
2650 }
2651
2652 // Materialization of an lvalue temporary occurs when we need to force a copy
2653 // (for instance, if it's a bitfield).
2654 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2655 if (!Visit(E->GetTemporaryExpr()))
2656 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002657 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002658 Info.CurrentCall->Temporaries[E]))
2659 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002660 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002661 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002662}
2663
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002664bool
2665LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002666 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2667 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2668 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002669 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002670}
2671
Richard Smith47d21452011-12-27 12:18:28 +00002672bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2673 if (E->isTypeOperand())
2674 return Success(E);
2675 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2676 if (RD && RD->isPolymorphic()) {
2677 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2678 << E->getExprOperand()->getType()
2679 << E->getExprOperand()->getSourceRange();
2680 return false;
2681 }
2682 return Success(E);
2683}
2684
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002685bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002686 // Handle static data members.
2687 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2688 VisitIgnoredValue(E->getBase());
2689 return VisitVarDecl(E, VD);
2690 }
2691
Richard Smithd0dccea2011-10-28 22:34:42 +00002692 // Handle static member functions.
2693 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2694 if (MD->isStatic()) {
2695 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002696 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002697 }
2698 }
2699
Richard Smith180f4792011-11-10 06:34:14 +00002700 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002701 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002702}
2703
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002704bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002705 // FIXME: Deal with vectors as array subscript bases.
2706 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002707 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002708
Anders Carlsson3068d112008-11-16 19:01:22 +00002709 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002710 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002711
Anders Carlsson3068d112008-11-16 19:01:22 +00002712 APSInt Index;
2713 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002714 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002715 int64_t IndexValue
2716 = Index.isSigned() ? Index.getSExtValue()
2717 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002718
Richard Smithb4e85ed2012-01-06 16:39:00 +00002719 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002720}
Eli Friedman4efaa272008-11-12 09:44:48 +00002721
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002722bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002723 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002724}
2725
Eli Friedman4efaa272008-11-12 09:44:48 +00002726//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002727// Pointer Evaluation
2728//===----------------------------------------------------------------------===//
2729
Anders Carlssonc754aa62008-07-08 05:13:58 +00002730namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002731class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002732 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002733 LValue &Result;
2734
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002735 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002736 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002737 return true;
2738 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002739public:
Mike Stump1eb44332009-09-09 15:08:12 +00002740
John McCallefdb83e2010-05-07 21:00:08 +00002741 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002742 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002743
Richard Smith47a1eed2011-10-29 20:57:55 +00002744 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002745 Result.setFrom(V);
2746 return true;
2747 }
Richard Smith51201882011-12-30 21:15:51 +00002748 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002749 return Success((Expr*)0);
2750 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002751
John McCallefdb83e2010-05-07 21:00:08 +00002752 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002753 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002754 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002755 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002756 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002757 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002758 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002759 bool VisitCallExpr(const CallExpr *E);
2760 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002761 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002762 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002763 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002764 }
Richard Smith180f4792011-11-10 06:34:14 +00002765 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2766 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002767 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002768 Result = *Info.CurrentCall->This;
2769 return true;
2770 }
John McCall56ca35d2011-02-17 10:25:35 +00002771
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002772 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002773};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002774} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002775
John McCallefdb83e2010-05-07 21:00:08 +00002776static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002777 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002778 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002779}
2780
John McCallefdb83e2010-05-07 21:00:08 +00002781bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002782 if (E->getOpcode() != BO_Add &&
2783 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002784 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002785
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002786 const Expr *PExp = E->getLHS();
2787 const Expr *IExp = E->getRHS();
2788 if (IExp->getType()->isPointerType())
2789 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002790
Richard Smith745f5142012-01-27 01:14:48 +00002791 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
2792 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00002793 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002794
John McCallefdb83e2010-05-07 21:00:08 +00002795 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00002796 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00002797 return false;
2798 int64_t AdditionalOffset
2799 = Offset.isSigned() ? Offset.getSExtValue()
2800 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002801 if (E->getOpcode() == BO_Sub)
2802 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002803
Richard Smith180f4792011-11-10 06:34:14 +00002804 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00002805 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2806 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002807}
Eli Friedman4efaa272008-11-12 09:44:48 +00002808
John McCallefdb83e2010-05-07 21:00:08 +00002809bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2810 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002811}
Mike Stump1eb44332009-09-09 15:08:12 +00002812
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002813bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2814 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002815
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002816 switch (E->getCastKind()) {
2817 default:
2818 break;
2819
John McCall2de56d12010-08-25 11:45:40 +00002820 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002821 case CK_CPointerToObjCPointerCast:
2822 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002823 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00002824 if (!Visit(SubExpr))
2825 return false;
Richard Smithc216a012011-12-12 12:46:16 +00002826 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2827 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2828 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002829 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00002830 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002831 if (SubExpr->getType()->isVoidPointerType())
2832 CCEDiag(E, diag::note_constexpr_invalid_cast)
2833 << 3 << SubExpr->getType();
2834 else
2835 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2836 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002837 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002838
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002839 case CK_DerivedToBase:
2840 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002841 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002842 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002843 if (!Result.Base && Result.Offset.isZero())
2844 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002845
Richard Smith180f4792011-11-10 06:34:14 +00002846 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002847 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002848 QualType Type =
2849 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002850
Richard Smith180f4792011-11-10 06:34:14 +00002851 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002852 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002853 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2854 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002855 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002856 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002857 }
2858
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002859 return true;
2860 }
2861
Richard Smithe24f5fc2011-11-17 22:56:20 +00002862 case CK_BaseToDerived:
2863 if (!Visit(E->getSubExpr()))
2864 return false;
2865 if (!Result.Base && Result.Offset.isZero())
2866 return true;
2867 return HandleBaseToDerivedCast(Info, E, Result);
2868
Richard Smith47a1eed2011-10-29 20:57:55 +00002869 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00002870 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002871
John McCall2de56d12010-08-25 11:45:40 +00002872 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002873 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2874
Richard Smith47a1eed2011-10-29 20:57:55 +00002875 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002876 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002877 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002878
John McCallefdb83e2010-05-07 21:00:08 +00002879 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002880 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2881 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002882 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002883 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002884 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002885 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002886 return true;
2887 } else {
2888 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002889 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002890 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002891 }
2892 }
John McCall2de56d12010-08-25 11:45:40 +00002893 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002894 if (SubExpr->isGLValue()) {
2895 if (!EvaluateLValue(SubExpr, Result, Info))
2896 return false;
2897 } else {
2898 Result.set(SubExpr, Info.CurrentCall);
2899 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2900 Info, Result, SubExpr))
2901 return false;
2902 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002903 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002904 if (const ConstantArrayType *CAT
2905 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
2906 Result.addArray(Info, E, CAT);
2907 else
2908 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00002909 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002910
John McCall2de56d12010-08-25 11:45:40 +00002911 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002912 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002913 }
2914
Richard Smithc49bd112011-10-28 17:51:58 +00002915 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002916}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002917
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002918bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002919 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002920 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002921
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002922 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002923}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002924
2925//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002926// Member Pointer Evaluation
2927//===----------------------------------------------------------------------===//
2928
2929namespace {
2930class MemberPointerExprEvaluator
2931 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2932 MemberPtr &Result;
2933
2934 bool Success(const ValueDecl *D) {
2935 Result = MemberPtr(D);
2936 return true;
2937 }
2938public:
2939
2940 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2941 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2942
2943 bool Success(const CCValue &V, const Expr *E) {
2944 Result.setFrom(V);
2945 return true;
2946 }
Richard Smith51201882011-12-30 21:15:51 +00002947 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002948 return Success((const ValueDecl*)0);
2949 }
2950
2951 bool VisitCastExpr(const CastExpr *E);
2952 bool VisitUnaryAddrOf(const UnaryOperator *E);
2953};
2954} // end anonymous namespace
2955
2956static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2957 EvalInfo &Info) {
2958 assert(E->isRValue() && E->getType()->isMemberPointerType());
2959 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2960}
2961
2962bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2963 switch (E->getCastKind()) {
2964 default:
2965 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2966
2967 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00002968 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002969
2970 case CK_BaseToDerivedMemberPointer: {
2971 if (!Visit(E->getSubExpr()))
2972 return false;
2973 if (E->path_empty())
2974 return true;
2975 // Base-to-derived member pointer casts store the path in derived-to-base
2976 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2977 // the wrong end of the derived->base arc, so stagger the path by one class.
2978 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2979 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2980 PathI != PathE; ++PathI) {
2981 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2982 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2983 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00002984 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002985 }
2986 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2987 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002988 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002989 return true;
2990 }
2991
2992 case CK_DerivedToBaseMemberPointer:
2993 if (!Visit(E->getSubExpr()))
2994 return false;
2995 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2996 PathE = E->path_end(); PathI != PathE; ++PathI) {
2997 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2998 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2999 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003000 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003001 }
3002 return true;
3003 }
3004}
3005
3006bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3007 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3008 // member can be formed.
3009 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3010}
3011
3012//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003013// Record Evaluation
3014//===----------------------------------------------------------------------===//
3015
3016namespace {
3017 class RecordExprEvaluator
3018 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3019 const LValue &This;
3020 APValue &Result;
3021 public:
3022
3023 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3024 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3025
3026 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003027 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00003028 }
Richard Smith51201882011-12-30 21:15:51 +00003029 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003030
Richard Smith59efe262011-11-11 04:05:33 +00003031 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003032 bool VisitInitListExpr(const InitListExpr *E);
3033 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3034 };
3035}
3036
Richard Smith51201882011-12-30 21:15:51 +00003037/// Perform zero-initialization on an object of non-union class type.
3038/// C++11 [dcl.init]p5:
3039/// To zero-initialize an object or reference of type T means:
3040/// [...]
3041/// -- if T is a (possibly cv-qualified) non-union class type,
3042/// each non-static data member and each base-class subobject is
3043/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003044static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3045 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003046 const LValue &This, APValue &Result) {
3047 assert(!RD->isUnion() && "Expected non-union class type");
3048 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3049 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3050 std::distance(RD->field_begin(), RD->field_end()));
3051
3052 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3053
3054 if (CD) {
3055 unsigned Index = 0;
3056 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003057 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003058 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3059 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003060 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3061 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003062 Result.getStructBase(Index)))
3063 return false;
3064 }
3065 }
3066
Richard Smithb4e85ed2012-01-06 16:39:00 +00003067 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3068 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003069 // -- if T is a reference type, no initialization is performed.
3070 if ((*I)->getType()->isReferenceType())
3071 continue;
3072
3073 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003074 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003075
3076 ImplicitValueInitExpr VIE((*I)->getType());
3077 if (!EvaluateConstantExpression(
3078 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3079 return false;
3080 }
3081
3082 return true;
3083}
3084
3085bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3086 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3087 if (RD->isUnion()) {
3088 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3089 // object's first non-static named data member is zero-initialized
3090 RecordDecl::field_iterator I = RD->field_begin();
3091 if (I == RD->field_end()) {
3092 Result = APValue((const FieldDecl*)0);
3093 return true;
3094 }
3095
3096 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003097 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003098 Result = APValue(*I);
3099 ImplicitValueInitExpr VIE((*I)->getType());
3100 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3101 Subobject, &VIE);
3102 }
3103
Richard Smithb4e85ed2012-01-06 16:39:00 +00003104 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003105}
3106
Richard Smith59efe262011-11-11 04:05:33 +00003107bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3108 switch (E->getCastKind()) {
3109 default:
3110 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3111
3112 case CK_ConstructorConversion:
3113 return Visit(E->getSubExpr());
3114
3115 case CK_DerivedToBase:
3116 case CK_UncheckedDerivedToBase: {
3117 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003118 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003119 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003120 if (!DerivedObject.isStruct())
3121 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003122
3123 // Derived-to-base rvalue conversion: just slice off the derived part.
3124 APValue *Value = &DerivedObject;
3125 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3126 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3127 PathE = E->path_end(); PathI != PathE; ++PathI) {
3128 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3129 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3130 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3131 RD = Base;
3132 }
3133 Result = *Value;
3134 return true;
3135 }
3136 }
3137}
3138
Richard Smith180f4792011-11-10 06:34:14 +00003139bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3140 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3141 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3142
3143 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003144 const FieldDecl *Field = E->getInitializedFieldInUnion();
3145 Result = APValue(Field);
3146 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003147 return true;
Richard Smithec789162012-01-12 18:54:33 +00003148
3149 // If the initializer list for a union does not contain any elements, the
3150 // first element of the union is value-initialized.
3151 ImplicitValueInitExpr VIE(Field->getType());
3152 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3153
Richard Smith180f4792011-11-10 06:34:14 +00003154 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003155 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003156 return EvaluateConstantExpression(Result.getUnionValue(), Info,
Richard Smithec789162012-01-12 18:54:33 +00003157 Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003158 }
3159
3160 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3161 "initializer list for class with base classes");
3162 Result = APValue(APValue::UninitStruct(), 0,
3163 std::distance(RD->field_begin(), RD->field_end()));
3164 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003165 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003166 for (RecordDecl::field_iterator Field = RD->field_begin(),
3167 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3168 // Anonymous bit-fields are not considered members of the class for
3169 // purposes of aggregate initialization.
3170 if (Field->isUnnamedBitfield())
3171 continue;
3172
3173 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003174
Richard Smith745f5142012-01-27 01:14:48 +00003175 bool HaveInit = ElementNo < E->getNumInits();
3176
3177 // FIXME: Diagnostics here should point to the end of the initializer
3178 // list, not the start.
3179 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3180 *Field, &Layout);
3181
3182 // Perform an implicit value-initialization for members beyond the end of
3183 // the initializer list.
3184 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3185
3186 if (!EvaluateConstantExpression(
3187 Result.getStructField((*Field)->getFieldIndex()),
3188 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3189 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003190 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003191 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003192 }
3193 }
3194
Richard Smith745f5142012-01-27 01:14:48 +00003195 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003196}
3197
3198bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3199 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003200 bool ZeroInit = E->requiresZeroInitialization();
3201 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003202 // If we've already performed zero-initialization, we're already done.
3203 if (!Result.isUninit())
3204 return true;
3205
Richard Smith51201882011-12-30 21:15:51 +00003206 if (ZeroInit)
3207 return ZeroInitialization(E);
3208
Richard Smith61802452011-12-22 02:22:31 +00003209 const CXXRecordDecl *RD = FD->getParent();
3210 if (RD->isUnion())
3211 Result = APValue((FieldDecl*)0);
3212 else
3213 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3214 std::distance(RD->field_begin(), RD->field_end()));
3215 return true;
3216 }
3217
Richard Smith180f4792011-11-10 06:34:14 +00003218 const FunctionDecl *Definition = 0;
3219 FD->getBody(Definition);
3220
Richard Smithc1c5f272011-12-13 06:39:58 +00003221 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3222 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003223
Richard Smith610a60c2012-01-10 04:32:03 +00003224 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003225 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003226 if (const MaterializeTemporaryExpr *ME
3227 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3228 return Visit(ME->GetTemporaryExpr());
3229
Richard Smith51201882011-12-30 21:15:51 +00003230 if (ZeroInit && !ZeroInitialization(E))
3231 return false;
3232
Richard Smith180f4792011-11-10 06:34:14 +00003233 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003234 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003235 cast<CXXConstructorDecl>(Definition), Info,
3236 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003237}
3238
3239static bool EvaluateRecord(const Expr *E, const LValue &This,
3240 APValue &Result, EvalInfo &Info) {
3241 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003242 "can't evaluate expression as a record rvalue");
3243 return RecordExprEvaluator(Info, This, Result).Visit(E);
3244}
3245
3246//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003247// Temporary Evaluation
3248//
3249// Temporaries are represented in the AST as rvalues, but generally behave like
3250// lvalues. The full-object of which the temporary is a subobject is implicitly
3251// materialized so that a reference can bind to it.
3252//===----------------------------------------------------------------------===//
3253namespace {
3254class TemporaryExprEvaluator
3255 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3256public:
3257 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3258 LValueExprEvaluatorBaseTy(Info, Result) {}
3259
3260 /// Visit an expression which constructs the value of this temporary.
3261 bool VisitConstructExpr(const Expr *E) {
3262 Result.set(E, Info.CurrentCall);
3263 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3264 Result, E);
3265 }
3266
3267 bool VisitCastExpr(const CastExpr *E) {
3268 switch (E->getCastKind()) {
3269 default:
3270 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3271
3272 case CK_ConstructorConversion:
3273 return VisitConstructExpr(E->getSubExpr());
3274 }
3275 }
3276 bool VisitInitListExpr(const InitListExpr *E) {
3277 return VisitConstructExpr(E);
3278 }
3279 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3280 return VisitConstructExpr(E);
3281 }
3282 bool VisitCallExpr(const CallExpr *E) {
3283 return VisitConstructExpr(E);
3284 }
3285};
3286} // end anonymous namespace
3287
3288/// Evaluate an expression of record type as a temporary.
3289static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003290 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003291 return TemporaryExprEvaluator(Info, Result).Visit(E);
3292}
3293
3294//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003295// Vector Evaluation
3296//===----------------------------------------------------------------------===//
3297
3298namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003299 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003300 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3301 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003302 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003303
Richard Smith07fc6572011-10-22 21:10:00 +00003304 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3305 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003306
Richard Smith07fc6572011-10-22 21:10:00 +00003307 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3308 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3309 // FIXME: remove this APValue copy.
3310 Result = APValue(V.data(), V.size());
3311 return true;
3312 }
Richard Smith69c2c502011-11-04 05:33:44 +00003313 bool Success(const CCValue &V, const Expr *E) {
3314 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003315 Result = V;
3316 return true;
3317 }
Richard Smith51201882011-12-30 21:15:51 +00003318 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003319
Richard Smith07fc6572011-10-22 21:10:00 +00003320 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003321 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003322 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003323 bool VisitInitListExpr(const InitListExpr *E);
3324 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003325 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003326 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003327 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003328 };
3329} // end anonymous namespace
3330
3331static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003332 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003333 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003334}
3335
Richard Smith07fc6572011-10-22 21:10:00 +00003336bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3337 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003338 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003339
Richard Smithd62ca372011-12-06 22:44:34 +00003340 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003341 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003342
Eli Friedman46a52322011-03-25 00:43:55 +00003343 switch (E->getCastKind()) {
3344 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003345 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003346 if (SETy->isIntegerType()) {
3347 APSInt IntResult;
3348 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003349 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003350 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003351 } else if (SETy->isRealFloatingType()) {
3352 APFloat F(0.0);
3353 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003354 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003355 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003356 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003357 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003358 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003359
3360 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003361 SmallVector<APValue, 4> Elts(NElts, Val);
3362 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003363 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003364 case CK_BitCast: {
3365 // Evaluate the operand into an APInt we can extract from.
3366 llvm::APInt SValInt;
3367 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3368 return false;
3369 // Extract the elements
3370 QualType EltTy = VTy->getElementType();
3371 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3372 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3373 SmallVector<APValue, 4> Elts;
3374 if (EltTy->isRealFloatingType()) {
3375 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3376 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3377 unsigned FloatEltSize = EltSize;
3378 if (&Sem == &APFloat::x87DoubleExtended)
3379 FloatEltSize = 80;
3380 for (unsigned i = 0; i < NElts; i++) {
3381 llvm::APInt Elt;
3382 if (BigEndian)
3383 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3384 else
3385 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3386 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3387 }
3388 } else if (EltTy->isIntegerType()) {
3389 for (unsigned i = 0; i < NElts; i++) {
3390 llvm::APInt Elt;
3391 if (BigEndian)
3392 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3393 else
3394 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3395 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3396 }
3397 } else {
3398 return Error(E);
3399 }
3400 return Success(Elts, E);
3401 }
Eli Friedman46a52322011-03-25 00:43:55 +00003402 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003403 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003404 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003405}
3406
Richard Smith07fc6572011-10-22 21:10:00 +00003407bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003408VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003409 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003410 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003411 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Nate Begeman59b5da62009-01-18 03:20:47 +00003413 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003414 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003415
Eli Friedman3edd5a92012-01-03 23:24:20 +00003416 // The number of initializers can be less than the number of
3417 // vector elements. For OpenCL, this can be due to nested vector
3418 // initialization. For GCC compatibility, missing trailing elements
3419 // should be initialized with zeroes.
3420 unsigned CountInits = 0, CountElts = 0;
3421 while (CountElts < NumElements) {
3422 // Handle nested vector initialization.
3423 if (CountInits < NumInits
3424 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3425 APValue v;
3426 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3427 return Error(E);
3428 unsigned vlen = v.getVectorLength();
3429 for (unsigned j = 0; j < vlen; j++)
3430 Elements.push_back(v.getVectorElt(j));
3431 CountElts += vlen;
3432 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003433 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003434 if (CountInits < NumInits) {
3435 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3436 return Error(E);
3437 } else // trailing integer zero.
3438 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3439 Elements.push_back(APValue(sInt));
3440 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003441 } else {
3442 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003443 if (CountInits < NumInits) {
3444 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3445 return Error(E);
3446 } else // trailing float zero.
3447 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3448 Elements.push_back(APValue(f));
3449 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003450 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003451 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003452 }
Richard Smith07fc6572011-10-22 21:10:00 +00003453 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003454}
3455
Richard Smith07fc6572011-10-22 21:10:00 +00003456bool
Richard Smith51201882011-12-30 21:15:51 +00003457VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003458 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003459 QualType EltTy = VT->getElementType();
3460 APValue ZeroElement;
3461 if (EltTy->isIntegerType())
3462 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3463 else
3464 ZeroElement =
3465 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3466
Chris Lattner5f9e2722011-07-23 10:55:15 +00003467 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003468 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003469}
3470
Richard Smith07fc6572011-10-22 21:10:00 +00003471bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003472 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003473 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003474}
3475
Nate Begeman59b5da62009-01-18 03:20:47 +00003476//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003477// Array Evaluation
3478//===----------------------------------------------------------------------===//
3479
3480namespace {
3481 class ArrayExprEvaluator
3482 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003483 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003484 APValue &Result;
3485 public:
3486
Richard Smith180f4792011-11-10 06:34:14 +00003487 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3488 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003489
3490 bool Success(const APValue &V, const Expr *E) {
3491 assert(V.isArray() && "Expected array type");
3492 Result = V;
3493 return true;
3494 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003495
Richard Smith51201882011-12-30 21:15:51 +00003496 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003497 const ConstantArrayType *CAT =
3498 Info.Ctx.getAsConstantArrayType(E->getType());
3499 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003500 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003501
3502 Result = APValue(APValue::UninitArray(), 0,
3503 CAT->getSize().getZExtValue());
3504 if (!Result.hasArrayFiller()) return true;
3505
Richard Smith51201882011-12-30 21:15:51 +00003506 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003507 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003508 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003509 ImplicitValueInitExpr VIE(CAT->getElementType());
3510 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3511 Subobject, &VIE);
3512 }
3513
Richard Smithcc5d4f62011-11-07 09:22:26 +00003514 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003515 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003516 };
3517} // end anonymous namespace
3518
Richard Smith180f4792011-11-10 06:34:14 +00003519static bool EvaluateArray(const Expr *E, const LValue &This,
3520 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003521 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003522 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003523}
3524
3525bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3526 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3527 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003528 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003529
Richard Smith974c5f92011-12-22 01:07:19 +00003530 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3531 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003532 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003533 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3534 LValue LV;
3535 if (!EvaluateLValue(E->getInit(0), LV, Info))
3536 return false;
3537 uint64_t NumElements = CAT->getSize().getZExtValue();
3538 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3539
3540 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003541 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003542 for (uint64_t I = 0; I < NumElements; ++I) {
3543 CCValue Char;
3544 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
Richard Smith745f5142012-01-27 01:14:48 +00003545 CAT->getElementType(), LV, Char) ||
3546 !CheckConstantExpression(Info, E->getInit(0), Char,
3547 Result.getArrayInitializedElt(I)) ||
3548 !HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
Richard Smithb4e85ed2012-01-06 16:39:00 +00003549 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003550 return false;
3551 }
3552 return true;
3553 }
3554
Richard Smith745f5142012-01-27 01:14:48 +00003555 bool Success = true;
3556
Richard Smithcc5d4f62011-11-07 09:22:26 +00003557 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3558 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003559 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003560 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003561 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003562 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003563 I != End; ++I, ++Index) {
3564 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
Richard Smith745f5142012-01-27 01:14:48 +00003565 Info, Subobject, cast<Expr>(*I)) ||
3566 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3567 CAT->getElementType(), 1)) {
3568 if (!Info.keepEvaluatingAfterFailure())
3569 return false;
3570 Success = false;
3571 }
Richard Smith180f4792011-11-10 06:34:14 +00003572 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003573
Richard Smith745f5142012-01-27 01:14:48 +00003574 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003575 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003576 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3577 // but sometimes does:
3578 // struct S { constexpr S() : p(&p) {} void *p; };
3579 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003580 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith745f5142012-01-27 01:14:48 +00003581 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003582}
3583
Richard Smithe24f5fc2011-11-17 22:56:20 +00003584bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3585 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3586 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003587 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003588
Richard Smithec789162012-01-12 18:54:33 +00003589 bool HadZeroInit = !Result.isUninit();
3590 if (!HadZeroInit)
3591 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003592 if (!Result.hasArrayFiller())
3593 return true;
3594
3595 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003596
Richard Smith51201882011-12-30 21:15:51 +00003597 bool ZeroInit = E->requiresZeroInitialization();
3598 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003599 if (HadZeroInit)
3600 return true;
3601
Richard Smith51201882011-12-30 21:15:51 +00003602 if (ZeroInit) {
3603 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003604 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003605 ImplicitValueInitExpr VIE(CAT->getElementType());
3606 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3607 Subobject, &VIE);
3608 }
3609
Richard Smith61802452011-12-22 02:22:31 +00003610 const CXXRecordDecl *RD = FD->getParent();
3611 if (RD->isUnion())
3612 Result.getArrayFiller() = APValue((FieldDecl*)0);
3613 else
3614 Result.getArrayFiller() =
3615 APValue(APValue::UninitStruct(), RD->getNumBases(),
3616 std::distance(RD->field_begin(), RD->field_end()));
3617 return true;
3618 }
3619
Richard Smithe24f5fc2011-11-17 22:56:20 +00003620 const FunctionDecl *Definition = 0;
3621 FD->getBody(Definition);
3622
Richard Smithc1c5f272011-12-13 06:39:58 +00003623 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3624 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003625
3626 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3627 // but sometimes does:
3628 // struct S { constexpr S() : p(&p) {} void *p; };
3629 // S s[10];
3630 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003631 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003632
Richard Smithec789162012-01-12 18:54:33 +00003633 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003634 ImplicitValueInitExpr VIE(CAT->getElementType());
3635 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3636 &VIE))
3637 return false;
3638 }
3639
Richard Smithe24f5fc2011-11-17 22:56:20 +00003640 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003641 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003642 cast<CXXConstructorDecl>(Definition),
3643 Info, Result.getArrayFiller());
3644}
3645
Richard Smithcc5d4f62011-11-07 09:22:26 +00003646//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003647// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003648//
3649// As a GNU extension, we support casting pointers to sufficiently-wide integer
3650// types and back in constant folding. Integer values are thus represented
3651// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003652//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003653
3654namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003655class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003656 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003657 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003658public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003659 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003660 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003661
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003662 bool Success(const llvm::APSInt &SI, const Expr *E) {
3663 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003664 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003665 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003666 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003667 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003668 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003669 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003670 return true;
3671 }
3672
Daniel Dunbar131eb432009-02-19 09:06:44 +00003673 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003674 assert(E->getType()->isIntegralOrEnumerationType() &&
3675 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003676 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003677 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003678 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003679 Result.getInt().setIsUnsigned(
3680 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003681 return true;
3682 }
3683
3684 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003685 assert(E->getType()->isIntegralOrEnumerationType() &&
3686 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003687 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003688 return true;
3689 }
3690
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003691 bool Success(CharUnits Size, const Expr *E) {
3692 return Success(Size.getQuantity(), E);
3693 }
3694
Richard Smith47a1eed2011-10-29 20:57:55 +00003695 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003696 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003697 Result = V;
3698 return true;
3699 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003700 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003701 }
Mike Stump1eb44332009-09-09 15:08:12 +00003702
Richard Smith51201882011-12-30 21:15:51 +00003703 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003704
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003705 //===--------------------------------------------------------------------===//
3706 // Visitor Methods
3707 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003708
Chris Lattner4c4867e2008-07-12 00:38:25 +00003709 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003710 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003711 }
3712 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003713 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003714 }
Eli Friedman04309752009-11-24 05:28:59 +00003715
3716 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3717 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003718 if (CheckReferencedDecl(E, E->getDecl()))
3719 return true;
3720
3721 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003722 }
3723 bool VisitMemberExpr(const MemberExpr *E) {
3724 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003725 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003726 return true;
3727 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003728
3729 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003730 }
3731
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003732 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003733 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003734 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003735 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003736
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003737 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003738 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003739
Anders Carlsson3068d112008-11-16 19:01:22 +00003740 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003741 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003742 }
Mike Stump1eb44332009-09-09 15:08:12 +00003743
Richard Smithf10d9172011-10-11 21:43:33 +00003744 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003745 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003746 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003747 }
3748
Sebastian Redl64b45f72009-01-05 20:52:13 +00003749 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003750 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003751 }
3752
Francois Pichet6ad6f282010-12-07 00:08:36 +00003753 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3754 return Success(E->getValue(), E);
3755 }
3756
John Wiegley21ff2e52011-04-28 00:16:57 +00003757 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3758 return Success(E->getValue(), E);
3759 }
3760
John Wiegley55262202011-04-25 06:54:41 +00003761 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3762 return Success(E->getValue(), E);
3763 }
3764
Eli Friedman722c7172009-02-28 03:59:05 +00003765 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003766 bool VisitUnaryImag(const UnaryOperator *E);
3767
Sebastian Redl295995c2010-09-10 20:55:47 +00003768 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003769 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003770
Chris Lattnerfcee0012008-07-11 21:24:13 +00003771private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003772 CharUnits GetAlignOfExpr(const Expr *E);
3773 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003774 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003775 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003776 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003777};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003778} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003779
Richard Smithc49bd112011-10-28 17:51:58 +00003780/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3781/// produce either the integer value or a pointer.
3782///
3783/// GCC has a heinous extension which folds casts between pointer types and
3784/// pointer-sized integral types. We support this by allowing the evaluation of
3785/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3786/// Some simple arithmetic on such values is supported (they are treated much
3787/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003788static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003789 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003790 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003791 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003792}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003793
Richard Smithf48fdb02011-12-09 22:58:01 +00003794static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003795 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003796 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003797 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003798 if (!Val.isInt()) {
3799 // FIXME: It would be better to produce the diagnostic for casting
3800 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003801 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003802 return false;
3803 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003804 Result = Val.getInt();
3805 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003806}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003807
Richard Smithf48fdb02011-12-09 22:58:01 +00003808/// Check whether the given declaration can be directly converted to an integral
3809/// rvalue. If not, no diagnostic is produced; there are other things we can
3810/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003811bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003812 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003813 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003814 // Check for signedness/width mismatches between E type and ECD value.
3815 bool SameSign = (ECD->getInitVal().isSigned()
3816 == E->getType()->isSignedIntegerOrEnumerationType());
3817 bool SameWidth = (ECD->getInitVal().getBitWidth()
3818 == Info.Ctx.getIntWidth(E->getType()));
3819 if (SameSign && SameWidth)
3820 return Success(ECD->getInitVal(), E);
3821 else {
3822 // Get rid of mismatch (otherwise Success assertions will fail)
3823 // by computing a new value matching the type of E.
3824 llvm::APSInt Val = ECD->getInitVal();
3825 if (!SameSign)
3826 Val.setIsSigned(!ECD->getInitVal().isSigned());
3827 if (!SameWidth)
3828 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3829 return Success(Val, E);
3830 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003831 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003832 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003833}
3834
Chris Lattnera4d55d82008-10-06 06:40:35 +00003835/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3836/// as GCC.
3837static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3838 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003839 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003840 enum gcc_type_class {
3841 no_type_class = -1,
3842 void_type_class, integer_type_class, char_type_class,
3843 enumeral_type_class, boolean_type_class,
3844 pointer_type_class, reference_type_class, offset_type_class,
3845 real_type_class, complex_type_class,
3846 function_type_class, method_type_class,
3847 record_type_class, union_type_class,
3848 array_type_class, string_type_class,
3849 lang_type_class
3850 };
Mike Stump1eb44332009-09-09 15:08:12 +00003851
3852 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003853 // ideal, however it is what gcc does.
3854 if (E->getNumArgs() == 0)
3855 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003856
Chris Lattnera4d55d82008-10-06 06:40:35 +00003857 QualType ArgTy = E->getArg(0)->getType();
3858 if (ArgTy->isVoidType())
3859 return void_type_class;
3860 else if (ArgTy->isEnumeralType())
3861 return enumeral_type_class;
3862 else if (ArgTy->isBooleanType())
3863 return boolean_type_class;
3864 else if (ArgTy->isCharType())
3865 return string_type_class; // gcc doesn't appear to use char_type_class
3866 else if (ArgTy->isIntegerType())
3867 return integer_type_class;
3868 else if (ArgTy->isPointerType())
3869 return pointer_type_class;
3870 else if (ArgTy->isReferenceType())
3871 return reference_type_class;
3872 else if (ArgTy->isRealType())
3873 return real_type_class;
3874 else if (ArgTy->isComplexType())
3875 return complex_type_class;
3876 else if (ArgTy->isFunctionType())
3877 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003878 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003879 return record_type_class;
3880 else if (ArgTy->isUnionType())
3881 return union_type_class;
3882 else if (ArgTy->isArrayType())
3883 return array_type_class;
3884 else if (ArgTy->isUnionType())
3885 return union_type_class;
3886 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003887 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003888}
3889
Richard Smith80d4b552011-12-28 19:48:30 +00003890/// EvaluateBuiltinConstantPForLValue - Determine the result of
3891/// __builtin_constant_p when applied to the given lvalue.
3892///
3893/// An lvalue is only "constant" if it is a pointer or reference to the first
3894/// character of a string literal.
3895template<typename LValue>
3896static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3897 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3898 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3899}
3900
3901/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3902/// GCC as we can manage.
3903static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3904 QualType ArgType = Arg->getType();
3905
3906 // __builtin_constant_p always has one operand. The rules which gcc follows
3907 // are not precisely documented, but are as follows:
3908 //
3909 // - If the operand is of integral, floating, complex or enumeration type,
3910 // and can be folded to a known value of that type, it returns 1.
3911 // - If the operand and can be folded to a pointer to the first character
3912 // of a string literal (or such a pointer cast to an integral type), it
3913 // returns 1.
3914 //
3915 // Otherwise, it returns 0.
3916 //
3917 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3918 // its support for this does not currently work.
3919 if (ArgType->isIntegralOrEnumerationType()) {
3920 Expr::EvalResult Result;
3921 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3922 return false;
3923
3924 APValue &V = Result.Val;
3925 if (V.getKind() == APValue::Int)
3926 return true;
3927
3928 return EvaluateBuiltinConstantPForLValue(V);
3929 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3930 return Arg->isEvaluatable(Ctx);
3931 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3932 LValue LV;
3933 Expr::EvalStatus Status;
3934 EvalInfo Info(Ctx, Status);
3935 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3936 : EvaluatePointer(Arg, LV, Info)) &&
3937 !Status.HasSideEffects)
3938 return EvaluateBuiltinConstantPForLValue(LV);
3939 }
3940
3941 // Anything else isn't considered to be sufficiently constant.
3942 return false;
3943}
3944
John McCall42c8f872010-05-10 23:27:23 +00003945/// Retrieves the "underlying object type" of the given expression,
3946/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003947QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3948 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3949 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003950 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003951 } else if (const Expr *E = B.get<const Expr*>()) {
3952 if (isa<CompoundLiteralExpr>(E))
3953 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003954 }
3955
3956 return QualType();
3957}
3958
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003959bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003960 // TODO: Perhaps we should let LLVM lower this?
3961 LValue Base;
3962 if (!EvaluatePointer(E->getArg(0), Base, Info))
3963 return false;
3964
3965 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003966 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003967
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003968 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003969 if (T.isNull() ||
3970 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00003971 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00003972 T->isVariablyModifiedType() ||
3973 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003974 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00003975
3976 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3977 CharUnits Offset = Base.getLValueOffset();
3978
3979 if (!Offset.isNegative() && Offset <= Size)
3980 Size -= Offset;
3981 else
3982 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003983 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00003984}
3985
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003986bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003987 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00003988 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003989 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003990
3991 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00003992 if (TryEvaluateBuiltinObjectSize(E))
3993 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00003994
Eric Christopherb2aaf512010-01-19 22:58:35 +00003995 // If evaluating the argument has side-effects we can't determine
3996 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00003997 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003998 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00003999 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004000 return Success(0, E);
4001 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004002
Richard Smithf48fdb02011-12-09 22:58:01 +00004003 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004004 }
4005
Chris Lattner019f4e82008-10-06 05:28:25 +00004006 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004007 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004008
Richard Smith80d4b552011-12-28 19:48:30 +00004009 case Builtin::BI__builtin_constant_p:
4010 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004011
Chris Lattner21fb98e2009-09-23 06:06:36 +00004012 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004013 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004014 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004015 return Success(Operand, E);
4016 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004017
4018 case Builtin::BI__builtin_expect:
4019 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004020
Douglas Gregor5726d402010-09-10 06:27:15 +00004021 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004022 // A call to strlen is not a constant expression.
4023 if (Info.getLangOpts().CPlusPlus0x)
4024 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4025 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4026 else
4027 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4028 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004029 case Builtin::BI__builtin_strlen:
4030 // As an extension, we support strlen() and __builtin_strlen() as constant
4031 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004032 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004033 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4034 // The string literal may have embedded null characters. Find the first
4035 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004036 StringRef Str = S->getString();
4037 StringRef::size_type Pos = Str.find(0);
4038 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004039 Str = Str.substr(0, Pos);
4040
4041 return Success(Str.size(), E);
4042 }
4043
Richard Smithf48fdb02011-12-09 22:58:01 +00004044 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004045
4046 case Builtin::BI__atomic_is_lock_free: {
4047 APSInt SizeVal;
4048 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4049 return false;
4050
4051 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4052 // of two less than the maximum inline atomic width, we know it is
4053 // lock-free. If the size isn't a power of two, or greater than the
4054 // maximum alignment where we promote atomics, we know it is not lock-free
4055 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4056 // the answer can only be determined at runtime; for example, 16-byte
4057 // atomics have lock-free implementations on some, but not all,
4058 // x86-64 processors.
4059
4060 // Check power-of-two.
4061 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4062 if (!Size.isPowerOfTwo())
4063#if 0
4064 // FIXME: Suppress this folding until the ABI for the promotion width
4065 // settles.
4066 return Success(0, E);
4067#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004068 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004069#endif
4070
4071#if 0
4072 // Check against promotion width.
4073 // FIXME: Suppress this folding until the ABI for the promotion width
4074 // settles.
4075 unsigned PromoteWidthBits =
4076 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4077 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4078 return Success(0, E);
4079#endif
4080
4081 // Check against inlining width.
4082 unsigned InlineWidthBits =
4083 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4084 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4085 return Success(1, E);
4086
Richard Smithf48fdb02011-12-09 22:58:01 +00004087 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004088 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004089 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004090}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004091
Richard Smith625b8072011-10-31 01:37:14 +00004092static bool HasSameBase(const LValue &A, const LValue &B) {
4093 if (!A.getLValueBase())
4094 return !B.getLValueBase();
4095 if (!B.getLValueBase())
4096 return false;
4097
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004098 if (A.getLValueBase().getOpaqueValue() !=
4099 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004100 const Decl *ADecl = GetLValueBaseDecl(A);
4101 if (!ADecl)
4102 return false;
4103 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004104 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004105 return false;
4106 }
4107
4108 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00004109 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00004110}
4111
Chris Lattnerb542afe2008-07-11 19:10:17 +00004112bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004113 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004114 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004115
John McCall2de56d12010-08-25 11:45:40 +00004116 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004117 VisitIgnoredValue(E->getLHS());
4118 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004119 }
4120
4121 if (E->isLogicalOp()) {
4122 // These need to be handled specially because the operands aren't
4123 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004124 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004125
Richard Smithc49bd112011-10-28 17:51:58 +00004126 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004127 // We were able to evaluate the LHS, see if we can get away with not
4128 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004129 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004130 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004131
Richard Smithc49bd112011-10-28 17:51:58 +00004132 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004133 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004134 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004135 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004136 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004137 }
4138 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004139 // FIXME: If both evaluations fail, we should produce the diagnostic from
4140 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4141 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00004142 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004143 // We can't evaluate the LHS; however, sometimes the result
4144 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00004145 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004146 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004147 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00004148 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004149
4150 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004151 }
4152 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004153 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004154
Eli Friedmana6afa762008-11-13 06:09:17 +00004155 return false;
4156 }
4157
Anders Carlsson286f85e2008-11-16 07:17:21 +00004158 QualType LHSTy = E->getLHS()->getType();
4159 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004160
4161 if (LHSTy->isAnyComplexType()) {
4162 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004163 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004164
Richard Smith745f5142012-01-27 01:14:48 +00004165 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4166 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004167 return false;
4168
Richard Smith745f5142012-01-27 01:14:48 +00004169 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004170 return false;
4171
4172 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004173 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004174 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004175 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004176 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4177
John McCall2de56d12010-08-25 11:45:40 +00004178 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004179 return Success((CR_r == APFloat::cmpEqual &&
4180 CR_i == APFloat::cmpEqual), E);
4181 else {
John McCall2de56d12010-08-25 11:45:40 +00004182 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004183 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004184 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004185 CR_r == APFloat::cmpLessThan ||
4186 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004187 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004188 CR_i == APFloat::cmpLessThan ||
4189 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004190 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004191 } else {
John McCall2de56d12010-08-25 11:45:40 +00004192 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004193 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4194 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4195 else {
John McCall2de56d12010-08-25 11:45:40 +00004196 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004197 "Invalid compex comparison.");
4198 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4199 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4200 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004201 }
4202 }
Mike Stump1eb44332009-09-09 15:08:12 +00004203
Anders Carlsson286f85e2008-11-16 07:17:21 +00004204 if (LHSTy->isRealFloatingType() &&
4205 RHSTy->isRealFloatingType()) {
4206 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004207
Richard Smith745f5142012-01-27 01:14:48 +00004208 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4209 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004210 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004211
Richard Smith745f5142012-01-27 01:14:48 +00004212 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004213 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004214
Anders Carlsson286f85e2008-11-16 07:17:21 +00004215 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004216
Anders Carlsson286f85e2008-11-16 07:17:21 +00004217 switch (E->getOpcode()) {
4218 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004219 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004220 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004221 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004222 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004223 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004224 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004225 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004226 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004227 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004228 E);
John McCall2de56d12010-08-25 11:45:40 +00004229 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004230 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004231 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004232 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004233 || CR == APFloat::cmpLessThan
4234 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004235 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004236 }
Mike Stump1eb44332009-09-09 15:08:12 +00004237
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004238 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004239 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004240 LValue LHSValue, RHSValue;
4241
4242 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4243 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004244 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004245
Richard Smith745f5142012-01-27 01:14:48 +00004246 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004247 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004248
Richard Smith625b8072011-10-31 01:37:14 +00004249 // Reject differing bases from the normal codepath; we special-case
4250 // comparisons to null.
4251 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004252 if (E->getOpcode() == BO_Sub) {
4253 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004254 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4255 return false;
4256 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4257 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4258 if (!LHSExpr || !RHSExpr)
4259 return false;
4260 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4261 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4262 if (!LHSAddrExpr || !RHSAddrExpr)
4263 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004264 // Make sure both labels come from the same function.
4265 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4266 RHSAddrExpr->getLabel()->getDeclContext())
4267 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004268 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4269 return true;
4270 }
Richard Smith9e36b532011-10-31 05:11:32 +00004271 // Inequalities and subtractions between unrelated pointers have
4272 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004273 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004274 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004275 // A constant address may compare equal to the address of a symbol.
4276 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004277 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004278 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4279 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004280 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004281 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00004282 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00004283 // distinct. However, we do know that the address of a literal will be
4284 // non-null.
4285 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4286 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004287 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004288 // We can't tell whether weak symbols will end up pointing to the same
4289 // object.
4290 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004291 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004292 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004293 // (Note that clang defaults to -fmerge-all-constants, which can
4294 // lead to inconsistent results for comparisons involving the address
4295 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004296 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004297 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004298
Richard Smithcc5d4f62011-11-07 09:22:26 +00004299 // FIXME: Implement the C++11 restrictions:
4300 // - Pointer subtractions must be on elements of the same array.
4301 // - Pointer comparisons must be between members with the same access.
4302
John McCall2de56d12010-08-25 11:45:40 +00004303 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00004304 QualType Type = E->getLHS()->getType();
4305 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004306
Richard Smith180f4792011-11-10 06:34:14 +00004307 CharUnits ElementSize;
4308 if (!HandleSizeof(Info, ElementType, ElementSize))
4309 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004310
Richard Smith180f4792011-11-10 06:34:14 +00004311 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00004312 RHSValue.getLValueOffset();
4313 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004314 }
Richard Smith625b8072011-10-31 01:37:14 +00004315
4316 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4317 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4318 switch (E->getOpcode()) {
4319 default: llvm_unreachable("missing comparison operator");
4320 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4321 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4322 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4323 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4324 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4325 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004326 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004327 }
4328 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004329 if (!LHSTy->isIntegralOrEnumerationType() ||
4330 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004331 // We can't continue from here for non-integral types.
4332 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004333 }
4334
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004335 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004336 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004337
4338 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4339 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004340 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004341
Richard Smith745f5142012-01-27 01:14:48 +00004342 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004343 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004344
Richard Smith47a1eed2011-10-29 20:57:55 +00004345 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004346
4347 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004348 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004349 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4350 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004351 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004352 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004353 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004354 LHSVal.getLValueOffset() -= AdditionalOffset;
4355 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004356 return true;
4357 }
4358
4359 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004360 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004361 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004362 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4363 LHSVal.getInt().getZExtValue());
4364 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004365 return true;
4366 }
4367
Eli Friedman65639282012-01-04 23:13:47 +00004368 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4369 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004370 if (!LHSVal.getLValueOffset().isZero() ||
4371 !RHSVal.getLValueOffset().isZero())
4372 return false;
4373 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4374 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4375 if (!LHSExpr || !RHSExpr)
4376 return false;
4377 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4378 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4379 if (!LHSAddrExpr || !RHSAddrExpr)
4380 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004381 // Make sure both labels come from the same function.
4382 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4383 RHSAddrExpr->getLabel()->getDeclContext())
4384 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004385 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4386 return true;
4387 }
4388
Eli Friedman42edd0d2009-03-24 01:14:50 +00004389 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004390 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004391 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004392
Richard Smithc49bd112011-10-28 17:51:58 +00004393 APSInt &LHS = LHSVal.getInt();
4394 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004395
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004396 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004397 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004398 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004399 case BO_Mul: return Success(LHS * RHS, E);
4400 case BO_Add: return Success(LHS + RHS, E);
4401 case BO_Sub: return Success(LHS - RHS, E);
4402 case BO_And: return Success(LHS & RHS, E);
4403 case BO_Xor: return Success(LHS ^ RHS, E);
4404 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004405 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00004406 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004407 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00004408 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004409 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004410 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004411 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00004412 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004413 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00004414 // During constant-folding, a negative shift is an opposite shift.
4415 if (RHS.isSigned() && RHS.isNegative()) {
4416 RHS = -RHS;
4417 goto shift_right;
4418 }
4419
4420 shift_left:
4421 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00004422 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4423 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004424 }
John McCall2de56d12010-08-25 11:45:40 +00004425 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00004426 // During constant-folding, a negative shift is an opposite shift.
4427 if (RHS.isSigned() && RHS.isNegative()) {
4428 RHS = -RHS;
4429 goto shift_left;
4430 }
4431
4432 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00004433 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00004434 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4435 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004436 }
Mike Stump1eb44332009-09-09 15:08:12 +00004437
Richard Smithc49bd112011-10-28 17:51:58 +00004438 case BO_LT: return Success(LHS < RHS, E);
4439 case BO_GT: return Success(LHS > RHS, E);
4440 case BO_LE: return Success(LHS <= RHS, E);
4441 case BO_GE: return Success(LHS >= RHS, E);
4442 case BO_EQ: return Success(LHS == RHS, E);
4443 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004444 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004445}
4446
Ken Dyck8b752f12010-01-27 17:10:57 +00004447CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004448 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4449 // the result is the size of the referenced type."
4450 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4451 // result shall be the alignment of the referenced type."
4452 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4453 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004454
4455 // __alignof is defined to return the preferred alignment.
4456 return Info.Ctx.toCharUnitsFromBits(
4457 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004458}
4459
Ken Dyck8b752f12010-01-27 17:10:57 +00004460CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004461 E = E->IgnoreParens();
4462
4463 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004464 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004465 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004466 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4467 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004468
Chris Lattneraf707ab2009-01-24 21:53:27 +00004469 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004470 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4471 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004472
Chris Lattnere9feb472009-01-24 21:09:06 +00004473 return GetAlignOfType(E->getType());
4474}
4475
4476
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004477/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4478/// a result as the expression's type.
4479bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4480 const UnaryExprOrTypeTraitExpr *E) {
4481 switch(E->getKind()) {
4482 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004483 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004484 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004485 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004486 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004487 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004488
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004489 case UETT_VecStep: {
4490 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004491
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004492 if (Ty->isVectorType()) {
4493 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004494
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004495 // The vec_step built-in functions that take a 3-component
4496 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4497 if (n == 3)
4498 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004499
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004500 return Success(n, E);
4501 } else
4502 return Success(1, E);
4503 }
4504
4505 case UETT_SizeOf: {
4506 QualType SrcTy = E->getTypeOfArgument();
4507 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4508 // the result is the size of the referenced type."
4509 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4510 // result shall be the alignment of the referenced type."
4511 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4512 SrcTy = Ref->getPointeeType();
4513
Richard Smith180f4792011-11-10 06:34:14 +00004514 CharUnits Sizeof;
4515 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004516 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004517 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004518 }
4519 }
4520
4521 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004522}
4523
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004524bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004525 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004526 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004527 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004528 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004529 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004530 for (unsigned i = 0; i != n; ++i) {
4531 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4532 switch (ON.getKind()) {
4533 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004534 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004535 APSInt IdxResult;
4536 if (!EvaluateInteger(Idx, IdxResult, Info))
4537 return false;
4538 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4539 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004540 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004541 CurrentType = AT->getElementType();
4542 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4543 Result += IdxResult.getSExtValue() * ElementSize;
4544 break;
4545 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004546
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004547 case OffsetOfExpr::OffsetOfNode::Field: {
4548 FieldDecl *MemberDecl = ON.getField();
4549 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004550 if (!RT)
4551 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004552 RecordDecl *RD = RT->getDecl();
4553 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004554 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004555 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004556 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004557 CurrentType = MemberDecl->getType().getNonReferenceType();
4558 break;
4559 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004560
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004561 case OffsetOfExpr::OffsetOfNode::Identifier:
4562 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004563
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004564 case OffsetOfExpr::OffsetOfNode::Base: {
4565 CXXBaseSpecifier *BaseSpec = ON.getBase();
4566 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004567 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004568
4569 // Find the layout of the class whose base we are looking into.
4570 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004571 if (!RT)
4572 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004573 RecordDecl *RD = RT->getDecl();
4574 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4575
4576 // Find the base class itself.
4577 CurrentType = BaseSpec->getType();
4578 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4579 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004580 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004581
4582 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004583 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004584 break;
4585 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004586 }
4587 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004588 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004589}
4590
Chris Lattnerb542afe2008-07-11 19:10:17 +00004591bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004592 switch (E->getOpcode()) {
4593 default:
4594 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4595 // See C99 6.6p3.
4596 return Error(E);
4597 case UO_Extension:
4598 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4599 // If so, we could clear the diagnostic ID.
4600 return Visit(E->getSubExpr());
4601 case UO_Plus:
4602 // The result is just the value.
4603 return Visit(E->getSubExpr());
4604 case UO_Minus: {
4605 if (!Visit(E->getSubExpr()))
4606 return false;
4607 if (!Result.isInt()) return Error(E);
4608 return Success(-Result.getInt(), E);
4609 }
4610 case UO_Not: {
4611 if (!Visit(E->getSubExpr()))
4612 return false;
4613 if (!Result.isInt()) return Error(E);
4614 return Success(~Result.getInt(), E);
4615 }
4616 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004617 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004618 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004619 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004620 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004621 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004622 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004623}
Mike Stump1eb44332009-09-09 15:08:12 +00004624
Chris Lattner732b2232008-07-12 01:15:53 +00004625/// HandleCast - This is used to evaluate implicit or explicit casts where the
4626/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004627bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4628 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004629 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004630 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004631
Eli Friedman46a52322011-03-25 00:43:55 +00004632 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004633 case CK_BaseToDerived:
4634 case CK_DerivedToBase:
4635 case CK_UncheckedDerivedToBase:
4636 case CK_Dynamic:
4637 case CK_ToUnion:
4638 case CK_ArrayToPointerDecay:
4639 case CK_FunctionToPointerDecay:
4640 case CK_NullToPointer:
4641 case CK_NullToMemberPointer:
4642 case CK_BaseToDerivedMemberPointer:
4643 case CK_DerivedToBaseMemberPointer:
4644 case CK_ConstructorConversion:
4645 case CK_IntegralToPointer:
4646 case CK_ToVoid:
4647 case CK_VectorSplat:
4648 case CK_IntegralToFloating:
4649 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004650 case CK_CPointerToObjCPointerCast:
4651 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004652 case CK_AnyPointerToBlockPointerCast:
4653 case CK_ObjCObjectLValueCast:
4654 case CK_FloatingRealToComplex:
4655 case CK_FloatingComplexToReal:
4656 case CK_FloatingComplexCast:
4657 case CK_FloatingComplexToIntegralComplex:
4658 case CK_IntegralRealToComplex:
4659 case CK_IntegralComplexCast:
4660 case CK_IntegralComplexToFloatingComplex:
4661 llvm_unreachable("invalid cast kind for integral value");
4662
Eli Friedmane50c2972011-03-25 19:07:11 +00004663 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004664 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004665 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00004666 case CK_ARCProduceObject:
4667 case CK_ARCConsumeObject:
4668 case CK_ARCReclaimReturnedObject:
4669 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004670 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004671
Richard Smith7d580a42012-01-17 21:17:26 +00004672 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00004673 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00004674 case CK_AtomicToNonAtomic:
4675 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00004676 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004677 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004678
4679 case CK_MemberPointerToBoolean:
4680 case CK_PointerToBoolean:
4681 case CK_IntegralToBoolean:
4682 case CK_FloatingToBoolean:
4683 case CK_FloatingComplexToBoolean:
4684 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004685 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004686 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004687 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004688 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004689 }
4690
Eli Friedman46a52322011-03-25 00:43:55 +00004691 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004692 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004693 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004694
Eli Friedmanbe265702009-02-20 01:15:07 +00004695 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00004696 // Allow casts of address-of-label differences if they are no-ops
4697 // or narrowing. (The narrowing case isn't actually guaranteed to
4698 // be constant-evaluatable except in some narrow cases which are hard
4699 // to detect here. We let it through on the assumption the user knows
4700 // what they are doing.)
4701 if (Result.isAddrLabelDiff())
4702 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00004703 // Only allow casts of lvalues if they are lossless.
4704 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4705 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004706
Richard Smithf72fccf2012-01-30 22:27:01 +00004707 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
4708 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00004709 }
Mike Stump1eb44332009-09-09 15:08:12 +00004710
Eli Friedman46a52322011-03-25 00:43:55 +00004711 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00004712 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4713
John McCallefdb83e2010-05-07 21:00:08 +00004714 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00004715 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004716 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00004717
Daniel Dunbardd211642009-02-19 22:24:01 +00004718 if (LV.getLValueBase()) {
4719 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00004720 // FIXME: Allow a larger integer size than the pointer size, and allow
4721 // narrowing back down to pointer width in subsequent integral casts.
4722 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00004723 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00004724 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004725
Richard Smithb755a9d2011-11-16 07:18:12 +00004726 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004727 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00004728 return true;
4729 }
4730
Ken Dycka7305832010-01-15 12:37:54 +00004731 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4732 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00004733 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00004734 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004735
Eli Friedman46a52322011-03-25 00:43:55 +00004736 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00004737 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00004738 if (!EvaluateComplex(SubExpr, C, Info))
4739 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00004740 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00004741 }
Eli Friedman2217c872009-02-22 11:46:18 +00004742
Eli Friedman46a52322011-03-25 00:43:55 +00004743 case CK_FloatingToIntegral: {
4744 APFloat F(0.0);
4745 if (!EvaluateFloat(SubExpr, F, Info))
4746 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00004747
Richard Smithc1c5f272011-12-13 06:39:58 +00004748 APSInt Value;
4749 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4750 return false;
4751 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00004752 }
4753 }
Mike Stump1eb44332009-09-09 15:08:12 +00004754
Eli Friedman46a52322011-03-25 00:43:55 +00004755 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004756}
Anders Carlsson2bad1682008-07-08 14:30:00 +00004757
Eli Friedman722c7172009-02-28 03:59:05 +00004758bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4759 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004760 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004761 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4762 return false;
4763 if (!LV.isComplexInt())
4764 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004765 return Success(LV.getComplexIntReal(), E);
4766 }
4767
4768 return Visit(E->getSubExpr());
4769}
4770
Eli Friedman664a1042009-02-27 04:45:43 +00004771bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004772 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004773 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004774 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4775 return false;
4776 if (!LV.isComplexInt())
4777 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004778 return Success(LV.getComplexIntImag(), E);
4779 }
4780
Richard Smith8327fad2011-10-24 18:44:57 +00004781 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004782 return Success(0, E);
4783}
4784
Douglas Gregoree8aff02011-01-04 17:33:58 +00004785bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4786 return Success(E->getPackLength(), E);
4787}
4788
Sebastian Redl295995c2010-09-10 20:55:47 +00004789bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4790 return Success(E->getValue(), E);
4791}
4792
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004793//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004794// Float Evaluation
4795//===----------------------------------------------------------------------===//
4796
4797namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004798class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004799 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004800 APFloat &Result;
4801public:
4802 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004803 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004804
Richard Smith47a1eed2011-10-29 20:57:55 +00004805 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004806 Result = V.getFloat();
4807 return true;
4808 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004809
Richard Smith51201882011-12-30 21:15:51 +00004810 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00004811 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4812 return true;
4813 }
4814
Chris Lattner019f4e82008-10-06 05:28:25 +00004815 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004816
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004817 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004818 bool VisitBinaryOperator(const BinaryOperator *E);
4819 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004820 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004821
John McCallabd3a852010-05-07 22:08:54 +00004822 bool VisitUnaryReal(const UnaryOperator *E);
4823 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004824
Richard Smith51201882011-12-30 21:15:51 +00004825 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004826};
4827} // end anonymous namespace
4828
4829static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004830 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004831 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004832}
4833
Jay Foad4ba2a172011-01-12 09:06:06 +00004834static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004835 QualType ResultTy,
4836 const Expr *Arg,
4837 bool SNaN,
4838 llvm::APFloat &Result) {
4839 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4840 if (!S) return false;
4841
4842 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4843
4844 llvm::APInt fill;
4845
4846 // Treat empty strings as if they were zero.
4847 if (S->getString().empty())
4848 fill = llvm::APInt(32, 0);
4849 else if (S->getString().getAsInteger(0, fill))
4850 return false;
4851
4852 if (SNaN)
4853 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4854 else
4855 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4856 return true;
4857}
4858
Chris Lattner019f4e82008-10-06 05:28:25 +00004859bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004860 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004861 default:
4862 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4863
Chris Lattner019f4e82008-10-06 05:28:25 +00004864 case Builtin::BI__builtin_huge_val:
4865 case Builtin::BI__builtin_huge_valf:
4866 case Builtin::BI__builtin_huge_vall:
4867 case Builtin::BI__builtin_inf:
4868 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004869 case Builtin::BI__builtin_infl: {
4870 const llvm::fltSemantics &Sem =
4871 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00004872 Result = llvm::APFloat::getInf(Sem);
4873 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004874 }
Mike Stump1eb44332009-09-09 15:08:12 +00004875
John McCalldb7b72a2010-02-28 13:00:19 +00004876 case Builtin::BI__builtin_nans:
4877 case Builtin::BI__builtin_nansf:
4878 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00004879 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4880 true, Result))
4881 return Error(E);
4882 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00004883
Chris Lattner9e621712008-10-06 06:31:58 +00004884 case Builtin::BI__builtin_nan:
4885 case Builtin::BI__builtin_nanf:
4886 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00004887 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00004888 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00004889 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4890 false, Result))
4891 return Error(E);
4892 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004893
4894 case Builtin::BI__builtin_fabs:
4895 case Builtin::BI__builtin_fabsf:
4896 case Builtin::BI__builtin_fabsl:
4897 if (!EvaluateFloat(E->getArg(0), Result, Info))
4898 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004899
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004900 if (Result.isNegative())
4901 Result.changeSign();
4902 return true;
4903
Mike Stump1eb44332009-09-09 15:08:12 +00004904 case Builtin::BI__builtin_copysign:
4905 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004906 case Builtin::BI__builtin_copysignl: {
4907 APFloat RHS(0.);
4908 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4909 !EvaluateFloat(E->getArg(1), RHS, Info))
4910 return false;
4911 Result.copySign(RHS);
4912 return true;
4913 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004914 }
4915}
4916
John McCallabd3a852010-05-07 22:08:54 +00004917bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004918 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4919 ComplexValue CV;
4920 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4921 return false;
4922 Result = CV.FloatReal;
4923 return true;
4924 }
4925
4926 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00004927}
4928
4929bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004930 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4931 ComplexValue CV;
4932 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4933 return false;
4934 Result = CV.FloatImag;
4935 return true;
4936 }
4937
Richard Smith8327fad2011-10-24 18:44:57 +00004938 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00004939 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4940 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00004941 return true;
4942}
4943
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004944bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004945 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004946 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004947 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004948 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00004949 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004950 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4951 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004952 Result.changeSign();
4953 return true;
4954 }
4955}
Chris Lattner019f4e82008-10-06 05:28:25 +00004956
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004957bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004958 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4959 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00004960
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004961 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00004962 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
4963 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004964 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004965 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004966 return false;
4967
4968 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004969 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004970 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004971 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4972 return true;
John McCall2de56d12010-08-25 11:45:40 +00004973 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004974 Result.add(RHS, APFloat::rmNearestTiesToEven);
4975 return true;
John McCall2de56d12010-08-25 11:45:40 +00004976 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004977 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4978 return true;
John McCall2de56d12010-08-25 11:45:40 +00004979 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004980 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4981 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004982 }
4983}
4984
4985bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4986 Result = E->getValue();
4987 return true;
4988}
4989
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004990bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4991 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00004992
Eli Friedman2a523ee2011-03-25 00:54:52 +00004993 switch (E->getCastKind()) {
4994 default:
Richard Smithc49bd112011-10-28 17:51:58 +00004995 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00004996
4997 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004998 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00004999 return EvaluateInteger(SubExpr, IntResult, Info) &&
5000 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5001 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005002 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005003
5004 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005005 if (!Visit(SubExpr))
5006 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005007 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5008 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005009 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005010
Eli Friedman2a523ee2011-03-25 00:54:52 +00005011 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005012 ComplexValue V;
5013 if (!EvaluateComplex(SubExpr, V, Info))
5014 return false;
5015 Result = V.getComplexFloatReal();
5016 return true;
5017 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005018 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005019}
5020
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005021//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005022// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005023//===----------------------------------------------------------------------===//
5024
5025namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005026class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005027 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005028 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005029
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005030public:
John McCallf4cf1a12010-05-07 17:22:02 +00005031 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005032 : ExprEvaluatorBaseTy(info), Result(Result) {}
5033
Richard Smith47a1eed2011-10-29 20:57:55 +00005034 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005035 Result.setFrom(V);
5036 return true;
5037 }
Mike Stump1eb44332009-09-09 15:08:12 +00005038
Eli Friedman7ead5c72012-01-10 04:58:17 +00005039 bool ZeroInitialization(const Expr *E);
5040
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005041 //===--------------------------------------------------------------------===//
5042 // Visitor Methods
5043 //===--------------------------------------------------------------------===//
5044
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005045 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005046 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005047 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005048 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005049 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005050};
5051} // end anonymous namespace
5052
John McCallf4cf1a12010-05-07 17:22:02 +00005053static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5054 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005055 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005056 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005057}
5058
Eli Friedman7ead5c72012-01-10 04:58:17 +00005059bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005060 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005061 if (ElemTy->isRealFloatingType()) {
5062 Result.makeComplexFloat();
5063 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5064 Result.FloatReal = Zero;
5065 Result.FloatImag = Zero;
5066 } else {
5067 Result.makeComplexInt();
5068 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5069 Result.IntReal = Zero;
5070 Result.IntImag = Zero;
5071 }
5072 return true;
5073}
5074
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005075bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5076 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005077
5078 if (SubExpr->getType()->isRealFloatingType()) {
5079 Result.makeComplexFloat();
5080 APFloat &Imag = Result.FloatImag;
5081 if (!EvaluateFloat(SubExpr, Imag, Info))
5082 return false;
5083
5084 Result.FloatReal = APFloat(Imag.getSemantics());
5085 return true;
5086 } else {
5087 assert(SubExpr->getType()->isIntegerType() &&
5088 "Unexpected imaginary literal.");
5089
5090 Result.makeComplexInt();
5091 APSInt &Imag = Result.IntImag;
5092 if (!EvaluateInteger(SubExpr, Imag, Info))
5093 return false;
5094
5095 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5096 return true;
5097 }
5098}
5099
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005100bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005101
John McCall8786da72010-12-14 17:51:41 +00005102 switch (E->getCastKind()) {
5103 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005104 case CK_BaseToDerived:
5105 case CK_DerivedToBase:
5106 case CK_UncheckedDerivedToBase:
5107 case CK_Dynamic:
5108 case CK_ToUnion:
5109 case CK_ArrayToPointerDecay:
5110 case CK_FunctionToPointerDecay:
5111 case CK_NullToPointer:
5112 case CK_NullToMemberPointer:
5113 case CK_BaseToDerivedMemberPointer:
5114 case CK_DerivedToBaseMemberPointer:
5115 case CK_MemberPointerToBoolean:
5116 case CK_ConstructorConversion:
5117 case CK_IntegralToPointer:
5118 case CK_PointerToIntegral:
5119 case CK_PointerToBoolean:
5120 case CK_ToVoid:
5121 case CK_VectorSplat:
5122 case CK_IntegralCast:
5123 case CK_IntegralToBoolean:
5124 case CK_IntegralToFloating:
5125 case CK_FloatingToIntegral:
5126 case CK_FloatingToBoolean:
5127 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005128 case CK_CPointerToObjCPointerCast:
5129 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005130 case CK_AnyPointerToBlockPointerCast:
5131 case CK_ObjCObjectLValueCast:
5132 case CK_FloatingComplexToReal:
5133 case CK_FloatingComplexToBoolean:
5134 case CK_IntegralComplexToReal:
5135 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005136 case CK_ARCProduceObject:
5137 case CK_ARCConsumeObject:
5138 case CK_ARCReclaimReturnedObject:
5139 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005140 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005141
John McCall8786da72010-12-14 17:51:41 +00005142 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005143 case CK_AtomicToNonAtomic:
5144 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005145 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005146 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005147
5148 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005149 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005150 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005151 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005152
5153 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005154 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005155 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005156 return false;
5157
John McCall8786da72010-12-14 17:51:41 +00005158 Result.makeComplexFloat();
5159 Result.FloatImag = APFloat(Real.getSemantics());
5160 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005161 }
5162
John McCall8786da72010-12-14 17:51:41 +00005163 case CK_FloatingComplexCast: {
5164 if (!Visit(E->getSubExpr()))
5165 return false;
5166
5167 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5168 QualType From
5169 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5170
Richard Smithc1c5f272011-12-13 06:39:58 +00005171 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5172 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005173 }
5174
5175 case CK_FloatingComplexToIntegralComplex: {
5176 if (!Visit(E->getSubExpr()))
5177 return false;
5178
5179 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5180 QualType From
5181 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5182 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005183 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5184 To, Result.IntReal) &&
5185 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5186 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005187 }
5188
5189 case CK_IntegralRealToComplex: {
5190 APSInt &Real = Result.IntReal;
5191 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5192 return false;
5193
5194 Result.makeComplexInt();
5195 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5196 return true;
5197 }
5198
5199 case CK_IntegralComplexCast: {
5200 if (!Visit(E->getSubExpr()))
5201 return false;
5202
5203 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5204 QualType From
5205 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5206
Richard Smithf72fccf2012-01-30 22:27:01 +00005207 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5208 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005209 return true;
5210 }
5211
5212 case CK_IntegralComplexToFloatingComplex: {
5213 if (!Visit(E->getSubExpr()))
5214 return false;
5215
5216 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5217 QualType From
5218 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5219 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005220 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5221 To, Result.FloatReal) &&
5222 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5223 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005224 }
5225 }
5226
5227 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005228}
5229
John McCallf4cf1a12010-05-07 17:22:02 +00005230bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005231 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005232 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5233
Richard Smith745f5142012-01-27 01:14:48 +00005234 bool LHSOK = Visit(E->getLHS());
5235 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005236 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005237
John McCallf4cf1a12010-05-07 17:22:02 +00005238 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005239 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005240 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005241
Daniel Dunbar3f279872009-01-29 01:32:56 +00005242 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5243 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005244 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005245 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005246 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005247 if (Result.isComplexFloat()) {
5248 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5249 APFloat::rmNearestTiesToEven);
5250 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5251 APFloat::rmNearestTiesToEven);
5252 } else {
5253 Result.getComplexIntReal() += RHS.getComplexIntReal();
5254 Result.getComplexIntImag() += RHS.getComplexIntImag();
5255 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005256 break;
John McCall2de56d12010-08-25 11:45:40 +00005257 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005258 if (Result.isComplexFloat()) {
5259 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5260 APFloat::rmNearestTiesToEven);
5261 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5262 APFloat::rmNearestTiesToEven);
5263 } else {
5264 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5265 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5266 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005267 break;
John McCall2de56d12010-08-25 11:45:40 +00005268 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005269 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005270 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005271 APFloat &LHS_r = LHS.getComplexFloatReal();
5272 APFloat &LHS_i = LHS.getComplexFloatImag();
5273 APFloat &RHS_r = RHS.getComplexFloatReal();
5274 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005275
Daniel Dunbar3f279872009-01-29 01:32:56 +00005276 APFloat Tmp = LHS_r;
5277 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5278 Result.getComplexFloatReal() = Tmp;
5279 Tmp = LHS_i;
5280 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5281 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5282
5283 Tmp = LHS_r;
5284 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5285 Result.getComplexFloatImag() = Tmp;
5286 Tmp = LHS_i;
5287 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5288 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5289 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005290 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005291 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005292 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5293 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005294 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005295 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5296 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5297 }
5298 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005299 case BO_Div:
5300 if (Result.isComplexFloat()) {
5301 ComplexValue LHS = Result;
5302 APFloat &LHS_r = LHS.getComplexFloatReal();
5303 APFloat &LHS_i = LHS.getComplexFloatImag();
5304 APFloat &RHS_r = RHS.getComplexFloatReal();
5305 APFloat &RHS_i = RHS.getComplexFloatImag();
5306 APFloat &Res_r = Result.getComplexFloatReal();
5307 APFloat &Res_i = Result.getComplexFloatImag();
5308
5309 APFloat Den = RHS_r;
5310 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5311 APFloat Tmp = RHS_i;
5312 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5313 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5314
5315 Res_r = LHS_r;
5316 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5317 Tmp = LHS_i;
5318 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5319 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5320 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5321
5322 Res_i = LHS_i;
5323 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5324 Tmp = LHS_r;
5325 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5326 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5327 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5328 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005329 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5330 return Error(E, diag::note_expr_divide_by_zero);
5331
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005332 ComplexValue LHS = Result;
5333 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5334 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5335 Result.getComplexIntReal() =
5336 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5337 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5338 Result.getComplexIntImag() =
5339 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5340 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5341 }
5342 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005343 }
5344
John McCallf4cf1a12010-05-07 17:22:02 +00005345 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005346}
5347
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005348bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5349 // Get the operand value into 'Result'.
5350 if (!Visit(E->getSubExpr()))
5351 return false;
5352
5353 switch (E->getOpcode()) {
5354 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005355 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005356 case UO_Extension:
5357 return true;
5358 case UO_Plus:
5359 // The result is always just the subexpr.
5360 return true;
5361 case UO_Minus:
5362 if (Result.isComplexFloat()) {
5363 Result.getComplexFloatReal().changeSign();
5364 Result.getComplexFloatImag().changeSign();
5365 }
5366 else {
5367 Result.getComplexIntReal() = -Result.getComplexIntReal();
5368 Result.getComplexIntImag() = -Result.getComplexIntImag();
5369 }
5370 return true;
5371 case UO_Not:
5372 if (Result.isComplexFloat())
5373 Result.getComplexFloatImag().changeSign();
5374 else
5375 Result.getComplexIntImag() = -Result.getComplexIntImag();
5376 return true;
5377 }
5378}
5379
Eli Friedman7ead5c72012-01-10 04:58:17 +00005380bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5381 if (E->getNumInits() == 2) {
5382 if (E->getType()->isComplexType()) {
5383 Result.makeComplexFloat();
5384 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5385 return false;
5386 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5387 return false;
5388 } else {
5389 Result.makeComplexInt();
5390 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5391 return false;
5392 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5393 return false;
5394 }
5395 return true;
5396 }
5397 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5398}
5399
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005400//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005401// Void expression evaluation, primarily for a cast to void on the LHS of a
5402// comma operator
5403//===----------------------------------------------------------------------===//
5404
5405namespace {
5406class VoidExprEvaluator
5407 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5408public:
5409 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5410
5411 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005412
5413 bool VisitCastExpr(const CastExpr *E) {
5414 switch (E->getCastKind()) {
5415 default:
5416 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5417 case CK_ToVoid:
5418 VisitIgnoredValue(E->getSubExpr());
5419 return true;
5420 }
5421 }
5422};
5423} // end anonymous namespace
5424
5425static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5426 assert(E->isRValue() && E->getType()->isVoidType());
5427 return VoidExprEvaluator(Info).Visit(E);
5428}
5429
5430//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005431// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005432//===----------------------------------------------------------------------===//
5433
Richard Smith47a1eed2011-10-29 20:57:55 +00005434static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005435 // In C, function designators are not lvalues, but we evaluate them as if they
5436 // are.
5437 if (E->isGLValue() || E->getType()->isFunctionType()) {
5438 LValue LV;
5439 if (!EvaluateLValue(E, LV, Info))
5440 return false;
5441 LV.moveInto(Result);
5442 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005443 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005444 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005445 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005446 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005447 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005448 } else if (E->getType()->hasPointerRepresentation()) {
5449 LValue LV;
5450 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005451 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005452 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005453 } else if (E->getType()->isRealFloatingType()) {
5454 llvm::APFloat F(0.0);
5455 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005456 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005457 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005458 } else if (E->getType()->isAnyComplexType()) {
5459 ComplexValue C;
5460 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005461 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005462 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005463 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005464 MemberPtr P;
5465 if (!EvaluateMemberPointer(E, P, Info))
5466 return false;
5467 P.moveInto(Result);
5468 return true;
Richard Smith51201882011-12-30 21:15:51 +00005469 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005470 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005471 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005472 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005473 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005474 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005475 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005476 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005477 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005478 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5479 return false;
5480 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005481 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005482 if (Info.getLangOpts().CPlusPlus0x)
5483 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5484 << E->getType();
5485 else
5486 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005487 if (!EvaluateVoid(E, Info))
5488 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005489 } else if (Info.getLangOpts().CPlusPlus0x) {
5490 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5491 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005492 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005493 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005494 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005495 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005496
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005497 return true;
5498}
5499
Richard Smith69c2c502011-11-04 05:33:44 +00005500/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5501/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5502/// since later initializers for an object can indirectly refer to subobjects
5503/// which were initialized earlier.
5504static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005505 const LValue &This, const Expr *E,
5506 CheckConstantExpressionKind CCEK) {
Richard Smith51201882011-12-30 21:15:51 +00005507 if (!CheckLiteralType(Info, E))
5508 return false;
5509
5510 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005511 // Evaluate arrays and record types in-place, so that later initializers can
5512 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005513 if (E->getType()->isArrayType())
5514 return EvaluateArray(E, This, Result, Info);
5515 else if (E->getType()->isRecordType())
5516 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005517 }
5518
5519 // For any other type, in-place evaluation is unimportant.
5520 CCValue CoreConstResult;
5521 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005522 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005523}
5524
Richard Smithf48fdb02011-12-09 22:58:01 +00005525/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5526/// lvalue-to-rvalue cast if it is an lvalue.
5527static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005528 if (!CheckLiteralType(Info, E))
5529 return false;
5530
Richard Smithf48fdb02011-12-09 22:58:01 +00005531 CCValue Value;
5532 if (!::Evaluate(Value, Info, E))
5533 return false;
5534
5535 if (E->isGLValue()) {
5536 LValue LV;
5537 LV.setFrom(Value);
5538 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5539 return false;
5540 }
5541
5542 // Check this core constant expression is a constant expression, and if so,
5543 // convert it to one.
5544 return CheckConstantExpression(Info, E, Value, Result);
5545}
Richard Smithc49bd112011-10-28 17:51:58 +00005546
Richard Smith51f47082011-10-29 00:50:52 +00005547/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005548/// any crazy technique (that has nothing to do with language standards) that
5549/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005550/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5551/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005552bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005553 // Fast-path evaluations of integer literals, since we sometimes see files
5554 // containing vast quantities of these.
5555 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5556 Result.Val = APValue(APSInt(L->getValue(),
5557 L->getType()->isUnsignedIntegerType()));
5558 return true;
5559 }
5560
Richard Smith2d6a5672012-01-14 04:30:29 +00005561 // FIXME: Evaluating values of large array and record types can cause
5562 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005563 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5564 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005565 return false;
5566
Richard Smithf48fdb02011-12-09 22:58:01 +00005567 EvalInfo Info(Ctx, Result);
5568 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005569}
5570
Jay Foad4ba2a172011-01-12 09:06:06 +00005571bool Expr::EvaluateAsBooleanCondition(bool &Result,
5572 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005573 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005574 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00005575 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5576 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005577 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005578}
5579
Richard Smith80d4b552011-12-28 19:48:30 +00005580bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5581 SideEffectsKind AllowSideEffects) const {
5582 if (!getType()->isIntegralOrEnumerationType())
5583 return false;
5584
Richard Smithc49bd112011-10-28 17:51:58 +00005585 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00005586 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5587 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00005588 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005589
Richard Smithc49bd112011-10-28 17:51:58 +00005590 Result = ExprResult.Val.getInt();
5591 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005592}
5593
Jay Foad4ba2a172011-01-12 09:06:06 +00005594bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005595 EvalInfo Info(Ctx, Result);
5596
John McCallefdb83e2010-05-07 21:00:08 +00005597 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005598 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005599 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5600 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005601}
5602
Richard Smith099e7f62011-12-19 06:19:21 +00005603bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5604 const VarDecl *VD,
5605 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00005606 // FIXME: Evaluating initializers for large array and record types can cause
5607 // performance problems. Only do so in C++11 for now.
5608 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5609 !Ctx.getLangOptions().CPlusPlus0x)
5610 return false;
5611
Richard Smith099e7f62011-12-19 06:19:21 +00005612 Expr::EvalStatus EStatus;
5613 EStatus.Diag = &Notes;
5614
5615 EvalInfo InitInfo(Ctx, EStatus);
5616 InitInfo.setEvaluatingDecl(VD, Value);
5617
Richard Smith51201882011-12-30 21:15:51 +00005618 if (!CheckLiteralType(InitInfo, this))
5619 return false;
5620
Richard Smith099e7f62011-12-19 06:19:21 +00005621 LValue LVal;
5622 LVal.set(VD);
5623
Richard Smith51201882011-12-30 21:15:51 +00005624 // C++11 [basic.start.init]p2:
5625 // Variables with static storage duration or thread storage duration shall be
5626 // zero-initialized before any other initialization takes place.
5627 // This behavior is not present in C.
5628 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5629 !VD->getType()->isReferenceType()) {
5630 ImplicitValueInitExpr VIE(VD->getType());
5631 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5632 return false;
5633 }
5634
Richard Smith099e7f62011-12-19 06:19:21 +00005635 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5636 !EStatus.HasSideEffects;
5637}
5638
Richard Smith51f47082011-10-29 00:50:52 +00005639/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5640/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005641bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005642 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005643 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005644}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005645
Jay Foad4ba2a172011-01-12 09:06:06 +00005646bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005647 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005648}
5649
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005650APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005651 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005652 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005653 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005654 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005655 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005656
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005657 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005658}
John McCalld905f5a2010-05-07 05:32:02 +00005659
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005660 bool Expr::EvalResult::isGlobalLValue() const {
5661 assert(Val.isLValue());
5662 return IsGlobalLValue(Val.getLValueBase());
5663 }
5664
5665
John McCalld905f5a2010-05-07 05:32:02 +00005666/// isIntegerConstantExpr - this recursive routine will test if an expression is
5667/// an integer constant expression.
5668
5669/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5670/// comma, etc
5671///
5672/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5673/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5674/// cast+dereference.
5675
5676// CheckICE - This function does the fundamental ICE checking: the returned
5677// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5678// Note that to reduce code duplication, this helper does no evaluation
5679// itself; the caller checks whether the expression is evaluatable, and
5680// in the rare cases where CheckICE actually cares about the evaluated
5681// value, it calls into Evalute.
5682//
5683// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005684// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005685// 1: This expression is not an ICE, but if it isn't evaluated, it's
5686// a legal subexpression for an ICE. This return value is used to handle
5687// the comma operator in C99 mode.
5688// 2: This expression is not an ICE, and is not a legal subexpression for one.
5689
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005690namespace {
5691
John McCalld905f5a2010-05-07 05:32:02 +00005692struct ICEDiag {
5693 unsigned Val;
5694 SourceLocation Loc;
5695
5696 public:
5697 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5698 ICEDiag() : Val(0) {}
5699};
5700
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005701}
5702
5703static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00005704
5705static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5706 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005707 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005708 !EVResult.Val.isInt()) {
5709 return ICEDiag(2, E->getLocStart());
5710 }
5711 return NoDiag();
5712}
5713
5714static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5715 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005716 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00005717 return ICEDiag(2, E->getLocStart());
5718 }
5719
5720 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00005721#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00005722#define STMT(Node, Base) case Expr::Node##Class:
5723#define EXPR(Node, Base)
5724#include "clang/AST/StmtNodes.inc"
5725 case Expr::PredefinedExprClass:
5726 case Expr::FloatingLiteralClass:
5727 case Expr::ImaginaryLiteralClass:
5728 case Expr::StringLiteralClass:
5729 case Expr::ArraySubscriptExprClass:
5730 case Expr::MemberExprClass:
5731 case Expr::CompoundAssignOperatorClass:
5732 case Expr::CompoundLiteralExprClass:
5733 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005734 case Expr::DesignatedInitExprClass:
5735 case Expr::ImplicitValueInitExprClass:
5736 case Expr::ParenListExprClass:
5737 case Expr::VAArgExprClass:
5738 case Expr::AddrLabelExprClass:
5739 case Expr::StmtExprClass:
5740 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00005741 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005742 case Expr::CXXDynamicCastExprClass:
5743 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00005744 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005745 case Expr::CXXNullPtrLiteralExprClass:
5746 case Expr::CXXThisExprClass:
5747 case Expr::CXXThrowExprClass:
5748 case Expr::CXXNewExprClass:
5749 case Expr::CXXDeleteExprClass:
5750 case Expr::CXXPseudoDestructorExprClass:
5751 case Expr::UnresolvedLookupExprClass:
5752 case Expr::DependentScopeDeclRefExprClass:
5753 case Expr::CXXConstructExprClass:
5754 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00005755 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00005756 case Expr::CXXTemporaryObjectExprClass:
5757 case Expr::CXXUnresolvedConstructExprClass:
5758 case Expr::CXXDependentScopeMemberExprClass:
5759 case Expr::UnresolvedMemberExprClass:
5760 case Expr::ObjCStringLiteralClass:
5761 case Expr::ObjCEncodeExprClass:
5762 case Expr::ObjCMessageExprClass:
5763 case Expr::ObjCSelectorExprClass:
5764 case Expr::ObjCProtocolExprClass:
5765 case Expr::ObjCIvarRefExprClass:
5766 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005767 case Expr::ObjCIsaExprClass:
5768 case Expr::ShuffleVectorExprClass:
5769 case Expr::BlockExprClass:
5770 case Expr::BlockDeclRefExprClass:
5771 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00005772 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00005773 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00005774 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005775 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005776 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00005777 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00005778 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00005779 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005780 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005781 return ICEDiag(2, E->getLocStart());
5782
Douglas Gregoree8aff02011-01-04 17:33:58 +00005783 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005784 case Expr::GNUNullExprClass:
5785 // GCC considers the GNU __null value to be an integral constant expression.
5786 return NoDiag();
5787
John McCall91a57552011-07-15 05:09:51 +00005788 case Expr::SubstNonTypeTemplateParmExprClass:
5789 return
5790 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5791
John McCalld905f5a2010-05-07 05:32:02 +00005792 case Expr::ParenExprClass:
5793 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00005794 case Expr::GenericSelectionExprClass:
5795 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005796 case Expr::IntegerLiteralClass:
5797 case Expr::CharacterLiteralClass:
5798 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00005799 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005800 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00005801 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00005802 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00005803 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00005804 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005805 return NoDiag();
5806 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00005807 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00005808 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5809 // constant expressions, but they can never be ICEs because an ICE cannot
5810 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00005811 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00005812 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00005813 return CheckEvalInICE(E, Ctx);
5814 return ICEDiag(2, E->getLocStart());
5815 }
5816 case Expr::DeclRefExprClass:
5817 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5818 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00005819 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00005820 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5821
5822 // Parameter variables are never constants. Without this check,
5823 // getAnyInitializer() can find a default argument, which leads
5824 // to chaos.
5825 if (isa<ParmVarDecl>(D))
5826 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5827
5828 // C++ 7.1.5.1p2
5829 // A variable of non-volatile const-qualified integral or enumeration
5830 // type initialized by an ICE can be used in ICEs.
5831 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00005832 if (!Dcl->getType()->isIntegralOrEnumerationType())
5833 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5834
Richard Smith099e7f62011-12-19 06:19:21 +00005835 const VarDecl *VD;
5836 // Look for a declaration of this variable that has an initializer, and
5837 // check whether it is an ICE.
5838 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5839 return NoDiag();
5840 else
5841 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00005842 }
5843 }
5844 return ICEDiag(2, E->getLocStart());
5845 case Expr::UnaryOperatorClass: {
5846 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5847 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005848 case UO_PostInc:
5849 case UO_PostDec:
5850 case UO_PreInc:
5851 case UO_PreDec:
5852 case UO_AddrOf:
5853 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00005854 // C99 6.6/3 allows increment and decrement within unevaluated
5855 // subexpressions of constant expressions, but they can never be ICEs
5856 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005857 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00005858 case UO_Extension:
5859 case UO_LNot:
5860 case UO_Plus:
5861 case UO_Minus:
5862 case UO_Not:
5863 case UO_Real:
5864 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00005865 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005866 }
5867
5868 // OffsetOf falls through here.
5869 }
5870 case Expr::OffsetOfExprClass: {
5871 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00005872 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00005873 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00005874 // compliance: we should warn earlier for offsetof expressions with
5875 // array subscripts that aren't ICEs, and if the array subscripts
5876 // are ICEs, the value of the offsetof must be an integer constant.
5877 return CheckEvalInICE(E, Ctx);
5878 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005879 case Expr::UnaryExprOrTypeTraitExprClass: {
5880 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5881 if ((Exp->getKind() == UETT_SizeOf) &&
5882 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00005883 return ICEDiag(2, E->getLocStart());
5884 return NoDiag();
5885 }
5886 case Expr::BinaryOperatorClass: {
5887 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5888 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005889 case BO_PtrMemD:
5890 case BO_PtrMemI:
5891 case BO_Assign:
5892 case BO_MulAssign:
5893 case BO_DivAssign:
5894 case BO_RemAssign:
5895 case BO_AddAssign:
5896 case BO_SubAssign:
5897 case BO_ShlAssign:
5898 case BO_ShrAssign:
5899 case BO_AndAssign:
5900 case BO_XorAssign:
5901 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00005902 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5903 // constant expressions, but they can never be ICEs because an ICE cannot
5904 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005905 return ICEDiag(2, E->getLocStart());
5906
John McCall2de56d12010-08-25 11:45:40 +00005907 case BO_Mul:
5908 case BO_Div:
5909 case BO_Rem:
5910 case BO_Add:
5911 case BO_Sub:
5912 case BO_Shl:
5913 case BO_Shr:
5914 case BO_LT:
5915 case BO_GT:
5916 case BO_LE:
5917 case BO_GE:
5918 case BO_EQ:
5919 case BO_NE:
5920 case BO_And:
5921 case BO_Xor:
5922 case BO_Or:
5923 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00005924 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5925 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00005926 if (Exp->getOpcode() == BO_Div ||
5927 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00005928 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00005929 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00005930 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005931 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005932 if (REval == 0)
5933 return ICEDiag(1, E->getLocStart());
5934 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005935 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005936 if (LEval.isMinSignedValue())
5937 return ICEDiag(1, E->getLocStart());
5938 }
5939 }
5940 }
John McCall2de56d12010-08-25 11:45:40 +00005941 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00005942 if (Ctx.getLangOptions().C99) {
5943 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5944 // if it isn't evaluated.
5945 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5946 return ICEDiag(1, E->getLocStart());
5947 } else {
5948 // In both C89 and C++, commas in ICEs are illegal.
5949 return ICEDiag(2, E->getLocStart());
5950 }
5951 }
5952 if (LHSResult.Val >= RHSResult.Val)
5953 return LHSResult;
5954 return RHSResult;
5955 }
John McCall2de56d12010-08-25 11:45:40 +00005956 case BO_LAnd:
5957 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00005958 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5959 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5960 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5961 // Rare case where the RHS has a comma "side-effect"; we need
5962 // to actually check the condition to see whether the side
5963 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00005964 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005965 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00005966 return RHSResult;
5967 return NoDiag();
5968 }
5969
5970 if (LHSResult.Val >= RHSResult.Val)
5971 return LHSResult;
5972 return RHSResult;
5973 }
5974 }
5975 }
5976 case Expr::ImplicitCastExprClass:
5977 case Expr::CStyleCastExprClass:
5978 case Expr::CXXFunctionalCastExprClass:
5979 case Expr::CXXStaticCastExprClass:
5980 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00005981 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005982 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00005983 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00005984 if (isa<ExplicitCastExpr>(E)) {
5985 if (const FloatingLiteral *FL
5986 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5987 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5988 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5989 APSInt IgnoredVal(DestWidth, !DestSigned);
5990 bool Ignored;
5991 // If the value does not fit in the destination type, the behavior is
5992 // undefined, so we are not required to treat it as a constant
5993 // expression.
5994 if (FL->getValue().convertToInteger(IgnoredVal,
5995 llvm::APFloat::rmTowardZero,
5996 &Ignored) & APFloat::opInvalidOp)
5997 return ICEDiag(2, E->getLocStart());
5998 return NoDiag();
5999 }
6000 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006001 switch (cast<CastExpr>(E)->getCastKind()) {
6002 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006003 case CK_AtomicToNonAtomic:
6004 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006005 case CK_NoOp:
6006 case CK_IntegralToBoolean:
6007 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006008 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006009 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006010 return ICEDiag(2, E->getLocStart());
6011 }
John McCalld905f5a2010-05-07 05:32:02 +00006012 }
John McCall56ca35d2011-02-17 10:25:35 +00006013 case Expr::BinaryConditionalOperatorClass: {
6014 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6015 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6016 if (CommonResult.Val == 2) return CommonResult;
6017 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6018 if (FalseResult.Val == 2) return FalseResult;
6019 if (CommonResult.Val == 1) return CommonResult;
6020 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006021 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006022 return FalseResult;
6023 }
John McCalld905f5a2010-05-07 05:32:02 +00006024 case Expr::ConditionalOperatorClass: {
6025 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6026 // If the condition (ignoring parens) is a __builtin_constant_p call,
6027 // then only the true side is actually considered in an integer constant
6028 // expression, and it is fully evaluated. This is an important GNU
6029 // extension. See GCC PR38377 for discussion.
6030 if (const CallExpr *CallCE
6031 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006032 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6033 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006034 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006035 if (CondResult.Val == 2)
6036 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006037
Richard Smithf48fdb02011-12-09 22:58:01 +00006038 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6039 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006040
John McCalld905f5a2010-05-07 05:32:02 +00006041 if (TrueResult.Val == 2)
6042 return TrueResult;
6043 if (FalseResult.Val == 2)
6044 return FalseResult;
6045 if (CondResult.Val == 1)
6046 return CondResult;
6047 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6048 return NoDiag();
6049 // Rare case where the diagnostics depend on which side is evaluated
6050 // Note that if we get here, CondResult is 0, and at least one of
6051 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006052 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006053 return FalseResult;
6054 }
6055 return TrueResult;
6056 }
6057 case Expr::CXXDefaultArgExprClass:
6058 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6059 case Expr::ChooseExprClass: {
6060 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6061 }
6062 }
6063
David Blaikie30263482012-01-20 21:50:17 +00006064 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006065}
6066
Richard Smithf48fdb02011-12-09 22:58:01 +00006067/// Evaluate an expression as a C++11 integral constant expression.
6068static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6069 const Expr *E,
6070 llvm::APSInt *Value,
6071 SourceLocation *Loc) {
6072 if (!E->getType()->isIntegralOrEnumerationType()) {
6073 if (Loc) *Loc = E->getExprLoc();
6074 return false;
6075 }
6076
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006077 APValue Result;
6078 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006079 return false;
6080
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006081 assert(Result.isInt() && "pointer cast to int is not an ICE");
6082 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006083 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006084}
6085
Richard Smithdd1f29b2011-12-12 09:28:41 +00006086bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006087 if (Ctx.getLangOptions().CPlusPlus0x)
6088 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6089
John McCalld905f5a2010-05-07 05:32:02 +00006090 ICEDiag d = CheckICE(this, Ctx);
6091 if (d.Val != 0) {
6092 if (Loc) *Loc = d.Loc;
6093 return false;
6094 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006095 return true;
6096}
6097
6098bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6099 SourceLocation *Loc, bool isEvaluated) const {
6100 if (Ctx.getLangOptions().CPlusPlus0x)
6101 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6102
6103 if (!isIntegerConstantExpr(Ctx, Loc))
6104 return false;
6105 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006106 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006107 return true;
6108}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006109
6110bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6111 SourceLocation *Loc) const {
6112 // We support this checking in C++98 mode in order to diagnose compatibility
6113 // issues.
6114 assert(Ctx.getLangOptions().CPlusPlus);
6115
6116 Expr::EvalStatus Status;
6117 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6118 Status.Diag = &Diags;
6119 EvalInfo Info(Ctx, Status);
6120
6121 APValue Scratch;
6122 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6123
6124 if (!Diags.empty()) {
6125 IsConstExpr = false;
6126 if (Loc) *Loc = Diags[0].first;
6127 } else if (!IsConstExpr) {
6128 // FIXME: This shouldn't happen.
6129 if (Loc) *Loc = getExprLoc();
6130 }
6131
6132 return IsConstExpr;
6133}
Richard Smith745f5142012-01-27 01:14:48 +00006134
6135bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6136 llvm::SmallVectorImpl<
6137 PartialDiagnosticAt> &Diags) {
6138 // FIXME: It would be useful to check constexpr function templates, but at the
6139 // moment the constant expression evaluator cannot cope with the non-rigorous
6140 // ASTs which we build for dependent expressions.
6141 if (FD->isDependentContext())
6142 return true;
6143
6144 Expr::EvalStatus Status;
6145 Status.Diag = &Diags;
6146
6147 EvalInfo Info(FD->getASTContext(), Status);
6148 Info.CheckingPotentialConstantExpression = true;
6149
6150 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6151 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6152
6153 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6154 // is a temporary being used as the 'this' pointer.
6155 LValue This;
6156 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6157 This.set(&VIE, Info.CurrentCall);
6158
6159 APValue Scratch;
6160 ArrayRef<const Expr*> Args;
6161
6162 SourceLocation Loc = FD->getLocation();
6163
6164 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
6165 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6166 } else
6167 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6168 Args, FD->getBody(), Info, Scratch);
6169
6170 return Diags.empty();
6171}