blob: d50a4fb8302798642d9e74c52a21f0ab0369837a [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
Mike Stump1eb44332009-09-09 15:08:12 +00001089static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +00001090 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001091 unsigned DestWidth = Ctx.getIntWidth(DestType);
1092 APSInt Result = Value;
1093 // Figure out if this is a truncate, extend or noop cast.
1094 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001095 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001096 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001097 return Result;
1098}
1099
Richard Smithc1c5f272011-12-13 06:39:58 +00001100static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1101 QualType SrcType, const APSInt &Value,
1102 QualType DestType, APFloat &Result) {
1103 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1104 if (Result.convertFromAPInt(Value, Value.isSigned(),
1105 APFloat::rmNearestTiesToEven)
1106 & APFloat::opOverflow)
1107 return HandleOverflow(Info, E, Value, DestType);
1108 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001109}
1110
Eli Friedmane6a24e82011-12-22 03:51:45 +00001111static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1112 llvm::APInt &Res) {
1113 CCValue SVal;
1114 if (!Evaluate(SVal, Info, E))
1115 return false;
1116 if (SVal.isInt()) {
1117 Res = SVal.getInt();
1118 return true;
1119 }
1120 if (SVal.isFloat()) {
1121 Res = SVal.getFloat().bitcastToAPInt();
1122 return true;
1123 }
1124 if (SVal.isVector()) {
1125 QualType VecTy = E->getType();
1126 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1127 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1128 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1129 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1130 Res = llvm::APInt::getNullValue(VecSize);
1131 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1132 APValue &Elt = SVal.getVectorElt(i);
1133 llvm::APInt EltAsInt;
1134 if (Elt.isInt()) {
1135 EltAsInt = Elt.getInt();
1136 } else if (Elt.isFloat()) {
1137 EltAsInt = Elt.getFloat().bitcastToAPInt();
1138 } else {
1139 // Don't try to handle vectors of anything other than int or float
1140 // (not sure if it's possible to hit this case).
1141 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1142 return false;
1143 }
1144 unsigned BaseEltSize = EltAsInt.getBitWidth();
1145 if (BigEndian)
1146 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1147 else
1148 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1149 }
1150 return true;
1151 }
1152 // Give up if the input isn't an int, float, or vector. For example, we
1153 // reject "(v4i16)(intptr_t)&a".
1154 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1155 return false;
1156}
1157
Richard Smithb4e85ed2012-01-06 16:39:00 +00001158/// Cast an lvalue referring to a base subobject to a derived class, by
1159/// truncating the lvalue's path to the given length.
1160static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1161 const RecordDecl *TruncatedType,
1162 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001163 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001164
1165 // Check we actually point to a derived class object.
1166 if (TruncatedElements == D.Entries.size())
1167 return true;
1168 assert(TruncatedElements >= D.MostDerivedPathLength &&
1169 "not casting to a derived class");
1170 if (!Result.checkSubobject(Info, E, CSK_Derived))
1171 return false;
1172
1173 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001174 const RecordDecl *RD = TruncatedType;
1175 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001176 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1177 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001178 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001179 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001180 else
Richard Smith180f4792011-11-10 06:34:14 +00001181 Result.Offset -= Layout.getBaseClassOffset(Base);
1182 RD = Base;
1183 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001184 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001185 return true;
1186}
1187
Richard Smithb4e85ed2012-01-06 16:39:00 +00001188static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001189 const CXXRecordDecl *Derived,
1190 const CXXRecordDecl *Base,
1191 const ASTRecordLayout *RL = 0) {
1192 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1193 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001194 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001195}
1196
Richard Smithb4e85ed2012-01-06 16:39:00 +00001197static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001198 const CXXRecordDecl *DerivedDecl,
1199 const CXXBaseSpecifier *Base) {
1200 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1201
1202 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001203 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001204 return true;
1205 }
1206
Richard Smithb4e85ed2012-01-06 16:39:00 +00001207 SubobjectDesignator &D = Obj.Designator;
1208 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001209 return false;
1210
Richard Smithb4e85ed2012-01-06 16:39:00 +00001211 // Extract most-derived object and corresponding type.
1212 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1213 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1214 return false;
1215
1216 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001217 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1218 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001219 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001220 return true;
1221}
1222
1223/// Update LVal to refer to the given field, which must be a member of the type
1224/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001225static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001226 const FieldDecl *FD,
1227 const ASTRecordLayout *RL = 0) {
1228 if (!RL)
1229 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1230
1231 unsigned I = FD->getFieldIndex();
1232 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001233 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001234}
1235
Richard Smithd9b02e72012-01-25 22:15:11 +00001236/// Update LVal to refer to the given indirect field.
1237static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1238 LValue &LVal,
1239 const IndirectFieldDecl *IFD) {
1240 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1241 CE = IFD->chain_end(); C != CE; ++C)
1242 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1243}
1244
Richard Smith180f4792011-11-10 06:34:14 +00001245/// Get the size of the given type in char units.
1246static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1247 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1248 // extension.
1249 if (Type->isVoidType() || Type->isFunctionType()) {
1250 Size = CharUnits::One();
1251 return true;
1252 }
1253
1254 if (!Type->isConstantSizeType()) {
1255 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001256 // FIXME: Diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001257 return false;
1258 }
1259
1260 Size = Info.Ctx.getTypeSizeInChars(Type);
1261 return true;
1262}
1263
1264/// Update a pointer value to model pointer arithmetic.
1265/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001266/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001267/// \param LVal - The pointer value to be updated.
1268/// \param EltTy - The pointee type represented by LVal.
1269/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001270static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1271 LValue &LVal, QualType EltTy,
1272 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001273 CharUnits SizeOfPointee;
1274 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1275 return false;
1276
1277 // Compute the new offset in the appropriate width.
1278 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001279 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001280 return true;
1281}
1282
Richard Smith03f96112011-10-24 17:54:18 +00001283/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001284static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1285 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001286 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001287 // If this is a parameter to an active constexpr function call, perform
1288 // argument substitution.
1289 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001290 // Assume arguments of a potential constant expression are unknown
1291 // constant expressions.
1292 if (Info.CheckingPotentialConstantExpression)
1293 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001294 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001295 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001296 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001297 }
Richard Smith177dce72011-11-01 16:57:24 +00001298 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1299 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001300 }
Richard Smith03f96112011-10-24 17:54:18 +00001301
Richard Smith099e7f62011-12-19 06:19:21 +00001302 // Dig out the initializer, and use the declaration which it's attached to.
1303 const Expr *Init = VD->getAnyInitializer(VD);
1304 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001305 // If we're checking a potential constant expression, the variable could be
1306 // initialized later.
1307 if (!Info.CheckingPotentialConstantExpression)
1308 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001309 return false;
1310 }
1311
Richard Smith180f4792011-11-10 06:34:14 +00001312 // If we're currently evaluating the initializer of this declaration, use that
1313 // in-flight value.
1314 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001315 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1316 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001317 return !Result.isUninit();
1318 }
1319
Richard Smith65ac5982011-11-01 21:06:14 +00001320 // Never evaluate the initializer of a weak variable. We can't be sure that
1321 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001322 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001323 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001324 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001325 }
Richard Smith65ac5982011-11-01 21:06:14 +00001326
Richard Smith099e7f62011-12-19 06:19:21 +00001327 // Check that we can fold the initializer. In C++, we will have already done
1328 // this in the cases where it matters for conformance.
1329 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1330 if (!VD->evaluateValue(Notes)) {
1331 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1332 Notes.size() + 1) << VD;
1333 Info.Note(VD->getLocation(), diag::note_declared_at);
1334 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001335 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001336 } else if (!VD->checkInitIsICE()) {
1337 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1338 Notes.size() + 1) << VD;
1339 Info.Note(VD->getLocation(), diag::note_declared_at);
1340 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001341 }
Richard Smith03f96112011-10-24 17:54:18 +00001342
Richard Smithb4e85ed2012-01-06 16:39:00 +00001343 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001344 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001345}
1346
Richard Smithc49bd112011-10-28 17:51:58 +00001347static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001348 Qualifiers Quals = T.getQualifiers();
1349 return Quals.hasConst() && !Quals.hasVolatile();
1350}
1351
Richard Smith59efe262011-11-11 04:05:33 +00001352/// Get the base index of the given base class within an APValue representing
1353/// the given derived class.
1354static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1355 const CXXRecordDecl *Base) {
1356 Base = Base->getCanonicalDecl();
1357 unsigned Index = 0;
1358 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1359 E = Derived->bases_end(); I != E; ++I, ++Index) {
1360 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1361 return Index;
1362 }
1363
1364 llvm_unreachable("base class missing from derived class's bases list");
1365}
1366
Richard Smithcc5d4f62011-11-07 09:22:26 +00001367/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001368static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1369 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001370 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001371 if (Sub.Invalid)
1372 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001373 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001374 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001375 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001376 (unsigned)diag::note_constexpr_read_past_end :
1377 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001378 return false;
1379 }
Richard Smithf64699e2011-11-11 08:28:03 +00001380 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001381 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001382 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1383 // This object might be initialized later.
1384 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001385
1386 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1387 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001388 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001389 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001390 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001391 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001392 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001393 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001394 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001395 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001396 // Note, it should not be possible to form a pointer with a valid
1397 // designator which points more than one past the end of the array.
1398 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001399 (unsigned)diag::note_constexpr_read_past_end :
1400 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001401 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001402 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001403 if (O->getArrayInitializedElts() > Index)
1404 O = &O->getArrayInitializedElt(Index);
1405 else
1406 O = &O->getArrayFiller();
1407 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001408 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1409 // Next subobject is a class, struct or union field.
1410 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1411 if (RD->isUnion()) {
1412 const FieldDecl *UnionField = O->getUnionField();
1413 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001414 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001415 Info.Diag(E->getExprLoc(),
1416 diag::note_constexpr_read_inactive_union_member)
1417 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001418 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001419 }
Richard Smith180f4792011-11-10 06:34:14 +00001420 O = &O->getUnionValue();
1421 } else
1422 O = &O->getStructField(Field->getFieldIndex());
1423 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001424
1425 if (ObjType.isVolatileQualified()) {
1426 if (Info.getLangOpts().CPlusPlus) {
1427 // FIXME: Include a description of the path to the volatile subobject.
1428 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1429 << 2 << Field;
1430 Info.Note(Field->getLocation(), diag::note_declared_at);
1431 } else {
1432 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1433 }
1434 return false;
1435 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001436 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001437 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001438 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1439 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1440 O = &O->getStructBase(getBaseIndex(Derived, Base));
1441 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001442 }
Richard Smith180f4792011-11-10 06:34:14 +00001443
Richard Smithf48fdb02011-12-09 22:58:01 +00001444 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001445 if (!Info.CheckingPotentialConstantExpression)
1446 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001447 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001448 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001449 }
1450
Richard Smithb4e85ed2012-01-06 16:39:00 +00001451 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001452 return true;
1453}
1454
Richard Smith180f4792011-11-10 06:34:14 +00001455/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1456/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1457/// for looking up the glvalue referred to by an entity of reference type.
1458///
1459/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001460/// \param Conv - The expression for which we are performing the conversion.
1461/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001462/// \param Type - The type we expect this conversion to produce.
1463/// \param LVal - The glvalue on which we are attempting to perform this action.
1464/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001465static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1466 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001467 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001468 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1469 if (!Info.getLangOpts().CPlusPlus)
1470 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1471
Richard Smithb4e85ed2012-01-06 16:39:00 +00001472 if (LVal.Designator.Invalid)
1473 // A diagnostic will have already been produced.
1474 return false;
1475
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001476 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001477 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001478 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001479
Richard Smithf48fdb02011-12-09 22:58:01 +00001480 if (!LVal.Base) {
1481 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001482 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1483 return false;
1484 }
1485
1486 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1487 // is not a constant expression (even if the object is non-volatile). We also
1488 // apply this rule to C++98, in order to conform to the expected 'volatile'
1489 // semantics.
1490 if (Type.isVolatileQualified()) {
1491 if (Info.getLangOpts().CPlusPlus)
1492 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1493 else
1494 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001495 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001496 }
Richard Smithc49bd112011-10-28 17:51:58 +00001497
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001498 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001499 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1500 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001501 // expressions are constant expressions too. Inside constexpr functions,
1502 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001503 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001504 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001505 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001506 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001507 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001508 }
1509
Richard Smith7098cbd2011-12-21 05:04:46 +00001510 // DR1313: If the object is volatile-qualified but the glvalue was not,
1511 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001512 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001513 if (VT.isVolatileQualified()) {
1514 if (Info.getLangOpts().CPlusPlus) {
1515 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1516 Info.Note(VD->getLocation(), diag::note_declared_at);
1517 } else {
1518 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001519 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001520 return false;
1521 }
1522
1523 if (!isa<ParmVarDecl>(VD)) {
1524 if (VD->isConstexpr()) {
1525 // OK, we can read this variable.
1526 } else if (VT->isIntegralOrEnumerationType()) {
1527 if (!VT.isConstQualified()) {
1528 if (Info.getLangOpts().CPlusPlus) {
1529 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1530 Info.Note(VD->getLocation(), diag::note_declared_at);
1531 } else {
1532 Info.Diag(Loc);
1533 }
1534 return false;
1535 }
1536 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1537 // We support folding of const floating-point types, in order to make
1538 // static const data members of such types (supported as an extension)
1539 // more useful.
1540 if (Info.getLangOpts().CPlusPlus0x) {
1541 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1542 Info.Note(VD->getLocation(), diag::note_declared_at);
1543 } else {
1544 Info.CCEDiag(Loc);
1545 }
1546 } else {
1547 // FIXME: Allow folding of values of any literal type in all languages.
1548 if (Info.getLangOpts().CPlusPlus0x) {
1549 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1550 Info.Note(VD->getLocation(), diag::note_declared_at);
1551 } else {
1552 Info.Diag(Loc);
1553 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001554 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001555 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001556 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001557
Richard Smithf48fdb02011-12-09 22:58:01 +00001558 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001559 return false;
1560
Richard Smith47a1eed2011-10-29 20:57:55 +00001561 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001562 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001563
1564 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1565 // conversion. This happens when the declaration and the lvalue should be
1566 // considered synonymous, for instance when initializing an array of char
1567 // from a string literal. Continue as if the initializer lvalue was the
1568 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001569 assert(RVal.getLValueOffset().isZero() &&
1570 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001571 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001572 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001573 }
1574
Richard Smith7098cbd2011-12-21 05:04:46 +00001575 // Volatile temporary objects cannot be read in constant expressions.
1576 if (Base->getType().isVolatileQualified()) {
1577 if (Info.getLangOpts().CPlusPlus) {
1578 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1579 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1580 } else {
1581 Info.Diag(Loc);
1582 }
1583 return false;
1584 }
1585
Richard Smith0a3bdb62011-11-04 02:25:55 +00001586 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1587 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1588 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001589 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001590 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001591 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001592 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001593
1594 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001595 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001596 const ConstantArrayType *CAT =
1597 Info.Ctx.getAsConstantArrayType(S->getType());
1598 if (Index >= CAT->getSize().getZExtValue()) {
1599 // Note, it should not be possible to form a pointer which points more
1600 // than one past the end of the array without producing a prior const expr
1601 // diagnostic.
1602 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001603 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001604 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001605 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1606 Type->isUnsignedIntegerType());
1607 if (Index < S->getLength())
1608 Value = S->getCodeUnit(Index);
1609 RVal = CCValue(Value);
1610 return true;
1611 }
1612
Richard Smithcc5d4f62011-11-07 09:22:26 +00001613 if (Frame) {
1614 // If this is a temporary expression with a nontrivial initializer, grab the
1615 // value from the relevant stack frame.
1616 RVal = Frame->Temporaries[Base];
1617 } else if (const CompoundLiteralExpr *CLE
1618 = dyn_cast<CompoundLiteralExpr>(Base)) {
1619 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1620 // initializer until now for such expressions. Such an expression can't be
1621 // an ICE in C, so this only matters for fold.
1622 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1623 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1624 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001625 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001626 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001627 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001628 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001629
Richard Smithf48fdb02011-12-09 22:58:01 +00001630 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1631 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001632}
1633
Richard Smith59efe262011-11-11 04:05:33 +00001634/// Build an lvalue for the object argument of a member function call.
1635static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1636 LValue &This) {
1637 if (Object->getType()->isPointerType())
1638 return EvaluatePointer(Object, This, Info);
1639
1640 if (Object->isGLValue())
1641 return EvaluateLValue(Object, This, Info);
1642
Richard Smithe24f5fc2011-11-17 22:56:20 +00001643 if (Object->getType()->isLiteralType())
1644 return EvaluateTemporary(Object, This, Info);
1645
1646 return false;
1647}
1648
1649/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1650/// lvalue referring to the result.
1651///
1652/// \param Info - Information about the ongoing evaluation.
1653/// \param BO - The member pointer access operation.
1654/// \param LV - Filled in with a reference to the resulting object.
1655/// \param IncludeMember - Specifies whether the member itself is included in
1656/// the resulting LValue subobject designator. This is not possible when
1657/// creating a bound member function.
1658/// \return The field or method declaration to which the member pointer refers,
1659/// or 0 if evaluation fails.
1660static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1661 const BinaryOperator *BO,
1662 LValue &LV,
1663 bool IncludeMember = true) {
1664 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1665
Richard Smith745f5142012-01-27 01:14:48 +00001666 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1667 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001668 return 0;
1669
1670 MemberPtr MemPtr;
1671 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1672 return 0;
1673
1674 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1675 // member value, the behavior is undefined.
1676 if (!MemPtr.getDecl())
1677 return 0;
1678
Richard Smith745f5142012-01-27 01:14:48 +00001679 if (!EvalObjOK)
1680 return 0;
1681
Richard Smithe24f5fc2011-11-17 22:56:20 +00001682 if (MemPtr.isDerivedMember()) {
1683 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001684 // The end of the derived-to-base path for the base object must match the
1685 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001686 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001687 LV.Designator.Entries.size())
1688 return 0;
1689 unsigned PathLengthToMember =
1690 LV.Designator.Entries.size() - MemPtr.Path.size();
1691 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1692 const CXXRecordDecl *LVDecl = getAsBaseClass(
1693 LV.Designator.Entries[PathLengthToMember + I]);
1694 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1695 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1696 return 0;
1697 }
1698
1699 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001700 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1701 PathLengthToMember))
1702 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001703 } else if (!MemPtr.Path.empty()) {
1704 // Extend the LValue path with the member pointer's path.
1705 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1706 MemPtr.Path.size() + IncludeMember);
1707
1708 // Walk down to the appropriate base class.
1709 QualType LVType = BO->getLHS()->getType();
1710 if (const PointerType *PT = LVType->getAs<PointerType>())
1711 LVType = PT->getPointeeType();
1712 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1713 assert(RD && "member pointer access on non-class-type expression");
1714 // The first class in the path is that of the lvalue.
1715 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1716 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001717 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001718 RD = Base;
1719 }
1720 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001721 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001722 }
1723
1724 // Add the member. Note that we cannot build bound member functions here.
1725 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001726 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1727 HandleLValueMember(Info, BO, LV, FD);
1728 else if (const IndirectFieldDecl *IFD =
1729 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1730 HandleLValueIndirectMember(Info, BO, LV, IFD);
1731 else
1732 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001733 }
1734
1735 return MemPtr.getDecl();
1736}
1737
1738/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1739/// the provided lvalue, which currently refers to the base object.
1740static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1741 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001742 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001743 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001744 return false;
1745
Richard Smithb4e85ed2012-01-06 16:39:00 +00001746 QualType TargetQT = E->getType();
1747 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1748 TargetQT = PT->getPointeeType();
1749
1750 // Check this cast lands within the final derived-to-base subobject path.
1751 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1752 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1753 << D.MostDerivedType << TargetQT;
1754 return false;
1755 }
1756
Richard Smithe24f5fc2011-11-17 22:56:20 +00001757 // Check the type of the final cast. We don't need to check the path,
1758 // since a cast can only be formed if the path is unique.
1759 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001760 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1761 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001762 if (NewEntriesSize == D.MostDerivedPathLength)
1763 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1764 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001765 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001766 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1767 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1768 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001769 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001770 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001771
1772 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001773 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001774}
1775
Mike Stumpc4c90452009-10-27 22:09:17 +00001776namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001777enum EvalStmtResult {
1778 /// Evaluation failed.
1779 ESR_Failed,
1780 /// Hit a 'return' statement.
1781 ESR_Returned,
1782 /// Evaluation succeeded.
1783 ESR_Succeeded
1784};
1785}
1786
1787// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001788static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001789 const Stmt *S) {
1790 switch (S->getStmtClass()) {
1791 default:
1792 return ESR_Failed;
1793
1794 case Stmt::NullStmtClass:
1795 case Stmt::DeclStmtClass:
1796 return ESR_Succeeded;
1797
Richard Smithc1c5f272011-12-13 06:39:58 +00001798 case Stmt::ReturnStmtClass: {
1799 CCValue CCResult;
1800 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1801 if (!Evaluate(CCResult, Info, RetExpr) ||
1802 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1803 CCEK_ReturnValue))
1804 return ESR_Failed;
1805 return ESR_Returned;
1806 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001807
1808 case Stmt::CompoundStmtClass: {
1809 const CompoundStmt *CS = cast<CompoundStmt>(S);
1810 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1811 BE = CS->body_end(); BI != BE; ++BI) {
1812 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1813 if (ESR != ESR_Succeeded)
1814 return ESR;
1815 }
1816 return ESR_Succeeded;
1817 }
1818 }
1819}
1820
Richard Smith61802452011-12-22 02:22:31 +00001821/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1822/// default constructor. If so, we'll fold it whether or not it's marked as
1823/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1824/// so we need special handling.
1825static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00001826 const CXXConstructorDecl *CD,
1827 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001828 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1829 return false;
1830
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001831 // Value-initialization does not call a trivial default constructor, so such a
1832 // call is a core constant expression whether or not the constructor is
1833 // constexpr.
1834 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001835 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001836 // FIXME: If DiagDecl is an implicitly-declared special member function,
1837 // we should be much more explicit about why it's not constexpr.
1838 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1839 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1840 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00001841 } else {
1842 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1843 }
1844 }
1845 return true;
1846}
1847
Richard Smithc1c5f272011-12-13 06:39:58 +00001848/// CheckConstexprFunction - Check that a function can be called in a constant
1849/// expression.
1850static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1851 const FunctionDecl *Declaration,
1852 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00001853 // Potential constant expressions can contain calls to declared, but not yet
1854 // defined, constexpr functions.
1855 if (Info.CheckingPotentialConstantExpression && !Definition &&
1856 Declaration->isConstexpr())
1857 return false;
1858
Richard Smithc1c5f272011-12-13 06:39:58 +00001859 // Can we evaluate this function call?
1860 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1861 return true;
1862
1863 if (Info.getLangOpts().CPlusPlus0x) {
1864 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001865 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1866 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001867 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1868 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1869 << DiagDecl;
1870 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1871 } else {
1872 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1873 }
1874 return false;
1875}
1876
Richard Smith180f4792011-11-10 06:34:14 +00001877namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001878typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001879}
1880
1881/// EvaluateArgs - Evaluate the arguments to a function call.
1882static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1883 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00001884 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001885 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00001886 I != E; ++I) {
1887 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
1888 // If we're checking for a potential constant expression, evaluate all
1889 // initializers even if some of them fail.
1890 if (!Info.keepEvaluatingAfterFailure())
1891 return false;
1892 Success = false;
1893 }
1894 }
1895 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00001896}
1897
Richard Smithd0dccea2011-10-28 22:34:42 +00001898/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00001899static bool HandleFunctionCall(SourceLocation CallLoc,
1900 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00001901 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001902 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00001903 ArgVector ArgValues(Args.size());
1904 if (!EvaluateArgs(Args, ArgValues, Info))
1905 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001906
Richard Smith745f5142012-01-27 01:14:48 +00001907 if (!Info.CheckCallLimit(CallLoc))
1908 return false;
1909
1910 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001911 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1912}
1913
Richard Smith180f4792011-11-10 06:34:14 +00001914/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00001915static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001916 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001917 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00001918 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00001919 ArgVector ArgValues(Args.size());
1920 if (!EvaluateArgs(Args, ArgValues, Info))
1921 return false;
1922
Richard Smith745f5142012-01-27 01:14:48 +00001923 if (!Info.CheckCallLimit(CallLoc))
1924 return false;
1925
1926 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00001927
1928 // If it's a delegating constructor, just delegate.
1929 if (Definition->isDelegatingConstructor()) {
1930 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1931 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1932 }
1933
Richard Smith610a60c2012-01-10 04:32:03 +00001934 // For a trivial copy or move constructor, perform an APValue copy. This is
1935 // essential for unions, where the operations performed by the constructor
1936 // cannot be represented by ctor-initializers.
Richard Smith180f4792011-11-10 06:34:14 +00001937 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith610a60c2012-01-10 04:32:03 +00001938 if (Definition->isDefaulted() &&
1939 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
1940 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
1941 LValue RHS;
1942 RHS.setFrom(ArgValues[0]);
1943 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00001944 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
1945 RHS, Value))
1946 return false;
1947 assert((Value.isStruct() || Value.isUnion()) &&
1948 "trivial copy/move from non-class type?");
1949 // Any CCValue of class type must already be a constant expression.
1950 Result = Value;
1951 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00001952 }
1953
1954 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00001955 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00001956 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1957 std::distance(RD->field_begin(), RD->field_end()));
1958
1959 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1960
Richard Smith745f5142012-01-27 01:14:48 +00001961 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001962 unsigned BasesSeen = 0;
1963#ifndef NDEBUG
1964 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1965#endif
1966 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1967 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00001968 LValue Subobject = This;
1969 APValue *Value = &Result;
1970
1971 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00001972 if ((*I)->isBaseInitializer()) {
1973 QualType BaseType((*I)->getBaseClass(), 0);
1974#ifndef NDEBUG
1975 // Non-virtual base classes are initialized in the order in the class
1976 // definition. We cannot have a virtual base class for a literal type.
1977 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1978 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1979 "base class initializers not in expected order");
1980 ++BaseIt;
1981#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00001982 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00001983 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00001984 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00001985 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001986 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00001987 if (RD->isUnion()) {
1988 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00001989 Value = &Result.getUnionValue();
1990 } else {
1991 Value = &Result.getStructField(FD->getFieldIndex());
1992 }
Richard Smithd9b02e72012-01-25 22:15:11 +00001993 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001994 // Walk the indirect field decl's chain to find the object to initialize,
1995 // and make sure we've initialized every step along it.
1996 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1997 CE = IFD->chain_end();
1998 C != CE; ++C) {
1999 FieldDecl *FD = cast<FieldDecl>(*C);
2000 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2001 // Switch the union field if it differs. This happens if we had
2002 // preceding zero-initialization, and we're now initializing a union
2003 // subobject other than the first.
2004 // FIXME: In this case, the values of the other subobjects are
2005 // specified, since zero-initialization sets all padding bits to zero.
2006 if (Value->isUninit() ||
2007 (Value->isUnion() && Value->getUnionField() != FD)) {
2008 if (CD->isUnion())
2009 *Value = APValue(FD);
2010 else
2011 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2012 std::distance(CD->field_begin(), CD->field_end()));
2013 }
Richard Smith745f5142012-01-27 01:14:48 +00002014 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002015 if (CD->isUnion())
2016 Value = &Value->getUnionValue();
2017 else
2018 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002019 }
Richard Smith180f4792011-11-10 06:34:14 +00002020 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002021 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002022 }
Richard Smith745f5142012-01-27 01:14:48 +00002023
2024 if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
2025 (*I)->isBaseInitializer()
2026 ? CCEK_Constant : CCEK_MemberInit)) {
2027 // If we're checking for a potential constant expression, evaluate all
2028 // initializers even if some of them fail.
2029 if (!Info.keepEvaluatingAfterFailure())
2030 return false;
2031 Success = false;
2032 }
Richard Smith180f4792011-11-10 06:34:14 +00002033 }
2034
Richard Smith745f5142012-01-27 01:14:48 +00002035 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002036}
2037
Richard Smithd0dccea2011-10-28 22:34:42 +00002038namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002039class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002040 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002041 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002042public:
2043
Richard Smith1e12c592011-10-16 21:26:27 +00002044 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002045
2046 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002047 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002048 return true;
2049 }
2050
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002051 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2052 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002053 return Visit(E->getResultExpr());
2054 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002055 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002056 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002057 return true;
2058 return false;
2059 }
John McCallf85e1932011-06-15 23:02:42 +00002060 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002061 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002062 return true;
2063 return false;
2064 }
2065 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002066 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002067 return true;
2068 return false;
2069 }
2070
Mike Stumpc4c90452009-10-27 22:09:17 +00002071 // We don't want to evaluate BlockExprs multiple times, as they generate
2072 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002073 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2074 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2075 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002076 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002077 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2078 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2079 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2080 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2081 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2082 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002083 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002084 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002085 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002086 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002087 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002088 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2089 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2090 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2091 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002092 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002093 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2094 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2095 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2096 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2097 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002098 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002099 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002100 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002101 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002102 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002103
2104 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002105 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002106 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2107 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002108 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002109 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002110 return false;
2111 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002112
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002113 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002114};
2115
John McCall56ca35d2011-02-17 10:25:35 +00002116class OpaqueValueEvaluation {
2117 EvalInfo &info;
2118 OpaqueValueExpr *opaqueValue;
2119
2120public:
2121 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2122 Expr *value)
2123 : info(info), opaqueValue(opaqueValue) {
2124
2125 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002126 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002127 this->opaqueValue = 0;
2128 return;
2129 }
John McCall56ca35d2011-02-17 10:25:35 +00002130 }
2131
2132 bool hasError() const { return opaqueValue == 0; }
2133
2134 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00002135 // FIXME: This will not work for recursive constexpr functions using opaque
2136 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00002137 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2138 }
2139};
2140
Mike Stumpc4c90452009-10-27 22:09:17 +00002141} // end anonymous namespace
2142
Eli Friedman4efaa272008-11-12 09:44:48 +00002143//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002144// Generic Evaluation
2145//===----------------------------------------------------------------------===//
2146namespace {
2147
Richard Smithf48fdb02011-12-09 22:58:01 +00002148// FIXME: RetTy is always bool. Remove it.
2149template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002150class ExprEvaluatorBase
2151 : public ConstStmtVisitor<Derived, RetTy> {
2152private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002153 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002154 return static_cast<Derived*>(this)->Success(V, E);
2155 }
Richard Smith51201882011-12-30 21:15:51 +00002156 RetTy DerivedZeroInitialization(const Expr *E) {
2157 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002158 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002159
2160protected:
2161 EvalInfo &Info;
2162 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2163 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2164
Richard Smithdd1f29b2011-12-12 09:28:41 +00002165 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002166 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002167 }
2168
2169 /// Report an evaluation error. This should only be called when an error is
2170 /// first discovered. When propagating an error, just return false.
2171 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002172 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002173 return false;
2174 }
2175 bool Error(const Expr *E) {
2176 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2177 }
2178
Richard Smith51201882011-12-30 21:15:51 +00002179 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002180
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002181public:
2182 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2183
2184 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002185 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002186 }
2187 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002188 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002189 }
2190
2191 RetTy VisitParenExpr(const ParenExpr *E)
2192 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2193 RetTy VisitUnaryExtension(const UnaryOperator *E)
2194 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2195 RetTy VisitUnaryPlus(const UnaryOperator *E)
2196 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2197 RetTy VisitChooseExpr(const ChooseExpr *E)
2198 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2199 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2200 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002201 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2202 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002203 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2204 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002205 // We cannot create any objects for which cleanups are required, so there is
2206 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2207 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2208 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002209
Richard Smithc216a012011-12-12 12:46:16 +00002210 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2211 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2212 return static_cast<Derived*>(this)->VisitCastExpr(E);
2213 }
2214 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2215 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2216 return static_cast<Derived*>(this)->VisitCastExpr(E);
2217 }
2218
Richard Smithe24f5fc2011-11-17 22:56:20 +00002219 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2220 switch (E->getOpcode()) {
2221 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002222 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002223
2224 case BO_Comma:
2225 VisitIgnoredValue(E->getLHS());
2226 return StmtVisitorTy::Visit(E->getRHS());
2227
2228 case BO_PtrMemD:
2229 case BO_PtrMemI: {
2230 LValue Obj;
2231 if (!HandleMemberPointerAccess(Info, E, Obj))
2232 return false;
2233 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002234 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002235 return false;
2236 return DerivedSuccess(Result, E);
2237 }
2238 }
2239 }
2240
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002241 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2242 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2243 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002244 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002245
2246 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002247 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002248 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002249
2250 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2251 }
2252
2253 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2254 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002255 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002256 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002257
Richard Smithc49bd112011-10-28 17:51:58 +00002258 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002259 return StmtVisitorTy::Visit(EvalExpr);
2260 }
2261
2262 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002263 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002264 if (!Value) {
2265 const Expr *Source = E->getSourceExpr();
2266 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002267 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002268 if (Source == E) { // sanity checking.
2269 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002270 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002271 }
2272 return StmtVisitorTy::Visit(Source);
2273 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002274 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002275 }
Richard Smithf10d9172011-10-11 21:43:33 +00002276
Richard Smithd0dccea2011-10-28 22:34:42 +00002277 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002278 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002279 QualType CalleeType = Callee->getType();
2280
Richard Smithd0dccea2011-10-28 22:34:42 +00002281 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002282 LValue *This = 0, ThisVal;
2283 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002284
Richard Smith59efe262011-11-11 04:05:33 +00002285 // Extract function decl and 'this' pointer from the callee.
2286 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002287 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002288 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2289 // Explicit bound member calls, such as x.f() or p->g();
2290 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002291 return false;
2292 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002293 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002294 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2295 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002296 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2297 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002298 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002299 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002300 return Error(Callee);
2301
2302 FD = dyn_cast<FunctionDecl>(Member);
2303 if (!FD)
2304 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002305 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002306 LValue Call;
2307 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002308 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002309
Richard Smithb4e85ed2012-01-06 16:39:00 +00002310 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002311 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002312 FD = dyn_cast_or_null<FunctionDecl>(
2313 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002314 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002315 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002316
2317 // Overloaded operator calls to member functions are represented as normal
2318 // calls with '*this' as the first argument.
2319 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2320 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002321 // FIXME: When selecting an implicit conversion for an overloaded
2322 // operator delete, we sometimes try to evaluate calls to conversion
2323 // operators without a 'this' parameter!
2324 if (Args.empty())
2325 return Error(E);
2326
Richard Smith59efe262011-11-11 04:05:33 +00002327 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2328 return false;
2329 This = &ThisVal;
2330 Args = Args.slice(1);
2331 }
2332
2333 // Don't call function pointers which have been cast to some other type.
2334 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002335 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002336 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002337 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002338
Richard Smithc1c5f272011-12-13 06:39:58 +00002339 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002340 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002341 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002342
Richard Smithc1c5f272011-12-13 06:39:58 +00002343 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002344 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2345 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002346 return false;
2347
Richard Smithb4e85ed2012-01-06 16:39:00 +00002348 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002349 }
2350
Richard Smithc49bd112011-10-28 17:51:58 +00002351 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2352 return StmtVisitorTy::Visit(E->getInitializer());
2353 }
Richard Smithf10d9172011-10-11 21:43:33 +00002354 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002355 if (E->getNumInits() == 0)
2356 return DerivedZeroInitialization(E);
2357 if (E->getNumInits() == 1)
2358 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002359 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002360 }
2361 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002362 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002363 }
2364 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002365 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002366 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002367 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002368 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002369 }
Richard Smithf10d9172011-10-11 21:43:33 +00002370
Richard Smith180f4792011-11-10 06:34:14 +00002371 /// A member expression where the object is a prvalue is itself a prvalue.
2372 RetTy VisitMemberExpr(const MemberExpr *E) {
2373 assert(!E->isArrow() && "missing call to bound member function?");
2374
2375 CCValue Val;
2376 if (!Evaluate(Val, Info, E->getBase()))
2377 return false;
2378
2379 QualType BaseTy = E->getBase()->getType();
2380
2381 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002382 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002383 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2384 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2385 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2386
Richard Smithb4e85ed2012-01-06 16:39:00 +00002387 SubobjectDesignator Designator(BaseTy);
2388 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002389
Richard Smithf48fdb02011-12-09 22:58:01 +00002390 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002391 DerivedSuccess(Val, E);
2392 }
2393
Richard Smithc49bd112011-10-28 17:51:58 +00002394 RetTy VisitCastExpr(const CastExpr *E) {
2395 switch (E->getCastKind()) {
2396 default:
2397 break;
2398
David Chisnall7a7ee302012-01-16 17:27:18 +00002399 case CK_AtomicToNonAtomic:
2400 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002401 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002402 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002403 return StmtVisitorTy::Visit(E->getSubExpr());
2404
2405 case CK_LValueToRValue: {
2406 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002407 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2408 return false;
2409 CCValue RVal;
2410 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2411 return false;
2412 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002413 }
2414 }
2415
Richard Smithf48fdb02011-12-09 22:58:01 +00002416 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002417 }
2418
Richard Smith8327fad2011-10-24 18:44:57 +00002419 /// Visit a value which is evaluated, but whose value is ignored.
2420 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002421 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002422 if (!Evaluate(Scratch, Info, E))
2423 Info.EvalStatus.HasSideEffects = true;
2424 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002425};
2426
2427}
2428
2429//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002430// Common base class for lvalue and temporary evaluation.
2431//===----------------------------------------------------------------------===//
2432namespace {
2433template<class Derived>
2434class LValueExprEvaluatorBase
2435 : public ExprEvaluatorBase<Derived, bool> {
2436protected:
2437 LValue &Result;
2438 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2439 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2440
2441 bool Success(APValue::LValueBase B) {
2442 Result.set(B);
2443 return true;
2444 }
2445
2446public:
2447 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2448 ExprEvaluatorBaseTy(Info), Result(Result) {}
2449
2450 bool Success(const CCValue &V, const Expr *E) {
2451 Result.setFrom(V);
2452 return true;
2453 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002454
Richard Smithe24f5fc2011-11-17 22:56:20 +00002455 bool VisitMemberExpr(const MemberExpr *E) {
2456 // Handle non-static data members.
2457 QualType BaseTy;
2458 if (E->isArrow()) {
2459 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2460 return false;
2461 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002462 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002463 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002464 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2465 return false;
2466 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002467 } else {
2468 if (!this->Visit(E->getBase()))
2469 return false;
2470 BaseTy = E->getBase()->getType();
2471 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002472
Richard Smithd9b02e72012-01-25 22:15:11 +00002473 const ValueDecl *MD = E->getMemberDecl();
2474 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2475 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2476 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2477 (void)BaseTy;
2478 HandleLValueMember(this->Info, E, Result, FD);
2479 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2480 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2481 } else
2482 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002483
Richard Smithd9b02e72012-01-25 22:15:11 +00002484 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002485 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002486 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002487 RefValue))
2488 return false;
2489 return Success(RefValue, E);
2490 }
2491 return true;
2492 }
2493
2494 bool VisitBinaryOperator(const BinaryOperator *E) {
2495 switch (E->getOpcode()) {
2496 default:
2497 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2498
2499 case BO_PtrMemD:
2500 case BO_PtrMemI:
2501 return HandleMemberPointerAccess(this->Info, E, Result);
2502 }
2503 }
2504
2505 bool VisitCastExpr(const CastExpr *E) {
2506 switch (E->getCastKind()) {
2507 default:
2508 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2509
2510 case CK_DerivedToBase:
2511 case CK_UncheckedDerivedToBase: {
2512 if (!this->Visit(E->getSubExpr()))
2513 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002514
2515 // Now figure out the necessary offset to add to the base LV to get from
2516 // the derived class to the base class.
2517 QualType Type = E->getSubExpr()->getType();
2518
2519 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2520 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002521 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002522 *PathI))
2523 return false;
2524 Type = (*PathI)->getType();
2525 }
2526
2527 return true;
2528 }
2529 }
2530 }
2531};
2532}
2533
2534//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002535// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002536//
2537// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2538// function designators (in C), decl references to void objects (in C), and
2539// temporaries (if building with -Wno-address-of-temporary).
2540//
2541// LValue evaluation produces values comprising a base expression of one of the
2542// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002543// - Declarations
2544// * VarDecl
2545// * FunctionDecl
2546// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002547// * CompoundLiteralExpr in C
2548// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002549// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002550// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002551// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002552// * ObjCEncodeExpr
2553// * AddrLabelExpr
2554// * BlockExpr
2555// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002556// - Locals and temporaries
2557// * Any Expr, with a Frame indicating the function in which the temporary was
2558// evaluated.
2559// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002560//===----------------------------------------------------------------------===//
2561namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002562class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002563 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002564public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002565 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2566 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002567
Richard Smithc49bd112011-10-28 17:51:58 +00002568 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2569
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002570 bool VisitDeclRefExpr(const DeclRefExpr *E);
2571 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002572 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002573 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2574 bool VisitMemberExpr(const MemberExpr *E);
2575 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2576 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002577 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002578 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2579 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002580
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002581 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002582 switch (E->getCastKind()) {
2583 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002584 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002585
Eli Friedmandb924222011-10-11 00:13:24 +00002586 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002587 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002588 if (!Visit(E->getSubExpr()))
2589 return false;
2590 Result.Designator.setInvalid();
2591 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002592
Richard Smithe24f5fc2011-11-17 22:56:20 +00002593 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002594 if (!Visit(E->getSubExpr()))
2595 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002596 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002597 }
2598 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002599
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002600 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002601
Eli Friedman4efaa272008-11-12 09:44:48 +00002602};
2603} // end anonymous namespace
2604
Richard Smithc49bd112011-10-28 17:51:58 +00002605/// Evaluate an expression as an lvalue. This can be legitimately called on
2606/// expressions which are not glvalues, in a few cases:
2607/// * function designators in C,
2608/// * "extern void" objects,
2609/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002610static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002611 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2612 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2613 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002614 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002615}
2616
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002617bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002618 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2619 return Success(FD);
2620 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002621 return VisitVarDecl(E, VD);
2622 return Error(E);
2623}
Richard Smith436c8892011-10-24 23:14:33 +00002624
Richard Smithc49bd112011-10-28 17:51:58 +00002625bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002626 if (!VD->getType()->isReferenceType()) {
2627 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002628 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002629 return true;
2630 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002631 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002632 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002633
Richard Smith47a1eed2011-10-29 20:57:55 +00002634 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002635 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2636 return false;
2637 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002638}
2639
Richard Smithbd552ef2011-10-31 05:52:43 +00002640bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2641 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002642 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002643 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002644 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2645
2646 Result.set(E, Info.CurrentCall);
2647 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2648 Result, E->GetTemporaryExpr());
2649 }
2650
2651 // Materialization of an lvalue temporary occurs when we need to force a copy
2652 // (for instance, if it's a bitfield).
2653 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2654 if (!Visit(E->GetTemporaryExpr()))
2655 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002656 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002657 Info.CurrentCall->Temporaries[E]))
2658 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002659 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002660 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002661}
2662
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002663bool
2664LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002665 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2666 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2667 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002668 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002669}
2670
Richard Smith47d21452011-12-27 12:18:28 +00002671bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2672 if (E->isTypeOperand())
2673 return Success(E);
2674 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2675 if (RD && RD->isPolymorphic()) {
2676 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2677 << E->getExprOperand()->getType()
2678 << E->getExprOperand()->getSourceRange();
2679 return false;
2680 }
2681 return Success(E);
2682}
2683
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002684bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002685 // Handle static data members.
2686 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2687 VisitIgnoredValue(E->getBase());
2688 return VisitVarDecl(E, VD);
2689 }
2690
Richard Smithd0dccea2011-10-28 22:34:42 +00002691 // Handle static member functions.
2692 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2693 if (MD->isStatic()) {
2694 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002695 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002696 }
2697 }
2698
Richard Smith180f4792011-11-10 06:34:14 +00002699 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002700 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002701}
2702
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002703bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002704 // FIXME: Deal with vectors as array subscript bases.
2705 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002706 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002707
Anders Carlsson3068d112008-11-16 19:01:22 +00002708 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002709 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002710
Anders Carlsson3068d112008-11-16 19:01:22 +00002711 APSInt Index;
2712 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002713 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002714 int64_t IndexValue
2715 = Index.isSigned() ? Index.getSExtValue()
2716 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002717
Richard Smithb4e85ed2012-01-06 16:39:00 +00002718 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002719}
Eli Friedman4efaa272008-11-12 09:44:48 +00002720
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002721bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002722 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002723}
2724
Eli Friedman4efaa272008-11-12 09:44:48 +00002725//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002726// Pointer Evaluation
2727//===----------------------------------------------------------------------===//
2728
Anders Carlssonc754aa62008-07-08 05:13:58 +00002729namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002730class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002731 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002732 LValue &Result;
2733
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002734 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002735 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002736 return true;
2737 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002738public:
Mike Stump1eb44332009-09-09 15:08:12 +00002739
John McCallefdb83e2010-05-07 21:00:08 +00002740 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002741 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002742
Richard Smith47a1eed2011-10-29 20:57:55 +00002743 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002744 Result.setFrom(V);
2745 return true;
2746 }
Richard Smith51201882011-12-30 21:15:51 +00002747 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002748 return Success((Expr*)0);
2749 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002750
John McCallefdb83e2010-05-07 21:00:08 +00002751 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002752 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002753 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002754 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002755 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002756 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002757 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002758 bool VisitCallExpr(const CallExpr *E);
2759 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002760 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002761 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002762 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002763 }
Richard Smith180f4792011-11-10 06:34:14 +00002764 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2765 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002766 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002767 Result = *Info.CurrentCall->This;
2768 return true;
2769 }
John McCall56ca35d2011-02-17 10:25:35 +00002770
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002771 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002772};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002773} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002774
John McCallefdb83e2010-05-07 21:00:08 +00002775static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002776 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002777 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002778}
2779
John McCallefdb83e2010-05-07 21:00:08 +00002780bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002781 if (E->getOpcode() != BO_Add &&
2782 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002783 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002784
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002785 const Expr *PExp = E->getLHS();
2786 const Expr *IExp = E->getRHS();
2787 if (IExp->getType()->isPointerType())
2788 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002789
Richard Smith745f5142012-01-27 01:14:48 +00002790 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
2791 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00002792 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002793
John McCallefdb83e2010-05-07 21:00:08 +00002794 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00002795 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00002796 return false;
2797 int64_t AdditionalOffset
2798 = Offset.isSigned() ? Offset.getSExtValue()
2799 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002800 if (E->getOpcode() == BO_Sub)
2801 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002802
Richard Smith180f4792011-11-10 06:34:14 +00002803 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00002804 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2805 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002806}
Eli Friedman4efaa272008-11-12 09:44:48 +00002807
John McCallefdb83e2010-05-07 21:00:08 +00002808bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2809 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002810}
Mike Stump1eb44332009-09-09 15:08:12 +00002811
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002812bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2813 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002814
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002815 switch (E->getCastKind()) {
2816 default:
2817 break;
2818
John McCall2de56d12010-08-25 11:45:40 +00002819 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002820 case CK_CPointerToObjCPointerCast:
2821 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002822 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00002823 if (!Visit(SubExpr))
2824 return false;
Richard Smithc216a012011-12-12 12:46:16 +00002825 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2826 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2827 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002828 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00002829 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002830 if (SubExpr->getType()->isVoidPointerType())
2831 CCEDiag(E, diag::note_constexpr_invalid_cast)
2832 << 3 << SubExpr->getType();
2833 else
2834 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2835 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002836 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002837
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002838 case CK_DerivedToBase:
2839 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002840 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002841 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002842 if (!Result.Base && Result.Offset.isZero())
2843 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002844
Richard Smith180f4792011-11-10 06:34:14 +00002845 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002846 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002847 QualType Type =
2848 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002849
Richard Smith180f4792011-11-10 06:34:14 +00002850 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002851 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002852 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2853 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002854 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002855 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002856 }
2857
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002858 return true;
2859 }
2860
Richard Smithe24f5fc2011-11-17 22:56:20 +00002861 case CK_BaseToDerived:
2862 if (!Visit(E->getSubExpr()))
2863 return false;
2864 if (!Result.Base && Result.Offset.isZero())
2865 return true;
2866 return HandleBaseToDerivedCast(Info, E, Result);
2867
Richard Smith47a1eed2011-10-29 20:57:55 +00002868 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00002869 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002870
John McCall2de56d12010-08-25 11:45:40 +00002871 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002872 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2873
Richard Smith47a1eed2011-10-29 20:57:55 +00002874 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002875 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002876 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002877
John McCallefdb83e2010-05-07 21:00:08 +00002878 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002879 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2880 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002881 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002882 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002883 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002884 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002885 return true;
2886 } else {
2887 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002888 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002889 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002890 }
2891 }
John McCall2de56d12010-08-25 11:45:40 +00002892 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002893 if (SubExpr->isGLValue()) {
2894 if (!EvaluateLValue(SubExpr, Result, Info))
2895 return false;
2896 } else {
2897 Result.set(SubExpr, Info.CurrentCall);
2898 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2899 Info, Result, SubExpr))
2900 return false;
2901 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002902 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002903 if (const ConstantArrayType *CAT
2904 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
2905 Result.addArray(Info, E, CAT);
2906 else
2907 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00002908 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002909
John McCall2de56d12010-08-25 11:45:40 +00002910 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002911 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002912 }
2913
Richard Smithc49bd112011-10-28 17:51:58 +00002914 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002915}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002916
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002917bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002918 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002919 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002920
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002921 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002922}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002923
2924//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002925// Member Pointer Evaluation
2926//===----------------------------------------------------------------------===//
2927
2928namespace {
2929class MemberPointerExprEvaluator
2930 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2931 MemberPtr &Result;
2932
2933 bool Success(const ValueDecl *D) {
2934 Result = MemberPtr(D);
2935 return true;
2936 }
2937public:
2938
2939 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2940 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2941
2942 bool Success(const CCValue &V, const Expr *E) {
2943 Result.setFrom(V);
2944 return true;
2945 }
Richard Smith51201882011-12-30 21:15:51 +00002946 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002947 return Success((const ValueDecl*)0);
2948 }
2949
2950 bool VisitCastExpr(const CastExpr *E);
2951 bool VisitUnaryAddrOf(const UnaryOperator *E);
2952};
2953} // end anonymous namespace
2954
2955static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2956 EvalInfo &Info) {
2957 assert(E->isRValue() && E->getType()->isMemberPointerType());
2958 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2959}
2960
2961bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2962 switch (E->getCastKind()) {
2963 default:
2964 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2965
2966 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00002967 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002968
2969 case CK_BaseToDerivedMemberPointer: {
2970 if (!Visit(E->getSubExpr()))
2971 return false;
2972 if (E->path_empty())
2973 return true;
2974 // Base-to-derived member pointer casts store the path in derived-to-base
2975 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2976 // the wrong end of the derived->base arc, so stagger the path by one class.
2977 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2978 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2979 PathI != PathE; ++PathI) {
2980 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2981 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2982 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00002983 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002984 }
2985 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2986 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002987 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002988 return true;
2989 }
2990
2991 case CK_DerivedToBaseMemberPointer:
2992 if (!Visit(E->getSubExpr()))
2993 return false;
2994 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2995 PathE = E->path_end(); PathI != PathE; ++PathI) {
2996 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2997 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2998 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00002999 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003000 }
3001 return true;
3002 }
3003}
3004
3005bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3006 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3007 // member can be formed.
3008 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3009}
3010
3011//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003012// Record Evaluation
3013//===----------------------------------------------------------------------===//
3014
3015namespace {
3016 class RecordExprEvaluator
3017 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3018 const LValue &This;
3019 APValue &Result;
3020 public:
3021
3022 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3023 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3024
3025 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003026 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00003027 }
Richard Smith51201882011-12-30 21:15:51 +00003028 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003029
Richard Smith59efe262011-11-11 04:05:33 +00003030 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003031 bool VisitInitListExpr(const InitListExpr *E);
3032 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3033 };
3034}
3035
Richard Smith51201882011-12-30 21:15:51 +00003036/// Perform zero-initialization on an object of non-union class type.
3037/// C++11 [dcl.init]p5:
3038/// To zero-initialize an object or reference of type T means:
3039/// [...]
3040/// -- if T is a (possibly cv-qualified) non-union class type,
3041/// each non-static data member and each base-class subobject is
3042/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003043static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3044 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003045 const LValue &This, APValue &Result) {
3046 assert(!RD->isUnion() && "Expected non-union class type");
3047 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3048 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3049 std::distance(RD->field_begin(), RD->field_end()));
3050
3051 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3052
3053 if (CD) {
3054 unsigned Index = 0;
3055 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003056 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003057 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3058 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003059 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3060 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003061 Result.getStructBase(Index)))
3062 return false;
3063 }
3064 }
3065
Richard Smithb4e85ed2012-01-06 16:39:00 +00003066 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3067 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003068 // -- if T is a reference type, no initialization is performed.
3069 if ((*I)->getType()->isReferenceType())
3070 continue;
3071
3072 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003073 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003074
3075 ImplicitValueInitExpr VIE((*I)->getType());
3076 if (!EvaluateConstantExpression(
3077 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3078 return false;
3079 }
3080
3081 return true;
3082}
3083
3084bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3085 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3086 if (RD->isUnion()) {
3087 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3088 // object's first non-static named data member is zero-initialized
3089 RecordDecl::field_iterator I = RD->field_begin();
3090 if (I == RD->field_end()) {
3091 Result = APValue((const FieldDecl*)0);
3092 return true;
3093 }
3094
3095 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003096 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003097 Result = APValue(*I);
3098 ImplicitValueInitExpr VIE((*I)->getType());
3099 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3100 Subobject, &VIE);
3101 }
3102
Richard Smithb4e85ed2012-01-06 16:39:00 +00003103 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003104}
3105
Richard Smith59efe262011-11-11 04:05:33 +00003106bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3107 switch (E->getCastKind()) {
3108 default:
3109 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3110
3111 case CK_ConstructorConversion:
3112 return Visit(E->getSubExpr());
3113
3114 case CK_DerivedToBase:
3115 case CK_UncheckedDerivedToBase: {
3116 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003117 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003118 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003119 if (!DerivedObject.isStruct())
3120 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003121
3122 // Derived-to-base rvalue conversion: just slice off the derived part.
3123 APValue *Value = &DerivedObject;
3124 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3125 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3126 PathE = E->path_end(); PathI != PathE; ++PathI) {
3127 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3128 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3129 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3130 RD = Base;
3131 }
3132 Result = *Value;
3133 return true;
3134 }
3135 }
3136}
3137
Richard Smith180f4792011-11-10 06:34:14 +00003138bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3139 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3140 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3141
3142 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003143 const FieldDecl *Field = E->getInitializedFieldInUnion();
3144 Result = APValue(Field);
3145 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003146 return true;
Richard Smithec789162012-01-12 18:54:33 +00003147
3148 // If the initializer list for a union does not contain any elements, the
3149 // first element of the union is value-initialized.
3150 ImplicitValueInitExpr VIE(Field->getType());
3151 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3152
Richard Smith180f4792011-11-10 06:34:14 +00003153 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003154 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003155 return EvaluateConstantExpression(Result.getUnionValue(), Info,
Richard Smithec789162012-01-12 18:54:33 +00003156 Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003157 }
3158
3159 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3160 "initializer list for class with base classes");
3161 Result = APValue(APValue::UninitStruct(), 0,
3162 std::distance(RD->field_begin(), RD->field_end()));
3163 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003164 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003165 for (RecordDecl::field_iterator Field = RD->field_begin(),
3166 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3167 // Anonymous bit-fields are not considered members of the class for
3168 // purposes of aggregate initialization.
3169 if (Field->isUnnamedBitfield())
3170 continue;
3171
3172 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003173
Richard Smith745f5142012-01-27 01:14:48 +00003174 bool HaveInit = ElementNo < E->getNumInits();
3175
3176 // FIXME: Diagnostics here should point to the end of the initializer
3177 // list, not the start.
3178 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3179 *Field, &Layout);
3180
3181 // Perform an implicit value-initialization for members beyond the end of
3182 // the initializer list.
3183 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3184
3185 if (!EvaluateConstantExpression(
3186 Result.getStructField((*Field)->getFieldIndex()),
3187 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3188 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003189 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003190 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003191 }
3192 }
3193
Richard Smith745f5142012-01-27 01:14:48 +00003194 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003195}
3196
3197bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3198 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003199 bool ZeroInit = E->requiresZeroInitialization();
3200 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003201 // If we've already performed zero-initialization, we're already done.
3202 if (!Result.isUninit())
3203 return true;
3204
Richard Smith51201882011-12-30 21:15:51 +00003205 if (ZeroInit)
3206 return ZeroInitialization(E);
3207
Richard Smith61802452011-12-22 02:22:31 +00003208 const CXXRecordDecl *RD = FD->getParent();
3209 if (RD->isUnion())
3210 Result = APValue((FieldDecl*)0);
3211 else
3212 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3213 std::distance(RD->field_begin(), RD->field_end()));
3214 return true;
3215 }
3216
Richard Smith180f4792011-11-10 06:34:14 +00003217 const FunctionDecl *Definition = 0;
3218 FD->getBody(Definition);
3219
Richard Smithc1c5f272011-12-13 06:39:58 +00003220 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3221 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003222
Richard Smith610a60c2012-01-10 04:32:03 +00003223 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003224 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003225 if (const MaterializeTemporaryExpr *ME
3226 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3227 return Visit(ME->GetTemporaryExpr());
3228
Richard Smith51201882011-12-30 21:15:51 +00003229 if (ZeroInit && !ZeroInitialization(E))
3230 return false;
3231
Richard Smith180f4792011-11-10 06:34:14 +00003232 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003233 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003234 cast<CXXConstructorDecl>(Definition), Info,
3235 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003236}
3237
3238static bool EvaluateRecord(const Expr *E, const LValue &This,
3239 APValue &Result, EvalInfo &Info) {
3240 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003241 "can't evaluate expression as a record rvalue");
3242 return RecordExprEvaluator(Info, This, Result).Visit(E);
3243}
3244
3245//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003246// Temporary Evaluation
3247//
3248// Temporaries are represented in the AST as rvalues, but generally behave like
3249// lvalues. The full-object of which the temporary is a subobject is implicitly
3250// materialized so that a reference can bind to it.
3251//===----------------------------------------------------------------------===//
3252namespace {
3253class TemporaryExprEvaluator
3254 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3255public:
3256 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3257 LValueExprEvaluatorBaseTy(Info, Result) {}
3258
3259 /// Visit an expression which constructs the value of this temporary.
3260 bool VisitConstructExpr(const Expr *E) {
3261 Result.set(E, Info.CurrentCall);
3262 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3263 Result, E);
3264 }
3265
3266 bool VisitCastExpr(const CastExpr *E) {
3267 switch (E->getCastKind()) {
3268 default:
3269 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3270
3271 case CK_ConstructorConversion:
3272 return VisitConstructExpr(E->getSubExpr());
3273 }
3274 }
3275 bool VisitInitListExpr(const InitListExpr *E) {
3276 return VisitConstructExpr(E);
3277 }
3278 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3279 return VisitConstructExpr(E);
3280 }
3281 bool VisitCallExpr(const CallExpr *E) {
3282 return VisitConstructExpr(E);
3283 }
3284};
3285} // end anonymous namespace
3286
3287/// Evaluate an expression of record type as a temporary.
3288static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003289 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003290 return TemporaryExprEvaluator(Info, Result).Visit(E);
3291}
3292
3293//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003294// Vector Evaluation
3295//===----------------------------------------------------------------------===//
3296
3297namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003298 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003299 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3300 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003301 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003302
Richard Smith07fc6572011-10-22 21:10:00 +00003303 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3304 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003305
Richard Smith07fc6572011-10-22 21:10:00 +00003306 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3307 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3308 // FIXME: remove this APValue copy.
3309 Result = APValue(V.data(), V.size());
3310 return true;
3311 }
Richard Smith69c2c502011-11-04 05:33:44 +00003312 bool Success(const CCValue &V, const Expr *E) {
3313 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003314 Result = V;
3315 return true;
3316 }
Richard Smith51201882011-12-30 21:15:51 +00003317 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003318
Richard Smith07fc6572011-10-22 21:10:00 +00003319 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003320 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003321 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003322 bool VisitInitListExpr(const InitListExpr *E);
3323 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003324 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003325 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003326 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003327 };
3328} // end anonymous namespace
3329
3330static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003331 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003332 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003333}
3334
Richard Smith07fc6572011-10-22 21:10:00 +00003335bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3336 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003337 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003338
Richard Smithd62ca372011-12-06 22:44:34 +00003339 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003340 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003341
Eli Friedman46a52322011-03-25 00:43:55 +00003342 switch (E->getCastKind()) {
3343 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003344 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003345 if (SETy->isIntegerType()) {
3346 APSInt IntResult;
3347 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003348 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003349 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003350 } else if (SETy->isRealFloatingType()) {
3351 APFloat F(0.0);
3352 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003353 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003354 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003355 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003356 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003357 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003358
3359 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003360 SmallVector<APValue, 4> Elts(NElts, Val);
3361 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003362 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003363 case CK_BitCast: {
3364 // Evaluate the operand into an APInt we can extract from.
3365 llvm::APInt SValInt;
3366 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3367 return false;
3368 // Extract the elements
3369 QualType EltTy = VTy->getElementType();
3370 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3371 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3372 SmallVector<APValue, 4> Elts;
3373 if (EltTy->isRealFloatingType()) {
3374 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3375 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3376 unsigned FloatEltSize = EltSize;
3377 if (&Sem == &APFloat::x87DoubleExtended)
3378 FloatEltSize = 80;
3379 for (unsigned i = 0; i < NElts; i++) {
3380 llvm::APInt Elt;
3381 if (BigEndian)
3382 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3383 else
3384 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3385 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3386 }
3387 } else if (EltTy->isIntegerType()) {
3388 for (unsigned i = 0; i < NElts; i++) {
3389 llvm::APInt Elt;
3390 if (BigEndian)
3391 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3392 else
3393 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3394 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3395 }
3396 } else {
3397 return Error(E);
3398 }
3399 return Success(Elts, E);
3400 }
Eli Friedman46a52322011-03-25 00:43:55 +00003401 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003402 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003403 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003404}
3405
Richard Smith07fc6572011-10-22 21:10:00 +00003406bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003407VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003408 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003409 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003410 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003411
Nate Begeman59b5da62009-01-18 03:20:47 +00003412 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003413 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003414
Eli Friedman3edd5a92012-01-03 23:24:20 +00003415 // The number of initializers can be less than the number of
3416 // vector elements. For OpenCL, this can be due to nested vector
3417 // initialization. For GCC compatibility, missing trailing elements
3418 // should be initialized with zeroes.
3419 unsigned CountInits = 0, CountElts = 0;
3420 while (CountElts < NumElements) {
3421 // Handle nested vector initialization.
3422 if (CountInits < NumInits
3423 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3424 APValue v;
3425 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3426 return Error(E);
3427 unsigned vlen = v.getVectorLength();
3428 for (unsigned j = 0; j < vlen; j++)
3429 Elements.push_back(v.getVectorElt(j));
3430 CountElts += vlen;
3431 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003432 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003433 if (CountInits < NumInits) {
3434 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3435 return Error(E);
3436 } else // trailing integer zero.
3437 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3438 Elements.push_back(APValue(sInt));
3439 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003440 } else {
3441 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003442 if (CountInits < NumInits) {
3443 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3444 return Error(E);
3445 } else // trailing float zero.
3446 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3447 Elements.push_back(APValue(f));
3448 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003449 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003450 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003451 }
Richard Smith07fc6572011-10-22 21:10:00 +00003452 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003453}
3454
Richard Smith07fc6572011-10-22 21:10:00 +00003455bool
Richard Smith51201882011-12-30 21:15:51 +00003456VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003457 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003458 QualType EltTy = VT->getElementType();
3459 APValue ZeroElement;
3460 if (EltTy->isIntegerType())
3461 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3462 else
3463 ZeroElement =
3464 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3465
Chris Lattner5f9e2722011-07-23 10:55:15 +00003466 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003467 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003468}
3469
Richard Smith07fc6572011-10-22 21:10:00 +00003470bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003471 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003472 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003473}
3474
Nate Begeman59b5da62009-01-18 03:20:47 +00003475//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003476// Array Evaluation
3477//===----------------------------------------------------------------------===//
3478
3479namespace {
3480 class ArrayExprEvaluator
3481 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003482 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003483 APValue &Result;
3484 public:
3485
Richard Smith180f4792011-11-10 06:34:14 +00003486 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3487 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003488
3489 bool Success(const APValue &V, const Expr *E) {
3490 assert(V.isArray() && "Expected array type");
3491 Result = V;
3492 return true;
3493 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003494
Richard Smith51201882011-12-30 21:15:51 +00003495 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003496 const ConstantArrayType *CAT =
3497 Info.Ctx.getAsConstantArrayType(E->getType());
3498 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003499 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003500
3501 Result = APValue(APValue::UninitArray(), 0,
3502 CAT->getSize().getZExtValue());
3503 if (!Result.hasArrayFiller()) return true;
3504
Richard Smith51201882011-12-30 21:15:51 +00003505 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003506 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003507 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003508 ImplicitValueInitExpr VIE(CAT->getElementType());
3509 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3510 Subobject, &VIE);
3511 }
3512
Richard Smithcc5d4f62011-11-07 09:22:26 +00003513 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003514 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003515 };
3516} // end anonymous namespace
3517
Richard Smith180f4792011-11-10 06:34:14 +00003518static bool EvaluateArray(const Expr *E, const LValue &This,
3519 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003520 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003521 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003522}
3523
3524bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3525 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3526 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003527 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003528
Richard Smith974c5f92011-12-22 01:07:19 +00003529 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3530 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003531 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003532 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3533 LValue LV;
3534 if (!EvaluateLValue(E->getInit(0), LV, Info))
3535 return false;
3536 uint64_t NumElements = CAT->getSize().getZExtValue();
3537 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3538
3539 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003540 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003541 for (uint64_t I = 0; I < NumElements; ++I) {
3542 CCValue Char;
3543 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
Richard Smith745f5142012-01-27 01:14:48 +00003544 CAT->getElementType(), LV, Char) ||
3545 !CheckConstantExpression(Info, E->getInit(0), Char,
3546 Result.getArrayInitializedElt(I)) ||
3547 !HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
Richard Smithb4e85ed2012-01-06 16:39:00 +00003548 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003549 return false;
3550 }
3551 return true;
3552 }
3553
Richard Smith745f5142012-01-27 01:14:48 +00003554 bool Success = true;
3555
Richard Smithcc5d4f62011-11-07 09:22:26 +00003556 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3557 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003558 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003559 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003560 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003561 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003562 I != End; ++I, ++Index) {
3563 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
Richard Smith745f5142012-01-27 01:14:48 +00003564 Info, Subobject, cast<Expr>(*I)) ||
3565 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3566 CAT->getElementType(), 1)) {
3567 if (!Info.keepEvaluatingAfterFailure())
3568 return false;
3569 Success = false;
3570 }
Richard Smith180f4792011-11-10 06:34:14 +00003571 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003572
Richard Smith745f5142012-01-27 01:14:48 +00003573 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003574 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003575 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3576 // but sometimes does:
3577 // struct S { constexpr S() : p(&p) {} void *p; };
3578 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003579 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith745f5142012-01-27 01:14:48 +00003580 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003581}
3582
Richard Smithe24f5fc2011-11-17 22:56:20 +00003583bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3584 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3585 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003586 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003587
Richard Smithec789162012-01-12 18:54:33 +00003588 bool HadZeroInit = !Result.isUninit();
3589 if (!HadZeroInit)
3590 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003591 if (!Result.hasArrayFiller())
3592 return true;
3593
3594 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003595
Richard Smith51201882011-12-30 21:15:51 +00003596 bool ZeroInit = E->requiresZeroInitialization();
3597 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003598 if (HadZeroInit)
3599 return true;
3600
Richard Smith51201882011-12-30 21:15:51 +00003601 if (ZeroInit) {
3602 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003603 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003604 ImplicitValueInitExpr VIE(CAT->getElementType());
3605 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3606 Subobject, &VIE);
3607 }
3608
Richard Smith61802452011-12-22 02:22:31 +00003609 const CXXRecordDecl *RD = FD->getParent();
3610 if (RD->isUnion())
3611 Result.getArrayFiller() = APValue((FieldDecl*)0);
3612 else
3613 Result.getArrayFiller() =
3614 APValue(APValue::UninitStruct(), RD->getNumBases(),
3615 std::distance(RD->field_begin(), RD->field_end()));
3616 return true;
3617 }
3618
Richard Smithe24f5fc2011-11-17 22:56:20 +00003619 const FunctionDecl *Definition = 0;
3620 FD->getBody(Definition);
3621
Richard Smithc1c5f272011-12-13 06:39:58 +00003622 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3623 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003624
3625 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3626 // but sometimes does:
3627 // struct S { constexpr S() : p(&p) {} void *p; };
3628 // S s[10];
3629 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003630 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003631
Richard Smithec789162012-01-12 18:54:33 +00003632 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003633 ImplicitValueInitExpr VIE(CAT->getElementType());
3634 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3635 &VIE))
3636 return false;
3637 }
3638
Richard Smithe24f5fc2011-11-17 22:56:20 +00003639 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003640 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003641 cast<CXXConstructorDecl>(Definition),
3642 Info, Result.getArrayFiller());
3643}
3644
Richard Smithcc5d4f62011-11-07 09:22:26 +00003645//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003646// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003647//
3648// As a GNU extension, we support casting pointers to sufficiently-wide integer
3649// types and back in constant folding. Integer values are thus represented
3650// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003651//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003652
3653namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003654class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003655 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003656 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003657public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003658 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003659 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003660
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003661 bool Success(const llvm::APSInt &SI, const Expr *E) {
3662 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003663 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003664 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003665 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003666 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003667 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003668 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003669 return true;
3670 }
3671
Daniel Dunbar131eb432009-02-19 09:06:44 +00003672 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003673 assert(E->getType()->isIntegralOrEnumerationType() &&
3674 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003675 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003676 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003677 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003678 Result.getInt().setIsUnsigned(
3679 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003680 return true;
3681 }
3682
3683 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003684 assert(E->getType()->isIntegralOrEnumerationType() &&
3685 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003686 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003687 return true;
3688 }
3689
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003690 bool Success(CharUnits Size, const Expr *E) {
3691 return Success(Size.getQuantity(), E);
3692 }
3693
Richard Smith47a1eed2011-10-29 20:57:55 +00003694 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003695 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003696 Result = V;
3697 return true;
3698 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003699 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003700 }
Mike Stump1eb44332009-09-09 15:08:12 +00003701
Richard Smith51201882011-12-30 21:15:51 +00003702 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003703
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003704 //===--------------------------------------------------------------------===//
3705 // Visitor Methods
3706 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003707
Chris Lattner4c4867e2008-07-12 00:38:25 +00003708 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003709 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003710 }
3711 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003712 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003713 }
Eli Friedman04309752009-11-24 05:28:59 +00003714
3715 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3716 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003717 if (CheckReferencedDecl(E, E->getDecl()))
3718 return true;
3719
3720 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003721 }
3722 bool VisitMemberExpr(const MemberExpr *E) {
3723 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003724 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003725 return true;
3726 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003727
3728 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003729 }
3730
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003731 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003732 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003733 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003734 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003735
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003736 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003737 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003738
Anders Carlsson3068d112008-11-16 19:01:22 +00003739 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003740 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003741 }
Mike Stump1eb44332009-09-09 15:08:12 +00003742
Richard Smithf10d9172011-10-11 21:43:33 +00003743 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003744 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003745 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003746 }
3747
Sebastian Redl64b45f72009-01-05 20:52:13 +00003748 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003749 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003750 }
3751
Francois Pichet6ad6f282010-12-07 00:08:36 +00003752 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3753 return Success(E->getValue(), E);
3754 }
3755
John Wiegley21ff2e52011-04-28 00:16:57 +00003756 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3757 return Success(E->getValue(), E);
3758 }
3759
John Wiegley55262202011-04-25 06:54:41 +00003760 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3761 return Success(E->getValue(), E);
3762 }
3763
Eli Friedman722c7172009-02-28 03:59:05 +00003764 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003765 bool VisitUnaryImag(const UnaryOperator *E);
3766
Sebastian Redl295995c2010-09-10 20:55:47 +00003767 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003768 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003769
Chris Lattnerfcee0012008-07-11 21:24:13 +00003770private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003771 CharUnits GetAlignOfExpr(const Expr *E);
3772 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003773 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003774 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003775 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003776};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003777} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003778
Richard Smithc49bd112011-10-28 17:51:58 +00003779/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3780/// produce either the integer value or a pointer.
3781///
3782/// GCC has a heinous extension which folds casts between pointer types and
3783/// pointer-sized integral types. We support this by allowing the evaluation of
3784/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3785/// Some simple arithmetic on such values is supported (they are treated much
3786/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003787static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003788 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003789 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003790 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003791}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003792
Richard Smithf48fdb02011-12-09 22:58:01 +00003793static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003794 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003795 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003796 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003797 if (!Val.isInt()) {
3798 // FIXME: It would be better to produce the diagnostic for casting
3799 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003800 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003801 return false;
3802 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003803 Result = Val.getInt();
3804 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003805}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003806
Richard Smithf48fdb02011-12-09 22:58:01 +00003807/// Check whether the given declaration can be directly converted to an integral
3808/// rvalue. If not, no diagnostic is produced; there are other things we can
3809/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003810bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003811 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003812 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003813 // Check for signedness/width mismatches between E type and ECD value.
3814 bool SameSign = (ECD->getInitVal().isSigned()
3815 == E->getType()->isSignedIntegerOrEnumerationType());
3816 bool SameWidth = (ECD->getInitVal().getBitWidth()
3817 == Info.Ctx.getIntWidth(E->getType()));
3818 if (SameSign && SameWidth)
3819 return Success(ECD->getInitVal(), E);
3820 else {
3821 // Get rid of mismatch (otherwise Success assertions will fail)
3822 // by computing a new value matching the type of E.
3823 llvm::APSInt Val = ECD->getInitVal();
3824 if (!SameSign)
3825 Val.setIsSigned(!ECD->getInitVal().isSigned());
3826 if (!SameWidth)
3827 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3828 return Success(Val, E);
3829 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003830 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003831 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003832}
3833
Chris Lattnera4d55d82008-10-06 06:40:35 +00003834/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3835/// as GCC.
3836static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3837 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003838 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003839 enum gcc_type_class {
3840 no_type_class = -1,
3841 void_type_class, integer_type_class, char_type_class,
3842 enumeral_type_class, boolean_type_class,
3843 pointer_type_class, reference_type_class, offset_type_class,
3844 real_type_class, complex_type_class,
3845 function_type_class, method_type_class,
3846 record_type_class, union_type_class,
3847 array_type_class, string_type_class,
3848 lang_type_class
3849 };
Mike Stump1eb44332009-09-09 15:08:12 +00003850
3851 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003852 // ideal, however it is what gcc does.
3853 if (E->getNumArgs() == 0)
3854 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003855
Chris Lattnera4d55d82008-10-06 06:40:35 +00003856 QualType ArgTy = E->getArg(0)->getType();
3857 if (ArgTy->isVoidType())
3858 return void_type_class;
3859 else if (ArgTy->isEnumeralType())
3860 return enumeral_type_class;
3861 else if (ArgTy->isBooleanType())
3862 return boolean_type_class;
3863 else if (ArgTy->isCharType())
3864 return string_type_class; // gcc doesn't appear to use char_type_class
3865 else if (ArgTy->isIntegerType())
3866 return integer_type_class;
3867 else if (ArgTy->isPointerType())
3868 return pointer_type_class;
3869 else if (ArgTy->isReferenceType())
3870 return reference_type_class;
3871 else if (ArgTy->isRealType())
3872 return real_type_class;
3873 else if (ArgTy->isComplexType())
3874 return complex_type_class;
3875 else if (ArgTy->isFunctionType())
3876 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003877 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003878 return record_type_class;
3879 else if (ArgTy->isUnionType())
3880 return union_type_class;
3881 else if (ArgTy->isArrayType())
3882 return array_type_class;
3883 else if (ArgTy->isUnionType())
3884 return union_type_class;
3885 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003886 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003887}
3888
Richard Smith80d4b552011-12-28 19:48:30 +00003889/// EvaluateBuiltinConstantPForLValue - Determine the result of
3890/// __builtin_constant_p when applied to the given lvalue.
3891///
3892/// An lvalue is only "constant" if it is a pointer or reference to the first
3893/// character of a string literal.
3894template<typename LValue>
3895static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3896 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3897 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3898}
3899
3900/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3901/// GCC as we can manage.
3902static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3903 QualType ArgType = Arg->getType();
3904
3905 // __builtin_constant_p always has one operand. The rules which gcc follows
3906 // are not precisely documented, but are as follows:
3907 //
3908 // - If the operand is of integral, floating, complex or enumeration type,
3909 // and can be folded to a known value of that type, it returns 1.
3910 // - If the operand and can be folded to a pointer to the first character
3911 // of a string literal (or such a pointer cast to an integral type), it
3912 // returns 1.
3913 //
3914 // Otherwise, it returns 0.
3915 //
3916 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3917 // its support for this does not currently work.
3918 if (ArgType->isIntegralOrEnumerationType()) {
3919 Expr::EvalResult Result;
3920 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3921 return false;
3922
3923 APValue &V = Result.Val;
3924 if (V.getKind() == APValue::Int)
3925 return true;
3926
3927 return EvaluateBuiltinConstantPForLValue(V);
3928 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3929 return Arg->isEvaluatable(Ctx);
3930 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3931 LValue LV;
3932 Expr::EvalStatus Status;
3933 EvalInfo Info(Ctx, Status);
3934 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3935 : EvaluatePointer(Arg, LV, Info)) &&
3936 !Status.HasSideEffects)
3937 return EvaluateBuiltinConstantPForLValue(LV);
3938 }
3939
3940 // Anything else isn't considered to be sufficiently constant.
3941 return false;
3942}
3943
John McCall42c8f872010-05-10 23:27:23 +00003944/// Retrieves the "underlying object type" of the given expression,
3945/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003946QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3947 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3948 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003949 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003950 } else if (const Expr *E = B.get<const Expr*>()) {
3951 if (isa<CompoundLiteralExpr>(E))
3952 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003953 }
3954
3955 return QualType();
3956}
3957
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003958bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003959 // TODO: Perhaps we should let LLVM lower this?
3960 LValue Base;
3961 if (!EvaluatePointer(E->getArg(0), Base, Info))
3962 return false;
3963
3964 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003965 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003966
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003967 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003968 if (T.isNull() ||
3969 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00003970 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00003971 T->isVariablyModifiedType() ||
3972 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003973 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00003974
3975 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3976 CharUnits Offset = Base.getLValueOffset();
3977
3978 if (!Offset.isNegative() && Offset <= Size)
3979 Size -= Offset;
3980 else
3981 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003982 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00003983}
3984
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003985bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003986 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00003987 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003988 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003989
3990 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00003991 if (TryEvaluateBuiltinObjectSize(E))
3992 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00003993
Eric Christopherb2aaf512010-01-19 22:58:35 +00003994 // If evaluating the argument has side-effects we can't determine
3995 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00003996 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003997 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00003998 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003999 return Success(0, E);
4000 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004001
Richard Smithf48fdb02011-12-09 22:58:01 +00004002 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004003 }
4004
Chris Lattner019f4e82008-10-06 05:28:25 +00004005 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004006 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004007
Richard Smith80d4b552011-12-28 19:48:30 +00004008 case Builtin::BI__builtin_constant_p:
4009 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004010
Chris Lattner21fb98e2009-09-23 06:06:36 +00004011 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004012 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004013 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004014 return Success(Operand, E);
4015 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004016
4017 case Builtin::BI__builtin_expect:
4018 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004019
Douglas Gregor5726d402010-09-10 06:27:15 +00004020 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004021 // A call to strlen is not a constant expression.
4022 if (Info.getLangOpts().CPlusPlus0x)
4023 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4024 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4025 else
4026 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4027 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004028 case Builtin::BI__builtin_strlen:
4029 // As an extension, we support strlen() and __builtin_strlen() as constant
4030 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004031 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004032 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4033 // The string literal may have embedded null characters. Find the first
4034 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004035 StringRef Str = S->getString();
4036 StringRef::size_type Pos = Str.find(0);
4037 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004038 Str = Str.substr(0, Pos);
4039
4040 return Success(Str.size(), E);
4041 }
4042
Richard Smithf48fdb02011-12-09 22:58:01 +00004043 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004044
4045 case Builtin::BI__atomic_is_lock_free: {
4046 APSInt SizeVal;
4047 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4048 return false;
4049
4050 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4051 // of two less than the maximum inline atomic width, we know it is
4052 // lock-free. If the size isn't a power of two, or greater than the
4053 // maximum alignment where we promote atomics, we know it is not lock-free
4054 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4055 // the answer can only be determined at runtime; for example, 16-byte
4056 // atomics have lock-free implementations on some, but not all,
4057 // x86-64 processors.
4058
4059 // Check power-of-two.
4060 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4061 if (!Size.isPowerOfTwo())
4062#if 0
4063 // FIXME: Suppress this folding until the ABI for the promotion width
4064 // settles.
4065 return Success(0, E);
4066#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004067 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004068#endif
4069
4070#if 0
4071 // Check against promotion width.
4072 // FIXME: Suppress this folding until the ABI for the promotion width
4073 // settles.
4074 unsigned PromoteWidthBits =
4075 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4076 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4077 return Success(0, E);
4078#endif
4079
4080 // Check against inlining width.
4081 unsigned InlineWidthBits =
4082 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4083 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4084 return Success(1, E);
4085
Richard Smithf48fdb02011-12-09 22:58:01 +00004086 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004087 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004088 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004089}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004090
Richard Smith625b8072011-10-31 01:37:14 +00004091static bool HasSameBase(const LValue &A, const LValue &B) {
4092 if (!A.getLValueBase())
4093 return !B.getLValueBase();
4094 if (!B.getLValueBase())
4095 return false;
4096
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004097 if (A.getLValueBase().getOpaqueValue() !=
4098 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004099 const Decl *ADecl = GetLValueBaseDecl(A);
4100 if (!ADecl)
4101 return false;
4102 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004103 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004104 return false;
4105 }
4106
4107 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00004108 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00004109}
4110
Chris Lattnerb542afe2008-07-11 19:10:17 +00004111bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004112 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004113 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004114
John McCall2de56d12010-08-25 11:45:40 +00004115 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004116 VisitIgnoredValue(E->getLHS());
4117 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004118 }
4119
4120 if (E->isLogicalOp()) {
4121 // These need to be handled specially because the operands aren't
4122 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004123 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004124
Richard Smithc49bd112011-10-28 17:51:58 +00004125 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004126 // We were able to evaluate the LHS, see if we can get away with not
4127 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004128 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004129 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004130
Richard Smithc49bd112011-10-28 17:51:58 +00004131 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004132 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004133 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004134 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004135 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004136 }
4137 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004138 // FIXME: If both evaluations fail, we should produce the diagnostic from
4139 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4140 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00004141 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004142 // We can't evaluate the LHS; however, sometimes the result
4143 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00004144 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004145 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004146 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00004147 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004148
4149 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004150 }
4151 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004152 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004153
Eli Friedmana6afa762008-11-13 06:09:17 +00004154 return false;
4155 }
4156
Anders Carlsson286f85e2008-11-16 07:17:21 +00004157 QualType LHSTy = E->getLHS()->getType();
4158 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004159
4160 if (LHSTy->isAnyComplexType()) {
4161 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004162 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004163
Richard Smith745f5142012-01-27 01:14:48 +00004164 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4165 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004166 return false;
4167
Richard Smith745f5142012-01-27 01:14:48 +00004168 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004169 return false;
4170
4171 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004172 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004173 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004174 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004175 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4176
John McCall2de56d12010-08-25 11:45:40 +00004177 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004178 return Success((CR_r == APFloat::cmpEqual &&
4179 CR_i == APFloat::cmpEqual), E);
4180 else {
John McCall2de56d12010-08-25 11:45:40 +00004181 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004182 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004183 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004184 CR_r == APFloat::cmpLessThan ||
4185 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004186 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004187 CR_i == APFloat::cmpLessThan ||
4188 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004189 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004190 } else {
John McCall2de56d12010-08-25 11:45:40 +00004191 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004192 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4193 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4194 else {
John McCall2de56d12010-08-25 11:45:40 +00004195 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004196 "Invalid compex comparison.");
4197 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4198 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4199 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004200 }
4201 }
Mike Stump1eb44332009-09-09 15:08:12 +00004202
Anders Carlsson286f85e2008-11-16 07:17:21 +00004203 if (LHSTy->isRealFloatingType() &&
4204 RHSTy->isRealFloatingType()) {
4205 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004206
Richard Smith745f5142012-01-27 01:14:48 +00004207 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4208 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004209 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004210
Richard Smith745f5142012-01-27 01:14:48 +00004211 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004212 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004213
Anders Carlsson286f85e2008-11-16 07:17:21 +00004214 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004215
Anders Carlsson286f85e2008-11-16 07:17:21 +00004216 switch (E->getOpcode()) {
4217 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004218 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004219 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004220 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004221 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004222 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004223 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004224 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004225 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004226 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004227 E);
John McCall2de56d12010-08-25 11:45:40 +00004228 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004229 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004230 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004231 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004232 || CR == APFloat::cmpLessThan
4233 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004234 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004235 }
Mike Stump1eb44332009-09-09 15:08:12 +00004236
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004237 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004238 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004239 LValue LHSValue, RHSValue;
4240
4241 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4242 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004243 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004244
Richard Smith745f5142012-01-27 01:14:48 +00004245 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004246 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004247
Richard Smith625b8072011-10-31 01:37:14 +00004248 // Reject differing bases from the normal codepath; we special-case
4249 // comparisons to null.
4250 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004251 if (E->getOpcode() == BO_Sub) {
4252 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004253 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4254 return false;
4255 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4256 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4257 if (!LHSExpr || !RHSExpr)
4258 return false;
4259 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4260 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4261 if (!LHSAddrExpr || !RHSAddrExpr)
4262 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004263 // Make sure both labels come from the same function.
4264 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4265 RHSAddrExpr->getLabel()->getDeclContext())
4266 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004267 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4268 return true;
4269 }
Richard Smith9e36b532011-10-31 05:11:32 +00004270 // Inequalities and subtractions between unrelated pointers have
4271 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004272 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004273 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004274 // A constant address may compare equal to the address of a symbol.
4275 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004276 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004277 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4278 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004279 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004280 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00004281 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00004282 // distinct. However, we do know that the address of a literal will be
4283 // non-null.
4284 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4285 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004286 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004287 // We can't tell whether weak symbols will end up pointing to the same
4288 // object.
4289 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004290 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004291 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004292 // (Note that clang defaults to -fmerge-all-constants, which can
4293 // lead to inconsistent results for comparisons involving the address
4294 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004295 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004296 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004297
Richard Smithcc5d4f62011-11-07 09:22:26 +00004298 // FIXME: Implement the C++11 restrictions:
4299 // - Pointer subtractions must be on elements of the same array.
4300 // - Pointer comparisons must be between members with the same access.
4301
John McCall2de56d12010-08-25 11:45:40 +00004302 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00004303 QualType Type = E->getLHS()->getType();
4304 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004305
Richard Smith180f4792011-11-10 06:34:14 +00004306 CharUnits ElementSize;
4307 if (!HandleSizeof(Info, ElementType, ElementSize))
4308 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004309
Richard Smith180f4792011-11-10 06:34:14 +00004310 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00004311 RHSValue.getLValueOffset();
4312 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004313 }
Richard Smith625b8072011-10-31 01:37:14 +00004314
4315 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4316 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4317 switch (E->getOpcode()) {
4318 default: llvm_unreachable("missing comparison operator");
4319 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4320 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4321 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4322 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4323 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4324 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004325 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004326 }
4327 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004328 if (!LHSTy->isIntegralOrEnumerationType() ||
4329 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004330 // We can't continue from here for non-integral types.
4331 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004332 }
4333
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004334 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004335 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004336
4337 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4338 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004339 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004340
Richard Smith745f5142012-01-27 01:14:48 +00004341 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004342 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004343
Richard Smith47a1eed2011-10-29 20:57:55 +00004344 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004345
4346 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004347 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004348 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4349 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004350 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004351 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004352 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004353 LHSVal.getLValueOffset() -= AdditionalOffset;
4354 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004355 return true;
4356 }
4357
4358 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004359 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004360 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004361 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4362 LHSVal.getInt().getZExtValue());
4363 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004364 return true;
4365 }
4366
Eli Friedman65639282012-01-04 23:13:47 +00004367 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4368 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004369 if (!LHSVal.getLValueOffset().isZero() ||
4370 !RHSVal.getLValueOffset().isZero())
4371 return false;
4372 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4373 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4374 if (!LHSExpr || !RHSExpr)
4375 return false;
4376 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4377 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4378 if (!LHSAddrExpr || !RHSAddrExpr)
4379 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004380 // Make sure both labels come from the same function.
4381 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4382 RHSAddrExpr->getLabel()->getDeclContext())
4383 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004384 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4385 return true;
4386 }
4387
Eli Friedman42edd0d2009-03-24 01:14:50 +00004388 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004389 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004390 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004391
Richard Smithc49bd112011-10-28 17:51:58 +00004392 APSInt &LHS = LHSVal.getInt();
4393 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004394
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004395 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004396 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004397 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004398 case BO_Mul: return Success(LHS * RHS, E);
4399 case BO_Add: return Success(LHS + RHS, E);
4400 case BO_Sub: return Success(LHS - RHS, E);
4401 case BO_And: return Success(LHS & RHS, E);
4402 case BO_Xor: return Success(LHS ^ RHS, E);
4403 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004404 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00004405 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004406 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00004407 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004408 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004409 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004410 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00004411 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004412 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00004413 // During constant-folding, a negative shift is an opposite shift.
4414 if (RHS.isSigned() && RHS.isNegative()) {
4415 RHS = -RHS;
4416 goto shift_right;
4417 }
4418
4419 shift_left:
4420 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00004421 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4422 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004423 }
John McCall2de56d12010-08-25 11:45:40 +00004424 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00004425 // During constant-folding, a negative shift is an opposite shift.
4426 if (RHS.isSigned() && RHS.isNegative()) {
4427 RHS = -RHS;
4428 goto shift_left;
4429 }
4430
4431 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00004432 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00004433 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4434 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004435 }
Mike Stump1eb44332009-09-09 15:08:12 +00004436
Richard Smithc49bd112011-10-28 17:51:58 +00004437 case BO_LT: return Success(LHS < RHS, E);
4438 case BO_GT: return Success(LHS > RHS, E);
4439 case BO_LE: return Success(LHS <= RHS, E);
4440 case BO_GE: return Success(LHS >= RHS, E);
4441 case BO_EQ: return Success(LHS == RHS, E);
4442 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004443 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004444}
4445
Ken Dyck8b752f12010-01-27 17:10:57 +00004446CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004447 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4448 // the result is the size of the referenced type."
4449 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4450 // result shall be the alignment of the referenced type."
4451 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4452 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004453
4454 // __alignof is defined to return the preferred alignment.
4455 return Info.Ctx.toCharUnitsFromBits(
4456 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004457}
4458
Ken Dyck8b752f12010-01-27 17:10:57 +00004459CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004460 E = E->IgnoreParens();
4461
4462 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004463 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004464 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004465 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4466 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004467
Chris Lattneraf707ab2009-01-24 21:53:27 +00004468 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004469 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4470 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004471
Chris Lattnere9feb472009-01-24 21:09:06 +00004472 return GetAlignOfType(E->getType());
4473}
4474
4475
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004476/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4477/// a result as the expression's type.
4478bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4479 const UnaryExprOrTypeTraitExpr *E) {
4480 switch(E->getKind()) {
4481 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004482 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004483 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004484 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004485 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004486 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004487
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004488 case UETT_VecStep: {
4489 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004490
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004491 if (Ty->isVectorType()) {
4492 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004493
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004494 // The vec_step built-in functions that take a 3-component
4495 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4496 if (n == 3)
4497 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004498
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004499 return Success(n, E);
4500 } else
4501 return Success(1, E);
4502 }
4503
4504 case UETT_SizeOf: {
4505 QualType SrcTy = E->getTypeOfArgument();
4506 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4507 // the result is the size of the referenced type."
4508 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4509 // result shall be the alignment of the referenced type."
4510 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4511 SrcTy = Ref->getPointeeType();
4512
Richard Smith180f4792011-11-10 06:34:14 +00004513 CharUnits Sizeof;
4514 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004515 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004516 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004517 }
4518 }
4519
4520 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004521}
4522
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004523bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004524 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004525 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004526 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004527 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004528 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004529 for (unsigned i = 0; i != n; ++i) {
4530 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4531 switch (ON.getKind()) {
4532 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004533 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004534 APSInt IdxResult;
4535 if (!EvaluateInteger(Idx, IdxResult, Info))
4536 return false;
4537 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4538 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004539 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004540 CurrentType = AT->getElementType();
4541 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4542 Result += IdxResult.getSExtValue() * ElementSize;
4543 break;
4544 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004545
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004546 case OffsetOfExpr::OffsetOfNode::Field: {
4547 FieldDecl *MemberDecl = ON.getField();
4548 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004549 if (!RT)
4550 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004551 RecordDecl *RD = RT->getDecl();
4552 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004553 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004554 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004555 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004556 CurrentType = MemberDecl->getType().getNonReferenceType();
4557 break;
4558 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004559
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004560 case OffsetOfExpr::OffsetOfNode::Identifier:
4561 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004562
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004563 case OffsetOfExpr::OffsetOfNode::Base: {
4564 CXXBaseSpecifier *BaseSpec = ON.getBase();
4565 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004566 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004567
4568 // Find the layout of the class whose base we are looking into.
4569 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004570 if (!RT)
4571 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004572 RecordDecl *RD = RT->getDecl();
4573 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4574
4575 // Find the base class itself.
4576 CurrentType = BaseSpec->getType();
4577 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4578 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004579 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004580
4581 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004582 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004583 break;
4584 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004585 }
4586 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004587 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004588}
4589
Chris Lattnerb542afe2008-07-11 19:10:17 +00004590bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004591 switch (E->getOpcode()) {
4592 default:
4593 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4594 // See C99 6.6p3.
4595 return Error(E);
4596 case UO_Extension:
4597 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4598 // If so, we could clear the diagnostic ID.
4599 return Visit(E->getSubExpr());
4600 case UO_Plus:
4601 // The result is just the value.
4602 return Visit(E->getSubExpr());
4603 case UO_Minus: {
4604 if (!Visit(E->getSubExpr()))
4605 return false;
4606 if (!Result.isInt()) return Error(E);
4607 return Success(-Result.getInt(), E);
4608 }
4609 case UO_Not: {
4610 if (!Visit(E->getSubExpr()))
4611 return false;
4612 if (!Result.isInt()) return Error(E);
4613 return Success(~Result.getInt(), E);
4614 }
4615 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004616 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004617 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004618 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004619 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004620 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004621 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004622}
Mike Stump1eb44332009-09-09 15:08:12 +00004623
Chris Lattner732b2232008-07-12 01:15:53 +00004624/// HandleCast - This is used to evaluate implicit or explicit casts where the
4625/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004626bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4627 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004628 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004629 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004630
Eli Friedman46a52322011-03-25 00:43:55 +00004631 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004632 case CK_BaseToDerived:
4633 case CK_DerivedToBase:
4634 case CK_UncheckedDerivedToBase:
4635 case CK_Dynamic:
4636 case CK_ToUnion:
4637 case CK_ArrayToPointerDecay:
4638 case CK_FunctionToPointerDecay:
4639 case CK_NullToPointer:
4640 case CK_NullToMemberPointer:
4641 case CK_BaseToDerivedMemberPointer:
4642 case CK_DerivedToBaseMemberPointer:
4643 case CK_ConstructorConversion:
4644 case CK_IntegralToPointer:
4645 case CK_ToVoid:
4646 case CK_VectorSplat:
4647 case CK_IntegralToFloating:
4648 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004649 case CK_CPointerToObjCPointerCast:
4650 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004651 case CK_AnyPointerToBlockPointerCast:
4652 case CK_ObjCObjectLValueCast:
4653 case CK_FloatingRealToComplex:
4654 case CK_FloatingComplexToReal:
4655 case CK_FloatingComplexCast:
4656 case CK_FloatingComplexToIntegralComplex:
4657 case CK_IntegralRealToComplex:
4658 case CK_IntegralComplexCast:
4659 case CK_IntegralComplexToFloatingComplex:
4660 llvm_unreachable("invalid cast kind for integral value");
4661
Eli Friedmane50c2972011-03-25 19:07:11 +00004662 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004663 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004664 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00004665 case CK_ARCProduceObject:
4666 case CK_ARCConsumeObject:
4667 case CK_ARCReclaimReturnedObject:
4668 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004669 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004670
Richard Smith7d580a42012-01-17 21:17:26 +00004671 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00004672 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00004673 case CK_AtomicToNonAtomic:
4674 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00004675 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004676 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004677
4678 case CK_MemberPointerToBoolean:
4679 case CK_PointerToBoolean:
4680 case CK_IntegralToBoolean:
4681 case CK_FloatingToBoolean:
4682 case CK_FloatingComplexToBoolean:
4683 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004684 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004685 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004686 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004687 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004688 }
4689
Eli Friedman46a52322011-03-25 00:43:55 +00004690 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004691 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004692 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004693
Eli Friedmanbe265702009-02-20 01:15:07 +00004694 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00004695 // Allow casts of address-of-label differences if they are no-ops
4696 // or narrowing. (The narrowing case isn't actually guaranteed to
4697 // be constant-evaluatable except in some narrow cases which are hard
4698 // to detect here. We let it through on the assumption the user knows
4699 // what they are doing.)
4700 if (Result.isAddrLabelDiff())
4701 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00004702 // Only allow casts of lvalues if they are lossless.
4703 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4704 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004705
Daniel Dunbardd211642009-02-19 22:24:01 +00004706 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004707 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00004708 }
Mike Stump1eb44332009-09-09 15:08:12 +00004709
Eli Friedman46a52322011-03-25 00:43:55 +00004710 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00004711 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4712
John McCallefdb83e2010-05-07 21:00:08 +00004713 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00004714 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004715 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00004716
Daniel Dunbardd211642009-02-19 22:24:01 +00004717 if (LV.getLValueBase()) {
4718 // Only allow based lvalue casts if they are lossless.
4719 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00004720 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004721
Richard Smithb755a9d2011-11-16 07:18:12 +00004722 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004723 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00004724 return true;
4725 }
4726
Ken Dycka7305832010-01-15 12:37:54 +00004727 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4728 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00004729 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00004730 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004731
Eli Friedman46a52322011-03-25 00:43:55 +00004732 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00004733 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00004734 if (!EvaluateComplex(SubExpr, C, Info))
4735 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00004736 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00004737 }
Eli Friedman2217c872009-02-22 11:46:18 +00004738
Eli Friedman46a52322011-03-25 00:43:55 +00004739 case CK_FloatingToIntegral: {
4740 APFloat F(0.0);
4741 if (!EvaluateFloat(SubExpr, F, Info))
4742 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00004743
Richard Smithc1c5f272011-12-13 06:39:58 +00004744 APSInt Value;
4745 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4746 return false;
4747 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00004748 }
4749 }
Mike Stump1eb44332009-09-09 15:08:12 +00004750
Eli Friedman46a52322011-03-25 00:43:55 +00004751 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004752}
Anders Carlsson2bad1682008-07-08 14:30:00 +00004753
Eli Friedman722c7172009-02-28 03:59:05 +00004754bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4755 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004756 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004757 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4758 return false;
4759 if (!LV.isComplexInt())
4760 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004761 return Success(LV.getComplexIntReal(), E);
4762 }
4763
4764 return Visit(E->getSubExpr());
4765}
4766
Eli Friedman664a1042009-02-27 04:45:43 +00004767bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004768 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004769 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004770 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4771 return false;
4772 if (!LV.isComplexInt())
4773 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004774 return Success(LV.getComplexIntImag(), E);
4775 }
4776
Richard Smith8327fad2011-10-24 18:44:57 +00004777 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004778 return Success(0, E);
4779}
4780
Douglas Gregoree8aff02011-01-04 17:33:58 +00004781bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4782 return Success(E->getPackLength(), E);
4783}
4784
Sebastian Redl295995c2010-09-10 20:55:47 +00004785bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4786 return Success(E->getValue(), E);
4787}
4788
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004789//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004790// Float Evaluation
4791//===----------------------------------------------------------------------===//
4792
4793namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004794class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004795 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004796 APFloat &Result;
4797public:
4798 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004799 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004800
Richard Smith47a1eed2011-10-29 20:57:55 +00004801 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004802 Result = V.getFloat();
4803 return true;
4804 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004805
Richard Smith51201882011-12-30 21:15:51 +00004806 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00004807 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4808 return true;
4809 }
4810
Chris Lattner019f4e82008-10-06 05:28:25 +00004811 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004812
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004813 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004814 bool VisitBinaryOperator(const BinaryOperator *E);
4815 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004816 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004817
John McCallabd3a852010-05-07 22:08:54 +00004818 bool VisitUnaryReal(const UnaryOperator *E);
4819 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004820
Richard Smith51201882011-12-30 21:15:51 +00004821 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004822};
4823} // end anonymous namespace
4824
4825static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004826 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004827 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004828}
4829
Jay Foad4ba2a172011-01-12 09:06:06 +00004830static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004831 QualType ResultTy,
4832 const Expr *Arg,
4833 bool SNaN,
4834 llvm::APFloat &Result) {
4835 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4836 if (!S) return false;
4837
4838 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4839
4840 llvm::APInt fill;
4841
4842 // Treat empty strings as if they were zero.
4843 if (S->getString().empty())
4844 fill = llvm::APInt(32, 0);
4845 else if (S->getString().getAsInteger(0, fill))
4846 return false;
4847
4848 if (SNaN)
4849 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4850 else
4851 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4852 return true;
4853}
4854
Chris Lattner019f4e82008-10-06 05:28:25 +00004855bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004856 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004857 default:
4858 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4859
Chris Lattner019f4e82008-10-06 05:28:25 +00004860 case Builtin::BI__builtin_huge_val:
4861 case Builtin::BI__builtin_huge_valf:
4862 case Builtin::BI__builtin_huge_vall:
4863 case Builtin::BI__builtin_inf:
4864 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004865 case Builtin::BI__builtin_infl: {
4866 const llvm::fltSemantics &Sem =
4867 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00004868 Result = llvm::APFloat::getInf(Sem);
4869 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004870 }
Mike Stump1eb44332009-09-09 15:08:12 +00004871
John McCalldb7b72a2010-02-28 13:00:19 +00004872 case Builtin::BI__builtin_nans:
4873 case Builtin::BI__builtin_nansf:
4874 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00004875 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4876 true, Result))
4877 return Error(E);
4878 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00004879
Chris Lattner9e621712008-10-06 06:31:58 +00004880 case Builtin::BI__builtin_nan:
4881 case Builtin::BI__builtin_nanf:
4882 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00004883 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00004884 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00004885 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4886 false, Result))
4887 return Error(E);
4888 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004889
4890 case Builtin::BI__builtin_fabs:
4891 case Builtin::BI__builtin_fabsf:
4892 case Builtin::BI__builtin_fabsl:
4893 if (!EvaluateFloat(E->getArg(0), Result, Info))
4894 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004895
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004896 if (Result.isNegative())
4897 Result.changeSign();
4898 return true;
4899
Mike Stump1eb44332009-09-09 15:08:12 +00004900 case Builtin::BI__builtin_copysign:
4901 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004902 case Builtin::BI__builtin_copysignl: {
4903 APFloat RHS(0.);
4904 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4905 !EvaluateFloat(E->getArg(1), RHS, Info))
4906 return false;
4907 Result.copySign(RHS);
4908 return true;
4909 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004910 }
4911}
4912
John McCallabd3a852010-05-07 22:08:54 +00004913bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004914 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4915 ComplexValue CV;
4916 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4917 return false;
4918 Result = CV.FloatReal;
4919 return true;
4920 }
4921
4922 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00004923}
4924
4925bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004926 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4927 ComplexValue CV;
4928 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4929 return false;
4930 Result = CV.FloatImag;
4931 return true;
4932 }
4933
Richard Smith8327fad2011-10-24 18:44:57 +00004934 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00004935 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4936 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00004937 return true;
4938}
4939
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004940bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004941 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004942 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004943 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004944 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00004945 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004946 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4947 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004948 Result.changeSign();
4949 return true;
4950 }
4951}
Chris Lattner019f4e82008-10-06 05:28:25 +00004952
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004953bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004954 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4955 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00004956
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004957 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00004958 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
4959 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004960 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004961 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004962 return false;
4963
4964 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004965 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004966 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004967 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4968 return true;
John McCall2de56d12010-08-25 11:45:40 +00004969 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004970 Result.add(RHS, APFloat::rmNearestTiesToEven);
4971 return true;
John McCall2de56d12010-08-25 11:45:40 +00004972 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004973 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4974 return true;
John McCall2de56d12010-08-25 11:45:40 +00004975 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004976 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4977 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004978 }
4979}
4980
4981bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4982 Result = E->getValue();
4983 return true;
4984}
4985
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004986bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4987 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00004988
Eli Friedman2a523ee2011-03-25 00:54:52 +00004989 switch (E->getCastKind()) {
4990 default:
Richard Smithc49bd112011-10-28 17:51:58 +00004991 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00004992
4993 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004994 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00004995 return EvaluateInteger(SubExpr, IntResult, Info) &&
4996 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4997 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004998 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004999
5000 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005001 if (!Visit(SubExpr))
5002 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005003 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5004 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005005 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005006
Eli Friedman2a523ee2011-03-25 00:54:52 +00005007 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005008 ComplexValue V;
5009 if (!EvaluateComplex(SubExpr, V, Info))
5010 return false;
5011 Result = V.getComplexFloatReal();
5012 return true;
5013 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005014 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005015}
5016
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005017//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005018// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005019//===----------------------------------------------------------------------===//
5020
5021namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005022class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005023 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005024 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005025
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005026public:
John McCallf4cf1a12010-05-07 17:22:02 +00005027 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005028 : ExprEvaluatorBaseTy(info), Result(Result) {}
5029
Richard Smith47a1eed2011-10-29 20:57:55 +00005030 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005031 Result.setFrom(V);
5032 return true;
5033 }
Mike Stump1eb44332009-09-09 15:08:12 +00005034
Eli Friedman7ead5c72012-01-10 04:58:17 +00005035 bool ZeroInitialization(const Expr *E);
5036
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005037 //===--------------------------------------------------------------------===//
5038 // Visitor Methods
5039 //===--------------------------------------------------------------------===//
5040
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005041 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005042 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005043 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005044 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005045 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005046};
5047} // end anonymous namespace
5048
John McCallf4cf1a12010-05-07 17:22:02 +00005049static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5050 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005051 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005052 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005053}
5054
Eli Friedman7ead5c72012-01-10 04:58:17 +00005055bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005056 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005057 if (ElemTy->isRealFloatingType()) {
5058 Result.makeComplexFloat();
5059 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5060 Result.FloatReal = Zero;
5061 Result.FloatImag = Zero;
5062 } else {
5063 Result.makeComplexInt();
5064 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5065 Result.IntReal = Zero;
5066 Result.IntImag = Zero;
5067 }
5068 return true;
5069}
5070
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005071bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5072 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005073
5074 if (SubExpr->getType()->isRealFloatingType()) {
5075 Result.makeComplexFloat();
5076 APFloat &Imag = Result.FloatImag;
5077 if (!EvaluateFloat(SubExpr, Imag, Info))
5078 return false;
5079
5080 Result.FloatReal = APFloat(Imag.getSemantics());
5081 return true;
5082 } else {
5083 assert(SubExpr->getType()->isIntegerType() &&
5084 "Unexpected imaginary literal.");
5085
5086 Result.makeComplexInt();
5087 APSInt &Imag = Result.IntImag;
5088 if (!EvaluateInteger(SubExpr, Imag, Info))
5089 return false;
5090
5091 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5092 return true;
5093 }
5094}
5095
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005096bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005097
John McCall8786da72010-12-14 17:51:41 +00005098 switch (E->getCastKind()) {
5099 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005100 case CK_BaseToDerived:
5101 case CK_DerivedToBase:
5102 case CK_UncheckedDerivedToBase:
5103 case CK_Dynamic:
5104 case CK_ToUnion:
5105 case CK_ArrayToPointerDecay:
5106 case CK_FunctionToPointerDecay:
5107 case CK_NullToPointer:
5108 case CK_NullToMemberPointer:
5109 case CK_BaseToDerivedMemberPointer:
5110 case CK_DerivedToBaseMemberPointer:
5111 case CK_MemberPointerToBoolean:
5112 case CK_ConstructorConversion:
5113 case CK_IntegralToPointer:
5114 case CK_PointerToIntegral:
5115 case CK_PointerToBoolean:
5116 case CK_ToVoid:
5117 case CK_VectorSplat:
5118 case CK_IntegralCast:
5119 case CK_IntegralToBoolean:
5120 case CK_IntegralToFloating:
5121 case CK_FloatingToIntegral:
5122 case CK_FloatingToBoolean:
5123 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005124 case CK_CPointerToObjCPointerCast:
5125 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005126 case CK_AnyPointerToBlockPointerCast:
5127 case CK_ObjCObjectLValueCast:
5128 case CK_FloatingComplexToReal:
5129 case CK_FloatingComplexToBoolean:
5130 case CK_IntegralComplexToReal:
5131 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005132 case CK_ARCProduceObject:
5133 case CK_ARCConsumeObject:
5134 case CK_ARCReclaimReturnedObject:
5135 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005136 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005137
John McCall8786da72010-12-14 17:51:41 +00005138 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005139 case CK_AtomicToNonAtomic:
5140 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005141 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005142 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005143
5144 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005145 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005146 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005147 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005148
5149 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005150 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005151 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005152 return false;
5153
John McCall8786da72010-12-14 17:51:41 +00005154 Result.makeComplexFloat();
5155 Result.FloatImag = APFloat(Real.getSemantics());
5156 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005157 }
5158
John McCall8786da72010-12-14 17:51:41 +00005159 case CK_FloatingComplexCast: {
5160 if (!Visit(E->getSubExpr()))
5161 return false;
5162
5163 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5164 QualType From
5165 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5166
Richard Smithc1c5f272011-12-13 06:39:58 +00005167 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5168 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005169 }
5170
5171 case CK_FloatingComplexToIntegralComplex: {
5172 if (!Visit(E->getSubExpr()))
5173 return false;
5174
5175 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5176 QualType From
5177 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5178 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005179 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5180 To, Result.IntReal) &&
5181 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5182 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005183 }
5184
5185 case CK_IntegralRealToComplex: {
5186 APSInt &Real = Result.IntReal;
5187 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5188 return false;
5189
5190 Result.makeComplexInt();
5191 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5192 return true;
5193 }
5194
5195 case CK_IntegralComplexCast: {
5196 if (!Visit(E->getSubExpr()))
5197 return false;
5198
5199 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5200 QualType From
5201 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5202
5203 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
5204 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
5205 return true;
5206 }
5207
5208 case CK_IntegralComplexToFloatingComplex: {
5209 if (!Visit(E->getSubExpr()))
5210 return false;
5211
5212 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5213 QualType From
5214 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5215 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005216 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5217 To, Result.FloatReal) &&
5218 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5219 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005220 }
5221 }
5222
5223 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005224}
5225
John McCallf4cf1a12010-05-07 17:22:02 +00005226bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005227 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005228 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5229
Richard Smith745f5142012-01-27 01:14:48 +00005230 bool LHSOK = Visit(E->getLHS());
5231 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005232 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005233
John McCallf4cf1a12010-05-07 17:22:02 +00005234 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005235 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005236 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005237
Daniel Dunbar3f279872009-01-29 01:32:56 +00005238 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5239 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005240 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005241 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005242 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005243 if (Result.isComplexFloat()) {
5244 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5245 APFloat::rmNearestTiesToEven);
5246 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5247 APFloat::rmNearestTiesToEven);
5248 } else {
5249 Result.getComplexIntReal() += RHS.getComplexIntReal();
5250 Result.getComplexIntImag() += RHS.getComplexIntImag();
5251 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005252 break;
John McCall2de56d12010-08-25 11:45:40 +00005253 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005254 if (Result.isComplexFloat()) {
5255 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5256 APFloat::rmNearestTiesToEven);
5257 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5258 APFloat::rmNearestTiesToEven);
5259 } else {
5260 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5261 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5262 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005263 break;
John McCall2de56d12010-08-25 11:45:40 +00005264 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005265 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005266 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005267 APFloat &LHS_r = LHS.getComplexFloatReal();
5268 APFloat &LHS_i = LHS.getComplexFloatImag();
5269 APFloat &RHS_r = RHS.getComplexFloatReal();
5270 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005271
Daniel Dunbar3f279872009-01-29 01:32:56 +00005272 APFloat Tmp = LHS_r;
5273 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5274 Result.getComplexFloatReal() = Tmp;
5275 Tmp = LHS_i;
5276 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5277 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5278
5279 Tmp = LHS_r;
5280 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5281 Result.getComplexFloatImag() = Tmp;
5282 Tmp = LHS_i;
5283 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5284 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5285 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005286 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005287 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005288 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5289 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005290 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005291 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5292 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5293 }
5294 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005295 case BO_Div:
5296 if (Result.isComplexFloat()) {
5297 ComplexValue LHS = Result;
5298 APFloat &LHS_r = LHS.getComplexFloatReal();
5299 APFloat &LHS_i = LHS.getComplexFloatImag();
5300 APFloat &RHS_r = RHS.getComplexFloatReal();
5301 APFloat &RHS_i = RHS.getComplexFloatImag();
5302 APFloat &Res_r = Result.getComplexFloatReal();
5303 APFloat &Res_i = Result.getComplexFloatImag();
5304
5305 APFloat Den = RHS_r;
5306 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5307 APFloat Tmp = RHS_i;
5308 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5309 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5310
5311 Res_r = LHS_r;
5312 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5313 Tmp = LHS_i;
5314 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5315 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5316 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5317
5318 Res_i = LHS_i;
5319 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5320 Tmp = LHS_r;
5321 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5322 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5323 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5324 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005325 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5326 return Error(E, diag::note_expr_divide_by_zero);
5327
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005328 ComplexValue LHS = Result;
5329 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5330 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5331 Result.getComplexIntReal() =
5332 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5333 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5334 Result.getComplexIntImag() =
5335 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5336 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5337 }
5338 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005339 }
5340
John McCallf4cf1a12010-05-07 17:22:02 +00005341 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005342}
5343
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005344bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5345 // Get the operand value into 'Result'.
5346 if (!Visit(E->getSubExpr()))
5347 return false;
5348
5349 switch (E->getOpcode()) {
5350 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005351 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005352 case UO_Extension:
5353 return true;
5354 case UO_Plus:
5355 // The result is always just the subexpr.
5356 return true;
5357 case UO_Minus:
5358 if (Result.isComplexFloat()) {
5359 Result.getComplexFloatReal().changeSign();
5360 Result.getComplexFloatImag().changeSign();
5361 }
5362 else {
5363 Result.getComplexIntReal() = -Result.getComplexIntReal();
5364 Result.getComplexIntImag() = -Result.getComplexIntImag();
5365 }
5366 return true;
5367 case UO_Not:
5368 if (Result.isComplexFloat())
5369 Result.getComplexFloatImag().changeSign();
5370 else
5371 Result.getComplexIntImag() = -Result.getComplexIntImag();
5372 return true;
5373 }
5374}
5375
Eli Friedman7ead5c72012-01-10 04:58:17 +00005376bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5377 if (E->getNumInits() == 2) {
5378 if (E->getType()->isComplexType()) {
5379 Result.makeComplexFloat();
5380 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5381 return false;
5382 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5383 return false;
5384 } else {
5385 Result.makeComplexInt();
5386 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5387 return false;
5388 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5389 return false;
5390 }
5391 return true;
5392 }
5393 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5394}
5395
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005396//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005397// Void expression evaluation, primarily for a cast to void on the LHS of a
5398// comma operator
5399//===----------------------------------------------------------------------===//
5400
5401namespace {
5402class VoidExprEvaluator
5403 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5404public:
5405 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5406
5407 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005408
5409 bool VisitCastExpr(const CastExpr *E) {
5410 switch (E->getCastKind()) {
5411 default:
5412 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5413 case CK_ToVoid:
5414 VisitIgnoredValue(E->getSubExpr());
5415 return true;
5416 }
5417 }
5418};
5419} // end anonymous namespace
5420
5421static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5422 assert(E->isRValue() && E->getType()->isVoidType());
5423 return VoidExprEvaluator(Info).Visit(E);
5424}
5425
5426//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005427// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005428//===----------------------------------------------------------------------===//
5429
Richard Smith47a1eed2011-10-29 20:57:55 +00005430static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005431 // In C, function designators are not lvalues, but we evaluate them as if they
5432 // are.
5433 if (E->isGLValue() || E->getType()->isFunctionType()) {
5434 LValue LV;
5435 if (!EvaluateLValue(E, LV, Info))
5436 return false;
5437 LV.moveInto(Result);
5438 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005439 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005440 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005441 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005442 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005443 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005444 } else if (E->getType()->hasPointerRepresentation()) {
5445 LValue LV;
5446 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005447 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005448 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005449 } else if (E->getType()->isRealFloatingType()) {
5450 llvm::APFloat F(0.0);
5451 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005452 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005453 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005454 } else if (E->getType()->isAnyComplexType()) {
5455 ComplexValue C;
5456 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005457 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005458 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005459 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005460 MemberPtr P;
5461 if (!EvaluateMemberPointer(E, P, Info))
5462 return false;
5463 P.moveInto(Result);
5464 return true;
Richard Smith51201882011-12-30 21:15:51 +00005465 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005466 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005467 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005468 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005469 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005470 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005471 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005472 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005473 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005474 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5475 return false;
5476 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005477 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005478 if (Info.getLangOpts().CPlusPlus0x)
5479 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5480 << E->getType();
5481 else
5482 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005483 if (!EvaluateVoid(E, Info))
5484 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005485 } else if (Info.getLangOpts().CPlusPlus0x) {
5486 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5487 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005488 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005489 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005490 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005491 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005492
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005493 return true;
5494}
5495
Richard Smith69c2c502011-11-04 05:33:44 +00005496/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5497/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5498/// since later initializers for an object can indirectly refer to subobjects
5499/// which were initialized earlier.
5500static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005501 const LValue &This, const Expr *E,
5502 CheckConstantExpressionKind CCEK) {
Richard Smith51201882011-12-30 21:15:51 +00005503 if (!CheckLiteralType(Info, E))
5504 return false;
5505
5506 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005507 // Evaluate arrays and record types in-place, so that later initializers can
5508 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005509 if (E->getType()->isArrayType())
5510 return EvaluateArray(E, This, Result, Info);
5511 else if (E->getType()->isRecordType())
5512 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005513 }
5514
5515 // For any other type, in-place evaluation is unimportant.
5516 CCValue CoreConstResult;
5517 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005518 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005519}
5520
Richard Smithf48fdb02011-12-09 22:58:01 +00005521/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5522/// lvalue-to-rvalue cast if it is an lvalue.
5523static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005524 if (!CheckLiteralType(Info, E))
5525 return false;
5526
Richard Smithf48fdb02011-12-09 22:58:01 +00005527 CCValue Value;
5528 if (!::Evaluate(Value, Info, E))
5529 return false;
5530
5531 if (E->isGLValue()) {
5532 LValue LV;
5533 LV.setFrom(Value);
5534 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5535 return false;
5536 }
5537
5538 // Check this core constant expression is a constant expression, and if so,
5539 // convert it to one.
5540 return CheckConstantExpression(Info, E, Value, Result);
5541}
Richard Smithc49bd112011-10-28 17:51:58 +00005542
Richard Smith51f47082011-10-29 00:50:52 +00005543/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005544/// any crazy technique (that has nothing to do with language standards) that
5545/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005546/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5547/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005548bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005549 // Fast-path evaluations of integer literals, since we sometimes see files
5550 // containing vast quantities of these.
5551 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5552 Result.Val = APValue(APSInt(L->getValue(),
5553 L->getType()->isUnsignedIntegerType()));
5554 return true;
5555 }
5556
Richard Smith2d6a5672012-01-14 04:30:29 +00005557 // FIXME: Evaluating values of large array and record types can cause
5558 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005559 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5560 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005561 return false;
5562
Richard Smithf48fdb02011-12-09 22:58:01 +00005563 EvalInfo Info(Ctx, Result);
5564 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005565}
5566
Jay Foad4ba2a172011-01-12 09:06:06 +00005567bool Expr::EvaluateAsBooleanCondition(bool &Result,
5568 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005569 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005570 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00005571 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5572 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005573 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005574}
5575
Richard Smith80d4b552011-12-28 19:48:30 +00005576bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5577 SideEffectsKind AllowSideEffects) const {
5578 if (!getType()->isIntegralOrEnumerationType())
5579 return false;
5580
Richard Smithc49bd112011-10-28 17:51:58 +00005581 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00005582 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5583 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00005584 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005585
Richard Smithc49bd112011-10-28 17:51:58 +00005586 Result = ExprResult.Val.getInt();
5587 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005588}
5589
Jay Foad4ba2a172011-01-12 09:06:06 +00005590bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005591 EvalInfo Info(Ctx, Result);
5592
John McCallefdb83e2010-05-07 21:00:08 +00005593 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005594 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005595 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5596 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005597}
5598
Richard Smith099e7f62011-12-19 06:19:21 +00005599bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5600 const VarDecl *VD,
5601 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00005602 // FIXME: Evaluating initializers for large array and record types can cause
5603 // performance problems. Only do so in C++11 for now.
5604 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5605 !Ctx.getLangOptions().CPlusPlus0x)
5606 return false;
5607
Richard Smith099e7f62011-12-19 06:19:21 +00005608 Expr::EvalStatus EStatus;
5609 EStatus.Diag = &Notes;
5610
5611 EvalInfo InitInfo(Ctx, EStatus);
5612 InitInfo.setEvaluatingDecl(VD, Value);
5613
Richard Smith51201882011-12-30 21:15:51 +00005614 if (!CheckLiteralType(InitInfo, this))
5615 return false;
5616
Richard Smith099e7f62011-12-19 06:19:21 +00005617 LValue LVal;
5618 LVal.set(VD);
5619
Richard Smith51201882011-12-30 21:15:51 +00005620 // C++11 [basic.start.init]p2:
5621 // Variables with static storage duration or thread storage duration shall be
5622 // zero-initialized before any other initialization takes place.
5623 // This behavior is not present in C.
5624 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5625 !VD->getType()->isReferenceType()) {
5626 ImplicitValueInitExpr VIE(VD->getType());
5627 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5628 return false;
5629 }
5630
Richard Smith099e7f62011-12-19 06:19:21 +00005631 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5632 !EStatus.HasSideEffects;
5633}
5634
Richard Smith51f47082011-10-29 00:50:52 +00005635/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5636/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005637bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005638 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005639 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005640}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005641
Jay Foad4ba2a172011-01-12 09:06:06 +00005642bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005643 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005644}
5645
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005646APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005647 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005648 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005649 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005650 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005651 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005652
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005653 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005654}
John McCalld905f5a2010-05-07 05:32:02 +00005655
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005656 bool Expr::EvalResult::isGlobalLValue() const {
5657 assert(Val.isLValue());
5658 return IsGlobalLValue(Val.getLValueBase());
5659 }
5660
5661
John McCalld905f5a2010-05-07 05:32:02 +00005662/// isIntegerConstantExpr - this recursive routine will test if an expression is
5663/// an integer constant expression.
5664
5665/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5666/// comma, etc
5667///
5668/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5669/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5670/// cast+dereference.
5671
5672// CheckICE - This function does the fundamental ICE checking: the returned
5673// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5674// Note that to reduce code duplication, this helper does no evaluation
5675// itself; the caller checks whether the expression is evaluatable, and
5676// in the rare cases where CheckICE actually cares about the evaluated
5677// value, it calls into Evalute.
5678//
5679// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005680// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005681// 1: This expression is not an ICE, but if it isn't evaluated, it's
5682// a legal subexpression for an ICE. This return value is used to handle
5683// the comma operator in C99 mode.
5684// 2: This expression is not an ICE, and is not a legal subexpression for one.
5685
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005686namespace {
5687
John McCalld905f5a2010-05-07 05:32:02 +00005688struct ICEDiag {
5689 unsigned Val;
5690 SourceLocation Loc;
5691
5692 public:
5693 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5694 ICEDiag() : Val(0) {}
5695};
5696
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005697}
5698
5699static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00005700
5701static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5702 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005703 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005704 !EVResult.Val.isInt()) {
5705 return ICEDiag(2, E->getLocStart());
5706 }
5707 return NoDiag();
5708}
5709
5710static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5711 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005712 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00005713 return ICEDiag(2, E->getLocStart());
5714 }
5715
5716 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00005717#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00005718#define STMT(Node, Base) case Expr::Node##Class:
5719#define EXPR(Node, Base)
5720#include "clang/AST/StmtNodes.inc"
5721 case Expr::PredefinedExprClass:
5722 case Expr::FloatingLiteralClass:
5723 case Expr::ImaginaryLiteralClass:
5724 case Expr::StringLiteralClass:
5725 case Expr::ArraySubscriptExprClass:
5726 case Expr::MemberExprClass:
5727 case Expr::CompoundAssignOperatorClass:
5728 case Expr::CompoundLiteralExprClass:
5729 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005730 case Expr::DesignatedInitExprClass:
5731 case Expr::ImplicitValueInitExprClass:
5732 case Expr::ParenListExprClass:
5733 case Expr::VAArgExprClass:
5734 case Expr::AddrLabelExprClass:
5735 case Expr::StmtExprClass:
5736 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00005737 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005738 case Expr::CXXDynamicCastExprClass:
5739 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00005740 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005741 case Expr::CXXNullPtrLiteralExprClass:
5742 case Expr::CXXThisExprClass:
5743 case Expr::CXXThrowExprClass:
5744 case Expr::CXXNewExprClass:
5745 case Expr::CXXDeleteExprClass:
5746 case Expr::CXXPseudoDestructorExprClass:
5747 case Expr::UnresolvedLookupExprClass:
5748 case Expr::DependentScopeDeclRefExprClass:
5749 case Expr::CXXConstructExprClass:
5750 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00005751 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00005752 case Expr::CXXTemporaryObjectExprClass:
5753 case Expr::CXXUnresolvedConstructExprClass:
5754 case Expr::CXXDependentScopeMemberExprClass:
5755 case Expr::UnresolvedMemberExprClass:
5756 case Expr::ObjCStringLiteralClass:
5757 case Expr::ObjCEncodeExprClass:
5758 case Expr::ObjCMessageExprClass:
5759 case Expr::ObjCSelectorExprClass:
5760 case Expr::ObjCProtocolExprClass:
5761 case Expr::ObjCIvarRefExprClass:
5762 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005763 case Expr::ObjCIsaExprClass:
5764 case Expr::ShuffleVectorExprClass:
5765 case Expr::BlockExprClass:
5766 case Expr::BlockDeclRefExprClass:
5767 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00005768 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00005769 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00005770 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005771 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005772 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00005773 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00005774 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00005775 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005776 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005777 return ICEDiag(2, E->getLocStart());
5778
Douglas Gregoree8aff02011-01-04 17:33:58 +00005779 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005780 case Expr::GNUNullExprClass:
5781 // GCC considers the GNU __null value to be an integral constant expression.
5782 return NoDiag();
5783
John McCall91a57552011-07-15 05:09:51 +00005784 case Expr::SubstNonTypeTemplateParmExprClass:
5785 return
5786 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5787
John McCalld905f5a2010-05-07 05:32:02 +00005788 case Expr::ParenExprClass:
5789 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00005790 case Expr::GenericSelectionExprClass:
5791 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005792 case Expr::IntegerLiteralClass:
5793 case Expr::CharacterLiteralClass:
5794 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00005795 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005796 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00005797 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00005798 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00005799 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00005800 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005801 return NoDiag();
5802 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00005803 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00005804 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5805 // constant expressions, but they can never be ICEs because an ICE cannot
5806 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00005807 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00005808 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00005809 return CheckEvalInICE(E, Ctx);
5810 return ICEDiag(2, E->getLocStart());
5811 }
5812 case Expr::DeclRefExprClass:
5813 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5814 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00005815 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00005816 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5817
5818 // Parameter variables are never constants. Without this check,
5819 // getAnyInitializer() can find a default argument, which leads
5820 // to chaos.
5821 if (isa<ParmVarDecl>(D))
5822 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5823
5824 // C++ 7.1.5.1p2
5825 // A variable of non-volatile const-qualified integral or enumeration
5826 // type initialized by an ICE can be used in ICEs.
5827 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00005828 if (!Dcl->getType()->isIntegralOrEnumerationType())
5829 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5830
Richard Smith099e7f62011-12-19 06:19:21 +00005831 const VarDecl *VD;
5832 // Look for a declaration of this variable that has an initializer, and
5833 // check whether it is an ICE.
5834 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5835 return NoDiag();
5836 else
5837 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00005838 }
5839 }
5840 return ICEDiag(2, E->getLocStart());
5841 case Expr::UnaryOperatorClass: {
5842 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5843 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005844 case UO_PostInc:
5845 case UO_PostDec:
5846 case UO_PreInc:
5847 case UO_PreDec:
5848 case UO_AddrOf:
5849 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00005850 // C99 6.6/3 allows increment and decrement within unevaluated
5851 // subexpressions of constant expressions, but they can never be ICEs
5852 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005853 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00005854 case UO_Extension:
5855 case UO_LNot:
5856 case UO_Plus:
5857 case UO_Minus:
5858 case UO_Not:
5859 case UO_Real:
5860 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00005861 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005862 }
5863
5864 // OffsetOf falls through here.
5865 }
5866 case Expr::OffsetOfExprClass: {
5867 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00005868 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00005869 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00005870 // compliance: we should warn earlier for offsetof expressions with
5871 // array subscripts that aren't ICEs, and if the array subscripts
5872 // are ICEs, the value of the offsetof must be an integer constant.
5873 return CheckEvalInICE(E, Ctx);
5874 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005875 case Expr::UnaryExprOrTypeTraitExprClass: {
5876 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5877 if ((Exp->getKind() == UETT_SizeOf) &&
5878 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00005879 return ICEDiag(2, E->getLocStart());
5880 return NoDiag();
5881 }
5882 case Expr::BinaryOperatorClass: {
5883 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5884 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005885 case BO_PtrMemD:
5886 case BO_PtrMemI:
5887 case BO_Assign:
5888 case BO_MulAssign:
5889 case BO_DivAssign:
5890 case BO_RemAssign:
5891 case BO_AddAssign:
5892 case BO_SubAssign:
5893 case BO_ShlAssign:
5894 case BO_ShrAssign:
5895 case BO_AndAssign:
5896 case BO_XorAssign:
5897 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00005898 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5899 // constant expressions, but they can never be ICEs because an ICE cannot
5900 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005901 return ICEDiag(2, E->getLocStart());
5902
John McCall2de56d12010-08-25 11:45:40 +00005903 case BO_Mul:
5904 case BO_Div:
5905 case BO_Rem:
5906 case BO_Add:
5907 case BO_Sub:
5908 case BO_Shl:
5909 case BO_Shr:
5910 case BO_LT:
5911 case BO_GT:
5912 case BO_LE:
5913 case BO_GE:
5914 case BO_EQ:
5915 case BO_NE:
5916 case BO_And:
5917 case BO_Xor:
5918 case BO_Or:
5919 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00005920 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5921 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00005922 if (Exp->getOpcode() == BO_Div ||
5923 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00005924 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00005925 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00005926 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005927 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005928 if (REval == 0)
5929 return ICEDiag(1, E->getLocStart());
5930 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005931 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005932 if (LEval.isMinSignedValue())
5933 return ICEDiag(1, E->getLocStart());
5934 }
5935 }
5936 }
John McCall2de56d12010-08-25 11:45:40 +00005937 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00005938 if (Ctx.getLangOptions().C99) {
5939 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5940 // if it isn't evaluated.
5941 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5942 return ICEDiag(1, E->getLocStart());
5943 } else {
5944 // In both C89 and C++, commas in ICEs are illegal.
5945 return ICEDiag(2, E->getLocStart());
5946 }
5947 }
5948 if (LHSResult.Val >= RHSResult.Val)
5949 return LHSResult;
5950 return RHSResult;
5951 }
John McCall2de56d12010-08-25 11:45:40 +00005952 case BO_LAnd:
5953 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00005954 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5955 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5956 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5957 // Rare case where the RHS has a comma "side-effect"; we need
5958 // to actually check the condition to see whether the side
5959 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00005960 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005961 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00005962 return RHSResult;
5963 return NoDiag();
5964 }
5965
5966 if (LHSResult.Val >= RHSResult.Val)
5967 return LHSResult;
5968 return RHSResult;
5969 }
5970 }
5971 }
5972 case Expr::ImplicitCastExprClass:
5973 case Expr::CStyleCastExprClass:
5974 case Expr::CXXFunctionalCastExprClass:
5975 case Expr::CXXStaticCastExprClass:
5976 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00005977 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005978 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00005979 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00005980 if (isa<ExplicitCastExpr>(E)) {
5981 if (const FloatingLiteral *FL
5982 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5983 unsigned DestWidth = Ctx.getIntWidth(E->getType());
5984 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5985 APSInt IgnoredVal(DestWidth, !DestSigned);
5986 bool Ignored;
5987 // If the value does not fit in the destination type, the behavior is
5988 // undefined, so we are not required to treat it as a constant
5989 // expression.
5990 if (FL->getValue().convertToInteger(IgnoredVal,
5991 llvm::APFloat::rmTowardZero,
5992 &Ignored) & APFloat::opInvalidOp)
5993 return ICEDiag(2, E->getLocStart());
5994 return NoDiag();
5995 }
5996 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00005997 switch (cast<CastExpr>(E)->getCastKind()) {
5998 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005999 case CK_AtomicToNonAtomic:
6000 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006001 case CK_NoOp:
6002 case CK_IntegralToBoolean:
6003 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006004 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006005 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006006 return ICEDiag(2, E->getLocStart());
6007 }
John McCalld905f5a2010-05-07 05:32:02 +00006008 }
John McCall56ca35d2011-02-17 10:25:35 +00006009 case Expr::BinaryConditionalOperatorClass: {
6010 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6011 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6012 if (CommonResult.Val == 2) return CommonResult;
6013 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6014 if (FalseResult.Val == 2) return FalseResult;
6015 if (CommonResult.Val == 1) return CommonResult;
6016 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006017 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006018 return FalseResult;
6019 }
John McCalld905f5a2010-05-07 05:32:02 +00006020 case Expr::ConditionalOperatorClass: {
6021 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6022 // If the condition (ignoring parens) is a __builtin_constant_p call,
6023 // then only the true side is actually considered in an integer constant
6024 // expression, and it is fully evaluated. This is an important GNU
6025 // extension. See GCC PR38377 for discussion.
6026 if (const CallExpr *CallCE
6027 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006028 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6029 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006030 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006031 if (CondResult.Val == 2)
6032 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006033
Richard Smithf48fdb02011-12-09 22:58:01 +00006034 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6035 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006036
John McCalld905f5a2010-05-07 05:32:02 +00006037 if (TrueResult.Val == 2)
6038 return TrueResult;
6039 if (FalseResult.Val == 2)
6040 return FalseResult;
6041 if (CondResult.Val == 1)
6042 return CondResult;
6043 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6044 return NoDiag();
6045 // Rare case where the diagnostics depend on which side is evaluated
6046 // Note that if we get here, CondResult is 0, and at least one of
6047 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006048 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006049 return FalseResult;
6050 }
6051 return TrueResult;
6052 }
6053 case Expr::CXXDefaultArgExprClass:
6054 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6055 case Expr::ChooseExprClass: {
6056 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6057 }
6058 }
6059
David Blaikie30263482012-01-20 21:50:17 +00006060 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006061}
6062
Richard Smithf48fdb02011-12-09 22:58:01 +00006063/// Evaluate an expression as a C++11 integral constant expression.
6064static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6065 const Expr *E,
6066 llvm::APSInt *Value,
6067 SourceLocation *Loc) {
6068 if (!E->getType()->isIntegralOrEnumerationType()) {
6069 if (Loc) *Loc = E->getExprLoc();
6070 return false;
6071 }
6072
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006073 APValue Result;
6074 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006075 return false;
6076
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006077 assert(Result.isInt() && "pointer cast to int is not an ICE");
6078 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006079 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006080}
6081
Richard Smithdd1f29b2011-12-12 09:28:41 +00006082bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006083 if (Ctx.getLangOptions().CPlusPlus0x)
6084 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6085
John McCalld905f5a2010-05-07 05:32:02 +00006086 ICEDiag d = CheckICE(this, Ctx);
6087 if (d.Val != 0) {
6088 if (Loc) *Loc = d.Loc;
6089 return false;
6090 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006091 return true;
6092}
6093
6094bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6095 SourceLocation *Loc, bool isEvaluated) const {
6096 if (Ctx.getLangOptions().CPlusPlus0x)
6097 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6098
6099 if (!isIntegerConstantExpr(Ctx, Loc))
6100 return false;
6101 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006102 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006103 return true;
6104}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006105
6106bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6107 SourceLocation *Loc) const {
6108 // We support this checking in C++98 mode in order to diagnose compatibility
6109 // issues.
6110 assert(Ctx.getLangOptions().CPlusPlus);
6111
6112 Expr::EvalStatus Status;
6113 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6114 Status.Diag = &Diags;
6115 EvalInfo Info(Ctx, Status);
6116
6117 APValue Scratch;
6118 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6119
6120 if (!Diags.empty()) {
6121 IsConstExpr = false;
6122 if (Loc) *Loc = Diags[0].first;
6123 } else if (!IsConstExpr) {
6124 // FIXME: This shouldn't happen.
6125 if (Loc) *Loc = getExprLoc();
6126 }
6127
6128 return IsConstExpr;
6129}
Richard Smith745f5142012-01-27 01:14:48 +00006130
6131bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6132 llvm::SmallVectorImpl<
6133 PartialDiagnosticAt> &Diags) {
6134 // FIXME: It would be useful to check constexpr function templates, but at the
6135 // moment the constant expression evaluator cannot cope with the non-rigorous
6136 // ASTs which we build for dependent expressions.
6137 if (FD->isDependentContext())
6138 return true;
6139
6140 Expr::EvalStatus Status;
6141 Status.Diag = &Diags;
6142
6143 EvalInfo Info(FD->getASTContext(), Status);
6144 Info.CheckingPotentialConstantExpression = true;
6145
6146 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6147 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6148
6149 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6150 // is a temporary being used as the 'this' pointer.
6151 LValue This;
6152 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6153 This.set(&VIE, Info.CurrentCall);
6154
6155 APValue Scratch;
6156 ArrayRef<const Expr*> Args;
6157
6158 SourceLocation Loc = FD->getLocation();
6159
6160 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
6161 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6162 } else
6163 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6164 Args, FD->getBody(), Info, Scratch);
6165
6166 return Diags.empty();
6167}