blob: 15ab15ce3d60ca3c4ede2f0b9533ac06566f11d4 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith745f5142012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlssonc44eec62008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000038#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000039#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000040#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000041#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000042#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000047#include <cstring>
48
Anders Carlssonc44eec62008-07-03 04:20:39 +000049using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000050using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000051using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000052
Chris Lattner87eae5e2008-07-11 22:52:41 +000053/// EvalInfo - This is a private struct used by the evaluator to capture
54/// information about a subexpression as it is folded. It retains information
55/// about the AST context, but also maintains information about the folded
56/// expression.
57///
58/// If an expression could be evaluated, it is still possible it is not a C
59/// "integer constant expression" or constant expression. If not, this struct
60/// captures information about how and why not.
61///
62/// One bit of information passed *into* the request for constant folding
63/// indicates whether the subexpression is "evaluated" or not according to C
64/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
65/// evaluate the expression regardless of what the RHS is, but C only allows
66/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000067namespace {
Richard Smith180f4792011-11-10 06:34:14 +000068 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000069 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000070 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000071
Richard Smith1bf9a9e2011-11-12 22:28:03 +000072 QualType getType(APValue::LValueBase B) {
73 if (!B) return QualType();
74 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
75 return D->getType();
76 return B.get<const Expr*>()->getType();
77 }
78
Richard Smith180f4792011-11-10 06:34:14 +000079 /// Get an LValue path entry, which is known to not be an array index, as a
80 /// field declaration.
81 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
82 APValue::BaseOrMemberType Value;
83 Value.setFromOpaqueValue(E.BaseOrMember);
84 return dyn_cast<FieldDecl>(Value.getPointer());
85 }
86 /// Get an LValue path entry, which is known to not be an array index, as a
87 /// base class declaration.
88 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
89 APValue::BaseOrMemberType Value;
90 Value.setFromOpaqueValue(E.BaseOrMember);
91 return dyn_cast<CXXRecordDecl>(Value.getPointer());
92 }
93 /// Determine whether this LValue path entry for a base class names a virtual
94 /// base class.
95 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
96 APValue::BaseOrMemberType Value;
97 Value.setFromOpaqueValue(E.BaseOrMember);
98 return Value.getInt();
99 }
100
Richard Smithb4e85ed2012-01-06 16:39:00 +0000101 /// Find the path length and type of the most-derived subobject in the given
102 /// path, and find the size of the containing array, if any.
103 static
104 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
105 ArrayRef<APValue::LValuePathEntry> Path,
106 uint64_t &ArraySize, QualType &Type) {
107 unsigned MostDerivedLength = 0;
108 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000109 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000110 if (Type->isArrayType()) {
111 const ConstantArrayType *CAT =
112 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
113 Type = CAT->getElementType();
114 ArraySize = CAT->getSize().getZExtValue();
115 MostDerivedLength = I + 1;
116 } else if (const FieldDecl *FD = getAsField(Path[I])) {
117 Type = FD->getType();
118 ArraySize = 0;
119 MostDerivedLength = I + 1;
120 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000121 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000122 ArraySize = 0;
123 }
Richard Smith9a17a682011-11-07 05:07:52 +0000124 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000125 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000126 }
127
Richard Smithb4e85ed2012-01-06 16:39:00 +0000128 // The order of this enum is important for diagnostics.
129 enum CheckSubobjectKind {
130 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex
131 };
132
Richard Smith0a3bdb62011-11-04 02:25:55 +0000133 /// A path from a glvalue to a subobject of that glvalue.
134 struct SubobjectDesignator {
135 /// True if the subobject was named in a manner not supported by C++11. Such
136 /// lvalues can still be folded, but they are not core constant expressions
137 /// and we cannot perform lvalue-to-rvalue conversions on them.
138 bool Invalid : 1;
139
Richard Smithb4e85ed2012-01-06 16:39:00 +0000140 /// Is this a pointer one past the end of an object?
141 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000142
Richard Smithb4e85ed2012-01-06 16:39:00 +0000143 /// The length of the path to the most-derived object of which this is a
144 /// subobject.
145 unsigned MostDerivedPathLength : 30;
146
147 /// The size of the array of which the most-derived object is an element, or
148 /// 0 if the most-derived object is not an array element.
149 uint64_t MostDerivedArraySize;
150
151 /// The type of the most derived object referred to by this address.
152 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000153
Richard Smith9a17a682011-11-07 05:07:52 +0000154 typedef APValue::LValuePathEntry PathEntry;
155
Richard Smith0a3bdb62011-11-04 02:25:55 +0000156 /// The entries on the path from the glvalue to the designated subobject.
157 SmallVector<PathEntry, 8> Entries;
158
Richard Smithb4e85ed2012-01-06 16:39:00 +0000159 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000160
Richard Smithb4e85ed2012-01-06 16:39:00 +0000161 explicit SubobjectDesignator(QualType T)
162 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
163 MostDerivedArraySize(0), MostDerivedType(T) {}
164
165 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
166 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
167 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000168 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000169 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000170 ArrayRef<PathEntry> VEntries = V.getLValuePath();
171 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
172 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000173 MostDerivedPathLength =
174 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
175 V.getLValuePath(), MostDerivedArraySize,
176 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000177 }
178 }
179
Richard Smith0a3bdb62011-11-04 02:25:55 +0000180 void setInvalid() {
181 Invalid = true;
182 Entries.clear();
183 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000184
185 /// Determine whether this is a one-past-the-end pointer.
186 bool isOnePastTheEnd() const {
187 if (IsOnePastTheEnd)
188 return true;
189 if (MostDerivedArraySize &&
190 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
191 return true;
192 return false;
193 }
194
195 /// Check that this refers to a valid subobject.
196 bool isValidSubobject() const {
197 if (Invalid)
198 return false;
199 return !isOnePastTheEnd();
200 }
201 /// Check that this refers to a valid subobject, and if not, produce a
202 /// relevant diagnostic and set the designator as invalid.
203 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
204
205 /// Update this designator to refer to the first element within this array.
206 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000207 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000208 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000209 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000210
211 // This is a most-derived object.
212 MostDerivedType = CAT->getElementType();
213 MostDerivedArraySize = CAT->getSize().getZExtValue();
214 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000215 }
216 /// Update this designator to refer to the given base or member of this
217 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000218 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000219 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000220 APValue::BaseOrMemberType Value(D, Virtual);
221 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000222 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000223
224 // If this isn't a base class, it's a new most-derived object.
225 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
226 MostDerivedType = FD->getType();
227 MostDerivedArraySize = 0;
228 MostDerivedPathLength = Entries.size();
229 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000230 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000231 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000232 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000233 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000234 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000235 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000236 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000237 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
238 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
239 setInvalid();
240 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000241 return;
242 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000243 // [expr.add]p4: For the purposes of these operators, a pointer to a
244 // nonarray object behaves the same as a pointer to the first element of
245 // an array of length one with the type of the object as its element type.
246 if (IsOnePastTheEnd && N == (uint64_t)-1)
247 IsOnePastTheEnd = false;
248 else if (!IsOnePastTheEnd && N == 1)
249 IsOnePastTheEnd = true;
250 else if (N != 0) {
251 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000252 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000253 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000254 }
255 };
256
Richard Smith47a1eed2011-10-29 20:57:55 +0000257 /// A core constant value. This can be the value of any constant expression,
258 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000259 ///
260 /// For an LValue, the base and offset are stored in the APValue subobject,
261 /// but the other information is stored in the SubobjectDesignator. For all
262 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000263 class CCValue : public APValue {
264 typedef llvm::APSInt APSInt;
265 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000266 /// If the value is a reference or pointer into a parameter or temporary,
267 /// this is the corresponding call stack frame.
268 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000269 /// If the value is a reference or pointer, this is a description of how the
270 /// subobject was specified.
271 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000272 public:
Richard Smith177dce72011-11-01 16:57:24 +0000273 struct GlobalValue {};
274
Richard Smith47a1eed2011-10-29 20:57:55 +0000275 CCValue() {}
276 explicit CCValue(const APSInt &I) : APValue(I) {}
277 explicit CCValue(const APFloat &F) : APValue(F) {}
278 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
279 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
280 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000281 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000282 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000283 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000284 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000285 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
286 APValue(V), CallFrame(0), Designator(Ctx, V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000287 CCValue(const ValueDecl *D, bool IsDerivedMember,
288 ArrayRef<const CXXRecordDecl*> Path) :
289 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000290 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
291 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000292
Richard Smith177dce72011-11-01 16:57:24 +0000293 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000294 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000295 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000296 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000297 SubobjectDesignator &getLValueDesignator() {
298 assert(getKind() == LValue);
299 return Designator;
300 }
301 const SubobjectDesignator &getLValueDesignator() const {
302 return const_cast<CCValue*>(this)->getLValueDesignator();
303 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000304 };
305
Richard Smithd0dccea2011-10-28 22:34:42 +0000306 /// A stack frame in the constexpr call stack.
307 struct CallStackFrame {
308 EvalInfo &Info;
309
310 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000311 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000312
Richard Smith08d6e032011-12-16 19:06:07 +0000313 /// CallLoc - The location of the call expression for this call.
314 SourceLocation CallLoc;
315
316 /// Callee - The function which was called.
317 const FunctionDecl *Callee;
318
Richard Smith180f4792011-11-10 06:34:14 +0000319 /// This - The binding for the this pointer in this call, if any.
320 const LValue *This;
321
Richard Smithd0dccea2011-10-28 22:34:42 +0000322 /// ParmBindings - Parameter bindings for this function call, indexed by
323 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000324 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000325
Richard Smithbd552ef2011-10-31 05:52:43 +0000326 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
327 typedef MapTy::const_iterator temp_iterator;
328 /// Temporaries - Temporary lvalues materialized within this stack frame.
329 MapTy Temporaries;
330
Richard Smith08d6e032011-12-16 19:06:07 +0000331 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
332 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000333 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000334 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000335 };
336
Richard Smithdd1f29b2011-12-12 09:28:41 +0000337 /// A partial diagnostic which we might know in advance that we are not going
338 /// to emit.
339 class OptionalDiagnostic {
340 PartialDiagnostic *Diag;
341
342 public:
343 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
344
345 template<typename T>
346 OptionalDiagnostic &operator<<(const T &v) {
347 if (Diag)
348 *Diag << v;
349 return *this;
350 }
Richard Smith789f9b62012-01-31 04:08:20 +0000351
352 OptionalDiagnostic &operator<<(const APSInt &I) {
353 if (Diag) {
354 llvm::SmallVector<char, 32> Buffer;
355 I.toString(Buffer);
356 *Diag << StringRef(Buffer.data(), Buffer.size());
357 }
358 return *this;
359 }
360
361 OptionalDiagnostic &operator<<(const APFloat &F) {
362 if (Diag) {
363 llvm::SmallVector<char, 32> Buffer;
364 F.toString(Buffer);
365 *Diag << StringRef(Buffer.data(), Buffer.size());
366 }
367 return *this;
368 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000369 };
370
Richard Smithbd552ef2011-10-31 05:52:43 +0000371 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000372 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000373
374 /// EvalStatus - Contains information about the evaluation.
375 Expr::EvalStatus &EvalStatus;
376
377 /// CurrentCall - The top of the constexpr call stack.
378 CallStackFrame *CurrentCall;
379
Richard Smithbd552ef2011-10-31 05:52:43 +0000380 /// CallStackDepth - The number of calls in the call stack right now.
381 unsigned CallStackDepth;
382
383 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
384 /// OpaqueValues - Values used as the common expression in a
385 /// BinaryConditionalOperator.
386 MapTy OpaqueValues;
387
388 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000389 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000390 CallStackFrame BottomFrame;
391
Richard Smith180f4792011-11-10 06:34:14 +0000392 /// EvaluatingDecl - This is the declaration whose initializer is being
393 /// evaluated, if any.
394 const VarDecl *EvaluatingDecl;
395
396 /// EvaluatingDeclValue - This is the value being constructed for the
397 /// declaration whose initializer is being evaluated, if any.
398 APValue *EvaluatingDeclValue;
399
Richard Smithc1c5f272011-12-13 06:39:58 +0000400 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
401 /// notes attached to it will also be stored, otherwise they will not be.
402 bool HasActiveDiagnostic;
403
Richard Smith745f5142012-01-27 01:14:48 +0000404 /// CheckingPotentialConstantExpression - Are we checking whether the
405 /// expression is a potential constant expression? If so, some diagnostics
406 /// are suppressed.
407 bool CheckingPotentialConstantExpression;
408
Richard Smithbd552ef2011-10-31 05:52:43 +0000409
410 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000411 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith08d6e032011-12-16 19:06:07 +0000412 CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000413 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
414 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000415
Richard Smithbd552ef2011-10-31 05:52:43 +0000416 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
417 MapTy::const_iterator i = OpaqueValues.find(e);
418 if (i == OpaqueValues.end()) return 0;
419 return &i->second;
420 }
421
Richard Smith180f4792011-11-10 06:34:14 +0000422 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
423 EvaluatingDecl = VD;
424 EvaluatingDeclValue = &Value;
425 }
426
Richard Smithc18c4232011-11-21 19:36:32 +0000427 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
428
Richard Smithc1c5f272011-12-13 06:39:58 +0000429 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000430 // Don't perform any constexpr calls (other than the call we're checking)
431 // when checking a potential constant expression.
432 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
433 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +0000434 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
435 return true;
436 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
437 << getLangOpts().ConstexprCallDepth;
438 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000439 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000440
Richard Smithc1c5f272011-12-13 06:39:58 +0000441 private:
442 /// Add a diagnostic to the diagnostics list.
443 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
444 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
445 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
446 return EvalStatus.Diag->back().second;
447 }
448
Richard Smith08d6e032011-12-16 19:06:07 +0000449 /// Add notes containing a call stack to the current point of evaluation.
450 void addCallStack(unsigned Limit);
451
Richard Smithc1c5f272011-12-13 06:39:58 +0000452 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000453 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000454 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
455 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000456 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000457 // If we have a prior diagnostic, it will be noting that the expression
458 // isn't a constant expression. This diagnostic is more important.
459 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000460 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000461 unsigned CallStackNotes = CallStackDepth - 1;
462 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
463 if (Limit)
464 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000465 if (CheckingPotentialConstantExpression)
466 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000467
Richard Smithc1c5f272011-12-13 06:39:58 +0000468 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000469 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000470 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
471 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000472 if (!CheckingPotentialConstantExpression)
473 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000474 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000475 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000476 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000477 return OptionalDiagnostic();
478 }
479
480 /// Diagnose that the evaluation does not produce a C++11 core constant
481 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000482 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
483 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000484 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000485 // Don't override a previous diagnostic.
486 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
487 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000488 return Diag(Loc, DiagId, ExtraNotes);
489 }
490
491 /// Add a note to a prior diagnostic.
492 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
493 if (!HasActiveDiagnostic)
494 return OptionalDiagnostic();
495 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000496 }
Richard Smith099e7f62011-12-19 06:19:21 +0000497
498 /// Add a stack of notes to a prior diagnostic.
499 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
500 if (HasActiveDiagnostic) {
501 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
502 Diags.begin(), Diags.end());
503 }
504 }
Richard Smith745f5142012-01-27 01:14:48 +0000505
506 /// Should we continue evaluation as much as possible after encountering a
507 /// construct which can't be folded?
508 bool keepEvaluatingAfterFailure() {
509 return CheckingPotentialConstantExpression && EvalStatus.Diag->empty();
510 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000511 };
Richard Smith08d6e032011-12-16 19:06:07 +0000512}
Richard Smithbd552ef2011-10-31 05:52:43 +0000513
Richard Smithb4e85ed2012-01-06 16:39:00 +0000514bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
515 CheckSubobjectKind CSK) {
516 if (Invalid)
517 return false;
518 if (isOnePastTheEnd()) {
519 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
520 << CSK;
521 setInvalid();
522 return false;
523 }
524 return true;
525}
526
527void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
528 const Expr *E, uint64_t N) {
529 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
530 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
531 << static_cast<int>(N) << /*array*/ 0
532 << static_cast<unsigned>(MostDerivedArraySize);
533 else
534 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
535 << static_cast<int>(N) << /*non-array*/ 1;
536 setInvalid();
537}
538
Richard Smith08d6e032011-12-16 19:06:07 +0000539CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
540 const FunctionDecl *Callee, const LValue *This,
541 const CCValue *Arguments)
542 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
543 This(This), Arguments(Arguments) {
544 Info.CurrentCall = this;
545 ++Info.CallStackDepth;
546}
547
548CallStackFrame::~CallStackFrame() {
549 assert(Info.CurrentCall == this && "calls retired out of order");
550 --Info.CallStackDepth;
551 Info.CurrentCall = Caller;
552}
553
554/// Produce a string describing the given constexpr call.
555static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
556 unsigned ArgIndex = 0;
557 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
558 !isa<CXXConstructorDecl>(Frame->Callee);
559
560 if (!IsMemberCall)
561 Out << *Frame->Callee << '(';
562
563 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
564 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000565 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000566 Out << ", ";
567
568 const ParmVarDecl *Param = *I;
569 const CCValue &Arg = Frame->Arguments[ArgIndex];
570 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
571 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
572 else {
573 // Deliberately slice off the frame to form an APValue we can print.
574 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
575 Arg.getLValueDesignator().Entries,
Richard Smithb4e85ed2012-01-06 16:39:00 +0000576 Arg.getLValueDesignator().IsOnePastTheEnd);
Richard Smith08d6e032011-12-16 19:06:07 +0000577 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
578 }
579
580 if (ArgIndex == 0 && IsMemberCall)
581 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000582 }
583
Richard Smith08d6e032011-12-16 19:06:07 +0000584 Out << ')';
585}
586
587void EvalInfo::addCallStack(unsigned Limit) {
588 // Determine which calls to skip, if any.
589 unsigned ActiveCalls = CallStackDepth - 1;
590 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
591 if (Limit && Limit < ActiveCalls) {
592 SkipStart = Limit / 2 + Limit % 2;
593 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000594 }
595
Richard Smith08d6e032011-12-16 19:06:07 +0000596 // Walk the call stack and add the diagnostics.
597 unsigned CallIdx = 0;
598 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
599 Frame = Frame->Caller, ++CallIdx) {
600 // Skip this call?
601 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
602 if (CallIdx == SkipStart) {
603 // Note that we're skipping calls.
604 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
605 << unsigned(ActiveCalls - Limit);
606 }
607 continue;
608 }
609
610 llvm::SmallVector<char, 128> Buffer;
611 llvm::raw_svector_ostream Out(Buffer);
612 describeCall(Frame, Out);
613 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
614 }
615}
616
617namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000618 struct ComplexValue {
619 private:
620 bool IsInt;
621
622 public:
623 APSInt IntReal, IntImag;
624 APFloat FloatReal, FloatImag;
625
626 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
627
628 void makeComplexFloat() { IsInt = false; }
629 bool isComplexFloat() const { return !IsInt; }
630 APFloat &getComplexFloatReal() { return FloatReal; }
631 APFloat &getComplexFloatImag() { return FloatImag; }
632
633 void makeComplexInt() { IsInt = true; }
634 bool isComplexInt() const { return IsInt; }
635 APSInt &getComplexIntReal() { return IntReal; }
636 APSInt &getComplexIntImag() { return IntImag; }
637
Richard Smith47a1eed2011-10-29 20:57:55 +0000638 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000639 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000640 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000641 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000642 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000643 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000644 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000645 assert(v.isComplexFloat() || v.isComplexInt());
646 if (v.isComplexFloat()) {
647 makeComplexFloat();
648 FloatReal = v.getComplexFloatReal();
649 FloatImag = v.getComplexFloatImag();
650 } else {
651 makeComplexInt();
652 IntReal = v.getComplexIntReal();
653 IntImag = v.getComplexIntImag();
654 }
655 }
John McCallf4cf1a12010-05-07 17:22:02 +0000656 };
John McCallefdb83e2010-05-07 21:00:08 +0000657
658 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000659 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000660 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000661 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000662 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000663
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000664 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000665 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000666 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000667 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000668 SubobjectDesignator &getLValueDesignator() { return Designator; }
669 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000670
Richard Smith47a1eed2011-10-29 20:57:55 +0000671 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000672 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000673 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000674 void setFrom(const CCValue &V) {
675 assert(V.isLValue());
676 Base = V.getLValueBase();
677 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000678 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000679 Designator = V.getLValueDesignator();
680 }
681
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000682 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
683 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000684 Offset = CharUnits::Zero();
685 Frame = F;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000686 Designator = SubobjectDesignator(getType(B));
687 }
688
689 // Check that this LValue is not based on a null pointer. If it is, produce
690 // a diagnostic and mark the designator as invalid.
691 bool checkNullPointer(EvalInfo &Info, const Expr *E,
692 CheckSubobjectKind CSK) {
693 if (Designator.Invalid)
694 return false;
695 if (!Base) {
696 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
697 << CSK;
698 Designator.setInvalid();
699 return false;
700 }
701 return true;
702 }
703
704 // Check this LValue refers to an object. If not, set the designator to be
705 // invalid and emit a diagnostic.
706 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
707 return checkNullPointer(Info, E, CSK) &&
708 Designator.checkSubobject(Info, E, CSK);
709 }
710
711 void addDecl(EvalInfo &Info, const Expr *E,
712 const Decl *D, bool Virtual = false) {
713 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
714 Designator.addDeclUnchecked(D, Virtual);
715 }
716 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
717 checkSubobject(Info, E, CSK_ArrayToPointer);
718 Designator.addArrayUnchecked(CAT);
719 }
720 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
721 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
722 return;
723 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000724 }
John McCallefdb83e2010-05-07 21:00:08 +0000725 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000726
727 struct MemberPtr {
728 MemberPtr() {}
729 explicit MemberPtr(const ValueDecl *Decl) :
730 DeclAndIsDerivedMember(Decl, false), Path() {}
731
732 /// The member or (direct or indirect) field referred to by this member
733 /// pointer, or 0 if this is a null member pointer.
734 const ValueDecl *getDecl() const {
735 return DeclAndIsDerivedMember.getPointer();
736 }
737 /// Is this actually a member of some type derived from the relevant class?
738 bool isDerivedMember() const {
739 return DeclAndIsDerivedMember.getInt();
740 }
741 /// Get the class which the declaration actually lives in.
742 const CXXRecordDecl *getContainingRecord() const {
743 return cast<CXXRecordDecl>(
744 DeclAndIsDerivedMember.getPointer()->getDeclContext());
745 }
746
747 void moveInto(CCValue &V) const {
748 V = CCValue(getDecl(), isDerivedMember(), Path);
749 }
750 void setFrom(const CCValue &V) {
751 assert(V.isMemberPointer());
752 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
753 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
754 Path.clear();
755 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
756 Path.insert(Path.end(), P.begin(), P.end());
757 }
758
759 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
760 /// whether the member is a member of some class derived from the class type
761 /// of the member pointer.
762 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
763 /// Path - The path of base/derived classes from the member declaration's
764 /// class (exclusive) to the class type of the member pointer (inclusive).
765 SmallVector<const CXXRecordDecl*, 4> Path;
766
767 /// Perform a cast towards the class of the Decl (either up or down the
768 /// hierarchy).
769 bool castBack(const CXXRecordDecl *Class) {
770 assert(!Path.empty());
771 const CXXRecordDecl *Expected;
772 if (Path.size() >= 2)
773 Expected = Path[Path.size() - 2];
774 else
775 Expected = getContainingRecord();
776 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
777 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
778 // if B does not contain the original member and is not a base or
779 // derived class of the class containing the original member, the result
780 // of the cast is undefined.
781 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
782 // (D::*). We consider that to be a language defect.
783 return false;
784 }
785 Path.pop_back();
786 return true;
787 }
788 /// Perform a base-to-derived member pointer cast.
789 bool castToDerived(const CXXRecordDecl *Derived) {
790 if (!getDecl())
791 return true;
792 if (!isDerivedMember()) {
793 Path.push_back(Derived);
794 return true;
795 }
796 if (!castBack(Derived))
797 return false;
798 if (Path.empty())
799 DeclAndIsDerivedMember.setInt(false);
800 return true;
801 }
802 /// Perform a derived-to-base member pointer cast.
803 bool castToBase(const CXXRecordDecl *Base) {
804 if (!getDecl())
805 return true;
806 if (Path.empty())
807 DeclAndIsDerivedMember.setInt(true);
808 if (isDerivedMember()) {
809 Path.push_back(Base);
810 return true;
811 }
812 return castBack(Base);
813 }
814 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000815
816 /// Kinds of constant expression checking, for diagnostics.
817 enum CheckConstantExpressionKind {
818 CCEK_Constant, ///< A normal constant.
819 CCEK_ReturnValue, ///< A constexpr function return value.
820 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
821 };
John McCallf4cf1a12010-05-07 17:22:02 +0000822}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000823
Richard Smith47a1eed2011-10-29 20:57:55 +0000824static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000825static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000826 const LValue &This, const Expr *E,
827 CheckConstantExpressionKind CCEK
828 = CCEK_Constant);
John McCallefdb83e2010-05-07 21:00:08 +0000829static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
830static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000831static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
832 EvalInfo &Info);
833static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000834static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000835static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000836 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000837static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000838static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000839
840//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000841// Misc utilities
842//===----------------------------------------------------------------------===//
843
Richard Smith180f4792011-11-10 06:34:14 +0000844/// Should this call expression be treated as a string literal?
845static bool IsStringLiteralCall(const CallExpr *E) {
846 unsigned Builtin = E->isBuiltinCall();
847 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
848 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
849}
850
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000851static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000852 // C++11 [expr.const]p3 An address constant expression is a prvalue core
853 // constant expression of pointer type that evaluates to...
854
855 // ... a null pointer value, or a prvalue core constant expression of type
856 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000857 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000858
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000859 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
860 // ... the address of an object with static storage duration,
861 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
862 return VD->hasGlobalStorage();
863 // ... the address of a function,
864 return isa<FunctionDecl>(D);
865 }
866
867 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000868 switch (E->getStmtClass()) {
869 default:
870 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000871 case Expr::CompoundLiteralExprClass:
872 return cast<CompoundLiteralExpr>(E)->isFileScope();
873 // A string literal has static storage duration.
874 case Expr::StringLiteralClass:
875 case Expr::PredefinedExprClass:
876 case Expr::ObjCStringLiteralClass:
877 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000878 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000879 return true;
880 case Expr::CallExprClass:
881 return IsStringLiteralCall(cast<CallExpr>(E));
882 // For GCC compatibility, &&label has static storage duration.
883 case Expr::AddrLabelExprClass:
884 return true;
885 // A Block literal expression may be used as the initialization value for
886 // Block variables at global or local static scope.
887 case Expr::BlockExprClass:
888 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000889 case Expr::ImplicitValueInitExprClass:
890 // FIXME:
891 // We can never form an lvalue with an implicit value initialization as its
892 // base through expression evaluation, so these only appear in one case: the
893 // implicit variable declaration we invent when checking whether a constexpr
894 // constructor can produce a constant expression. We must assume that such
895 // an expression might be a global lvalue.
896 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000897 }
John McCall42c8f872010-05-10 23:27:23 +0000898}
899
Richard Smith9a17a682011-11-07 05:07:52 +0000900/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +0000901/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +0000902/// either LValue or CCValue. Return true if we can fold this expression,
903/// whether or not it's a constant expression.
Richard Smith9a17a682011-11-07 05:07:52 +0000904template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000905static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000906 const T &LVal, APValue &Value,
907 CheckConstantExpressionKind CCEK) {
908 APValue::LValueBase Base = LVal.getLValueBase();
909 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
910
911 if (!IsGlobalLValue(Base)) {
912 if (Info.getLangOpts().CPlusPlus0x) {
913 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
914 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
915 << E->isGLValue() << !Designator.Entries.empty()
916 << !!VD << CCEK << VD;
917 if (VD)
918 Info.Note(VD->getLocation(), diag::note_declared_at);
919 else
920 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
921 diag::note_constexpr_temporary_here);
922 } else {
Richard Smith7098cbd2011-12-21 05:04:46 +0000923 Info.Diag(E->getExprLoc());
Richard Smithc1c5f272011-12-13 06:39:58 +0000924 }
Richard Smith61e61622012-01-12 06:08:57 +0000925 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000926 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000927 }
Richard Smith9a17a682011-11-07 05:07:52 +0000928
Richard Smithb4e85ed2012-01-06 16:39:00 +0000929 bool IsReferenceType = E->isGLValue();
930
931 if (Designator.Invalid) {
Richard Smith61e61622012-01-12 06:08:57 +0000932 // This is not a core constant expression. An appropriate diagnostic will
933 // have already been produced.
Richard Smith9a17a682011-11-07 05:07:52 +0000934 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
935 APValue::NoLValuePath());
936 return true;
937 }
938
Richard Smithb4e85ed2012-01-06 16:39:00 +0000939 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
940 Designator.Entries, Designator.IsOnePastTheEnd);
941
942 // Allow address constant expressions to be past-the-end pointers. This is
943 // an extension: the standard requires them to point to an object.
944 if (!IsReferenceType)
945 return true;
946
947 // A reference constant expression must refer to an object.
948 if (!Base) {
949 // FIXME: diagnostic
950 Info.CCEDiag(E->getExprLoc());
Richard Smith61e61622012-01-12 06:08:57 +0000951 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000952 }
953
Richard Smithc1c5f272011-12-13 06:39:58 +0000954 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +0000955 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000956 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
957 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
958 << !Designator.Entries.empty() << !!VD << VD;
959 if (VD)
960 Info.Note(VD->getLocation(), diag::note_declared_at);
961 else
962 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
963 diag::note_constexpr_temporary_here);
Richard Smithc1c5f272011-12-13 06:39:58 +0000964 }
965
Richard Smith9a17a682011-11-07 05:07:52 +0000966 return true;
967}
968
Richard Smith51201882011-12-30 21:15:51 +0000969/// Check that this core constant expression is of literal type, and if not,
970/// produce an appropriate diagnostic.
971static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
972 if (!E->isRValue() || E->getType()->isLiteralType())
973 return true;
974
975 // Prvalue constant expressions must be of literal types.
976 if (Info.getLangOpts().CPlusPlus0x)
977 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
978 << E->getType();
979 else
980 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
981 return false;
982}
983
Richard Smith47a1eed2011-10-29 20:57:55 +0000984/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000985/// constant expression, and if it is, produce the corresponding constant value.
Richard Smith51201882011-12-30 21:15:51 +0000986/// If not, report an appropriate diagnostic. Does not check that the expression
987/// is of literal type.
Richard Smithf48fdb02011-12-09 22:58:01 +0000988static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000989 const CCValue &CCValue, APValue &Value,
990 CheckConstantExpressionKind CCEK
991 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +0000992 if (!CCValue.isLValue()) {
993 Value = CCValue;
994 return true;
995 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000996 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +0000997}
998
Richard Smith9e36b532011-10-31 05:11:32 +0000999const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001000 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001001}
1002
1003static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001004 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +00001005}
1006
Richard Smith65ac5982011-11-01 21:06:14 +00001007static bool IsWeakLValue(const LValue &Value) {
1008 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001009 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001010}
1011
Richard Smithe24f5fc2011-11-17 22:56:20 +00001012static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001013 // A null base expression indicates a null pointer. These are always
1014 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001015 if (!Value.getLValueBase()) {
1016 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001017 return true;
1018 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001019
Richard Smithe24f5fc2011-11-17 22:56:20 +00001020 // We have a non-null base. These are generally known to be true, but if it's
1021 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001022 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001023 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001024 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001025}
1026
Richard Smith47a1eed2011-10-29 20:57:55 +00001027static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001028 switch (Val.getKind()) {
1029 case APValue::Uninitialized:
1030 return false;
1031 case APValue::Int:
1032 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001033 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001034 case APValue::Float:
1035 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001036 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001037 case APValue::ComplexInt:
1038 Result = Val.getComplexIntReal().getBoolValue() ||
1039 Val.getComplexIntImag().getBoolValue();
1040 return true;
1041 case APValue::ComplexFloat:
1042 Result = !Val.getComplexFloatReal().isZero() ||
1043 !Val.getComplexFloatImag().isZero();
1044 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001045 case APValue::LValue:
1046 return EvalPointerValueAsBool(Val, Result);
1047 case APValue::MemberPointer:
1048 Result = Val.getMemberPointerDecl();
1049 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001050 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001051 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001052 case APValue::Struct:
1053 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001054 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001055 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001056 }
1057
Richard Smithc49bd112011-10-28 17:51:58 +00001058 llvm_unreachable("unknown APValue kind");
1059}
1060
1061static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1062 EvalInfo &Info) {
1063 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001064 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001065 if (!Evaluate(Val, Info, E))
1066 return false;
1067 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001068}
1069
Richard Smithc1c5f272011-12-13 06:39:58 +00001070template<typename T>
1071static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1072 const T &SrcValue, QualType DestType) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001073 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001074 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001075 return false;
1076}
1077
1078static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1079 QualType SrcType, const APFloat &Value,
1080 QualType DestType, APSInt &Result) {
1081 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001082 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001083 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Richard Smithc1c5f272011-12-13 06:39:58 +00001085 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001086 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001087 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1088 & APFloat::opInvalidOp)
1089 return HandleOverflow(Info, E, Value, DestType);
1090 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001091}
1092
Richard Smithc1c5f272011-12-13 06:39:58 +00001093static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1094 QualType SrcType, QualType DestType,
1095 APFloat &Result) {
1096 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001097 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001098 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1099 APFloat::rmNearestTiesToEven, &ignored)
1100 & APFloat::opOverflow)
1101 return HandleOverflow(Info, E, Value, DestType);
1102 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001103}
1104
Richard Smithf72fccf2012-01-30 22:27:01 +00001105static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1106 QualType DestType, QualType SrcType,
1107 APSInt &Value) {
1108 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001109 APSInt Result = Value;
1110 // Figure out if this is a truncate, extend or noop cast.
1111 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001112 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001113 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001114 return Result;
1115}
1116
Richard Smithc1c5f272011-12-13 06:39:58 +00001117static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1118 QualType SrcType, const APSInt &Value,
1119 QualType DestType, APFloat &Result) {
1120 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1121 if (Result.convertFromAPInt(Value, Value.isSigned(),
1122 APFloat::rmNearestTiesToEven)
1123 & APFloat::opOverflow)
1124 return HandleOverflow(Info, E, Value, DestType);
1125 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001126}
1127
Eli Friedmane6a24e82011-12-22 03:51:45 +00001128static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1129 llvm::APInt &Res) {
1130 CCValue SVal;
1131 if (!Evaluate(SVal, Info, E))
1132 return false;
1133 if (SVal.isInt()) {
1134 Res = SVal.getInt();
1135 return true;
1136 }
1137 if (SVal.isFloat()) {
1138 Res = SVal.getFloat().bitcastToAPInt();
1139 return true;
1140 }
1141 if (SVal.isVector()) {
1142 QualType VecTy = E->getType();
1143 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1144 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1145 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1146 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1147 Res = llvm::APInt::getNullValue(VecSize);
1148 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1149 APValue &Elt = SVal.getVectorElt(i);
1150 llvm::APInt EltAsInt;
1151 if (Elt.isInt()) {
1152 EltAsInt = Elt.getInt();
1153 } else if (Elt.isFloat()) {
1154 EltAsInt = Elt.getFloat().bitcastToAPInt();
1155 } else {
1156 // Don't try to handle vectors of anything other than int or float
1157 // (not sure if it's possible to hit this case).
1158 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1159 return false;
1160 }
1161 unsigned BaseEltSize = EltAsInt.getBitWidth();
1162 if (BigEndian)
1163 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1164 else
1165 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1166 }
1167 return true;
1168 }
1169 // Give up if the input isn't an int, float, or vector. For example, we
1170 // reject "(v4i16)(intptr_t)&a".
1171 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1172 return false;
1173}
1174
Richard Smithb4e85ed2012-01-06 16:39:00 +00001175/// Cast an lvalue referring to a base subobject to a derived class, by
1176/// truncating the lvalue's path to the given length.
1177static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1178 const RecordDecl *TruncatedType,
1179 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001180 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001181
1182 // Check we actually point to a derived class object.
1183 if (TruncatedElements == D.Entries.size())
1184 return true;
1185 assert(TruncatedElements >= D.MostDerivedPathLength &&
1186 "not casting to a derived class");
1187 if (!Result.checkSubobject(Info, E, CSK_Derived))
1188 return false;
1189
1190 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001191 const RecordDecl *RD = TruncatedType;
1192 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001193 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1194 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001195 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001196 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001197 else
Richard Smith180f4792011-11-10 06:34:14 +00001198 Result.Offset -= Layout.getBaseClassOffset(Base);
1199 RD = Base;
1200 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001201 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001202 return true;
1203}
1204
Richard Smithb4e85ed2012-01-06 16:39:00 +00001205static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001206 const CXXRecordDecl *Derived,
1207 const CXXRecordDecl *Base,
1208 const ASTRecordLayout *RL = 0) {
1209 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1210 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001211 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001212}
1213
Richard Smithb4e85ed2012-01-06 16:39:00 +00001214static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001215 const CXXRecordDecl *DerivedDecl,
1216 const CXXBaseSpecifier *Base) {
1217 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1218
1219 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001220 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001221 return true;
1222 }
1223
Richard Smithb4e85ed2012-01-06 16:39:00 +00001224 SubobjectDesignator &D = Obj.Designator;
1225 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001226 return false;
1227
Richard Smithb4e85ed2012-01-06 16:39:00 +00001228 // Extract most-derived object and corresponding type.
1229 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1230 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1231 return false;
1232
1233 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001234 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1235 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001236 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001237 return true;
1238}
1239
1240/// Update LVal to refer to the given field, which must be a member of the type
1241/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001242static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001243 const FieldDecl *FD,
1244 const ASTRecordLayout *RL = 0) {
1245 if (!RL)
1246 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1247
1248 unsigned I = FD->getFieldIndex();
1249 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001250 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001251}
1252
Richard Smithd9b02e72012-01-25 22:15:11 +00001253/// Update LVal to refer to the given indirect field.
1254static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1255 LValue &LVal,
1256 const IndirectFieldDecl *IFD) {
1257 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1258 CE = IFD->chain_end(); C != CE; ++C)
1259 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1260}
1261
Richard Smith180f4792011-11-10 06:34:14 +00001262/// Get the size of the given type in char units.
1263static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1264 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1265 // extension.
1266 if (Type->isVoidType() || Type->isFunctionType()) {
1267 Size = CharUnits::One();
1268 return true;
1269 }
1270
1271 if (!Type->isConstantSizeType()) {
1272 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001273 // FIXME: Diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001274 return false;
1275 }
1276
1277 Size = Info.Ctx.getTypeSizeInChars(Type);
1278 return true;
1279}
1280
1281/// Update a pointer value to model pointer arithmetic.
1282/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001283/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001284/// \param LVal - The pointer value to be updated.
1285/// \param EltTy - The pointee type represented by LVal.
1286/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001287static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1288 LValue &LVal, QualType EltTy,
1289 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001290 CharUnits SizeOfPointee;
1291 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1292 return false;
1293
1294 // Compute the new offset in the appropriate width.
1295 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001296 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001297 return true;
1298}
1299
Richard Smith03f96112011-10-24 17:54:18 +00001300/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001301static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1302 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001303 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001304 // If this is a parameter to an active constexpr function call, perform
1305 // argument substitution.
1306 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001307 // Assume arguments of a potential constant expression are unknown
1308 // constant expressions.
1309 if (Info.CheckingPotentialConstantExpression)
1310 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001311 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001312 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001313 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001314 }
Richard Smith177dce72011-11-01 16:57:24 +00001315 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1316 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001317 }
Richard Smith03f96112011-10-24 17:54:18 +00001318
Richard Smith099e7f62011-12-19 06:19:21 +00001319 // Dig out the initializer, and use the declaration which it's attached to.
1320 const Expr *Init = VD->getAnyInitializer(VD);
1321 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001322 // If we're checking a potential constant expression, the variable could be
1323 // initialized later.
1324 if (!Info.CheckingPotentialConstantExpression)
1325 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001326 return false;
1327 }
1328
Richard Smith180f4792011-11-10 06:34:14 +00001329 // If we're currently evaluating the initializer of this declaration, use that
1330 // in-flight value.
1331 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001332 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1333 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001334 return !Result.isUninit();
1335 }
1336
Richard Smith65ac5982011-11-01 21:06:14 +00001337 // Never evaluate the initializer of a weak variable. We can't be sure that
1338 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001339 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001340 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001341 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001342 }
Richard Smith65ac5982011-11-01 21:06:14 +00001343
Richard Smith099e7f62011-12-19 06:19:21 +00001344 // Check that we can fold the initializer. In C++, we will have already done
1345 // this in the cases where it matters for conformance.
1346 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1347 if (!VD->evaluateValue(Notes)) {
1348 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1349 Notes.size() + 1) << VD;
1350 Info.Note(VD->getLocation(), diag::note_declared_at);
1351 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001352 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001353 } else if (!VD->checkInitIsICE()) {
1354 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1355 Notes.size() + 1) << VD;
1356 Info.Note(VD->getLocation(), diag::note_declared_at);
1357 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001358 }
Richard Smith03f96112011-10-24 17:54:18 +00001359
Richard Smithb4e85ed2012-01-06 16:39:00 +00001360 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001361 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001362}
1363
Richard Smithc49bd112011-10-28 17:51:58 +00001364static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001365 Qualifiers Quals = T.getQualifiers();
1366 return Quals.hasConst() && !Quals.hasVolatile();
1367}
1368
Richard Smith59efe262011-11-11 04:05:33 +00001369/// Get the base index of the given base class within an APValue representing
1370/// the given derived class.
1371static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1372 const CXXRecordDecl *Base) {
1373 Base = Base->getCanonicalDecl();
1374 unsigned Index = 0;
1375 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1376 E = Derived->bases_end(); I != E; ++I, ++Index) {
1377 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1378 return Index;
1379 }
1380
1381 llvm_unreachable("base class missing from derived class's bases list");
1382}
1383
Richard Smithcc5d4f62011-11-07 09:22:26 +00001384/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001385static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1386 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001387 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001388 if (Sub.Invalid)
1389 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001390 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001391 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001392 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001393 (unsigned)diag::note_constexpr_read_past_end :
1394 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001395 return false;
1396 }
Richard Smithf64699e2011-11-11 08:28:03 +00001397 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001398 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001399 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1400 // This object might be initialized later.
1401 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001402
1403 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1404 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001405 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001406 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001407 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001408 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001409 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001410 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001411 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001412 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001413 // Note, it should not be possible to form a pointer with a valid
1414 // designator which points more than one past the end of the array.
1415 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001416 (unsigned)diag::note_constexpr_read_past_end :
1417 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001418 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001419 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001420 if (O->getArrayInitializedElts() > Index)
1421 O = &O->getArrayInitializedElt(Index);
1422 else
1423 O = &O->getArrayFiller();
1424 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001425 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1426 // Next subobject is a class, struct or union field.
1427 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1428 if (RD->isUnion()) {
1429 const FieldDecl *UnionField = O->getUnionField();
1430 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001431 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001432 Info.Diag(E->getExprLoc(),
1433 diag::note_constexpr_read_inactive_union_member)
1434 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001435 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001436 }
Richard Smith180f4792011-11-10 06:34:14 +00001437 O = &O->getUnionValue();
1438 } else
1439 O = &O->getStructField(Field->getFieldIndex());
1440 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001441
1442 if (ObjType.isVolatileQualified()) {
1443 if (Info.getLangOpts().CPlusPlus) {
1444 // FIXME: Include a description of the path to the volatile subobject.
1445 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1446 << 2 << Field;
1447 Info.Note(Field->getLocation(), diag::note_declared_at);
1448 } else {
1449 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1450 }
1451 return false;
1452 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001453 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001454 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001455 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1456 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1457 O = &O->getStructBase(getBaseIndex(Derived, Base));
1458 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001459 }
Richard Smith180f4792011-11-10 06:34:14 +00001460
Richard Smithf48fdb02011-12-09 22:58:01 +00001461 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001462 if (!Info.CheckingPotentialConstantExpression)
1463 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001464 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001465 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001466 }
1467
Richard Smithb4e85ed2012-01-06 16:39:00 +00001468 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001469 return true;
1470}
1471
Richard Smith180f4792011-11-10 06:34:14 +00001472/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1473/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1474/// for looking up the glvalue referred to by an entity of reference type.
1475///
1476/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001477/// \param Conv - The expression for which we are performing the conversion.
1478/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001479/// \param Type - The type we expect this conversion to produce.
1480/// \param LVal - The glvalue on which we are attempting to perform this action.
1481/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001482static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1483 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001484 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001485 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1486 if (!Info.getLangOpts().CPlusPlus)
1487 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1488
Richard Smithb4e85ed2012-01-06 16:39:00 +00001489 if (LVal.Designator.Invalid)
1490 // A diagnostic will have already been produced.
1491 return false;
1492
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001493 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001494 CallStackFrame *Frame = LVal.Frame;
Richard Smith7098cbd2011-12-21 05:04:46 +00001495 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001496
Richard Smithf48fdb02011-12-09 22:58:01 +00001497 if (!LVal.Base) {
1498 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001499 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1500 return false;
1501 }
1502
1503 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1504 // is not a constant expression (even if the object is non-volatile). We also
1505 // apply this rule to C++98, in order to conform to the expected 'volatile'
1506 // semantics.
1507 if (Type.isVolatileQualified()) {
1508 if (Info.getLangOpts().CPlusPlus)
1509 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1510 else
1511 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001512 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001513 }
Richard Smithc49bd112011-10-28 17:51:58 +00001514
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001515 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001516 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1517 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001518 // expressions are constant expressions too. Inside constexpr functions,
1519 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001520 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001521 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001522 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001523 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001524 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001525 }
1526
Richard Smith7098cbd2011-12-21 05:04:46 +00001527 // DR1313: If the object is volatile-qualified but the glvalue was not,
1528 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001529 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001530 if (VT.isVolatileQualified()) {
1531 if (Info.getLangOpts().CPlusPlus) {
1532 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1533 Info.Note(VD->getLocation(), diag::note_declared_at);
1534 } else {
1535 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001536 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001537 return false;
1538 }
1539
1540 if (!isa<ParmVarDecl>(VD)) {
1541 if (VD->isConstexpr()) {
1542 // OK, we can read this variable.
1543 } else if (VT->isIntegralOrEnumerationType()) {
1544 if (!VT.isConstQualified()) {
1545 if (Info.getLangOpts().CPlusPlus) {
1546 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1547 Info.Note(VD->getLocation(), diag::note_declared_at);
1548 } else {
1549 Info.Diag(Loc);
1550 }
1551 return false;
1552 }
1553 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1554 // We support folding of const floating-point types, in order to make
1555 // static const data members of such types (supported as an extension)
1556 // more useful.
1557 if (Info.getLangOpts().CPlusPlus0x) {
1558 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1559 Info.Note(VD->getLocation(), diag::note_declared_at);
1560 } else {
1561 Info.CCEDiag(Loc);
1562 }
1563 } else {
1564 // FIXME: Allow folding of values of any literal type in all languages.
1565 if (Info.getLangOpts().CPlusPlus0x) {
1566 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1567 Info.Note(VD->getLocation(), diag::note_declared_at);
1568 } else {
1569 Info.Diag(Loc);
1570 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001571 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001572 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001573 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001574
Richard Smithf48fdb02011-12-09 22:58:01 +00001575 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001576 return false;
1577
Richard Smith47a1eed2011-10-29 20:57:55 +00001578 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001579 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001580
1581 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1582 // conversion. This happens when the declaration and the lvalue should be
1583 // considered synonymous, for instance when initializing an array of char
1584 // from a string literal. Continue as if the initializer lvalue was the
1585 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001586 assert(RVal.getLValueOffset().isZero() &&
1587 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001588 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001589 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001590 }
1591
Richard Smith7098cbd2011-12-21 05:04:46 +00001592 // Volatile temporary objects cannot be read in constant expressions.
1593 if (Base->getType().isVolatileQualified()) {
1594 if (Info.getLangOpts().CPlusPlus) {
1595 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1596 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1597 } else {
1598 Info.Diag(Loc);
1599 }
1600 return false;
1601 }
1602
Richard Smith0a3bdb62011-11-04 02:25:55 +00001603 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1604 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1605 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001606 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001607 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001608 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001609 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001610
1611 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001612 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith7098cbd2011-12-21 05:04:46 +00001613 const ConstantArrayType *CAT =
1614 Info.Ctx.getAsConstantArrayType(S->getType());
1615 if (Index >= CAT->getSize().getZExtValue()) {
1616 // Note, it should not be possible to form a pointer which points more
1617 // than one past the end of the array without producing a prior const expr
1618 // diagnostic.
1619 Info.Diag(Loc, diag::note_constexpr_read_past_end);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001620 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001621 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001622 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1623 Type->isUnsignedIntegerType());
1624 if (Index < S->getLength())
1625 Value = S->getCodeUnit(Index);
1626 RVal = CCValue(Value);
1627 return true;
1628 }
1629
Richard Smithcc5d4f62011-11-07 09:22:26 +00001630 if (Frame) {
1631 // If this is a temporary expression with a nontrivial initializer, grab the
1632 // value from the relevant stack frame.
1633 RVal = Frame->Temporaries[Base];
1634 } else if (const CompoundLiteralExpr *CLE
1635 = dyn_cast<CompoundLiteralExpr>(Base)) {
1636 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1637 // initializer until now for such expressions. Such an expression can't be
1638 // an ICE in C, so this only matters for fold.
1639 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1640 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1641 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001642 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001643 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001644 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001645 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001646
Richard Smithf48fdb02011-12-09 22:58:01 +00001647 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1648 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001649}
1650
Richard Smith59efe262011-11-11 04:05:33 +00001651/// Build an lvalue for the object argument of a member function call.
1652static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1653 LValue &This) {
1654 if (Object->getType()->isPointerType())
1655 return EvaluatePointer(Object, This, Info);
1656
1657 if (Object->isGLValue())
1658 return EvaluateLValue(Object, This, Info);
1659
Richard Smithe24f5fc2011-11-17 22:56:20 +00001660 if (Object->getType()->isLiteralType())
1661 return EvaluateTemporary(Object, This, Info);
1662
1663 return false;
1664}
1665
1666/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1667/// lvalue referring to the result.
1668///
1669/// \param Info - Information about the ongoing evaluation.
1670/// \param BO - The member pointer access operation.
1671/// \param LV - Filled in with a reference to the resulting object.
1672/// \param IncludeMember - Specifies whether the member itself is included in
1673/// the resulting LValue subobject designator. This is not possible when
1674/// creating a bound member function.
1675/// \return The field or method declaration to which the member pointer refers,
1676/// or 0 if evaluation fails.
1677static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1678 const BinaryOperator *BO,
1679 LValue &LV,
1680 bool IncludeMember = true) {
1681 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1682
Richard Smith745f5142012-01-27 01:14:48 +00001683 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1684 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001685 return 0;
1686
1687 MemberPtr MemPtr;
1688 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1689 return 0;
1690
1691 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1692 // member value, the behavior is undefined.
1693 if (!MemPtr.getDecl())
1694 return 0;
1695
Richard Smith745f5142012-01-27 01:14:48 +00001696 if (!EvalObjOK)
1697 return 0;
1698
Richard Smithe24f5fc2011-11-17 22:56:20 +00001699 if (MemPtr.isDerivedMember()) {
1700 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001701 // The end of the derived-to-base path for the base object must match the
1702 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001703 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001704 LV.Designator.Entries.size())
1705 return 0;
1706 unsigned PathLengthToMember =
1707 LV.Designator.Entries.size() - MemPtr.Path.size();
1708 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1709 const CXXRecordDecl *LVDecl = getAsBaseClass(
1710 LV.Designator.Entries[PathLengthToMember + I]);
1711 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1712 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1713 return 0;
1714 }
1715
1716 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001717 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1718 PathLengthToMember))
1719 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001720 } else if (!MemPtr.Path.empty()) {
1721 // Extend the LValue path with the member pointer's path.
1722 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1723 MemPtr.Path.size() + IncludeMember);
1724
1725 // Walk down to the appropriate base class.
1726 QualType LVType = BO->getLHS()->getType();
1727 if (const PointerType *PT = LVType->getAs<PointerType>())
1728 LVType = PT->getPointeeType();
1729 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1730 assert(RD && "member pointer access on non-class-type expression");
1731 // The first class in the path is that of the lvalue.
1732 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1733 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001734 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001735 RD = Base;
1736 }
1737 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001738 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001739 }
1740
1741 // Add the member. Note that we cannot build bound member functions here.
1742 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001743 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1744 HandleLValueMember(Info, BO, LV, FD);
1745 else if (const IndirectFieldDecl *IFD =
1746 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1747 HandleLValueIndirectMember(Info, BO, LV, IFD);
1748 else
1749 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001750 }
1751
1752 return MemPtr.getDecl();
1753}
1754
1755/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1756/// the provided lvalue, which currently refers to the base object.
1757static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1758 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001759 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001760 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001761 return false;
1762
Richard Smithb4e85ed2012-01-06 16:39:00 +00001763 QualType TargetQT = E->getType();
1764 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1765 TargetQT = PT->getPointeeType();
1766
1767 // Check this cast lands within the final derived-to-base subobject path.
1768 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1769 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1770 << D.MostDerivedType << TargetQT;
1771 return false;
1772 }
1773
Richard Smithe24f5fc2011-11-17 22:56:20 +00001774 // Check the type of the final cast. We don't need to check the path,
1775 // since a cast can only be formed if the path is unique.
1776 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001777 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1778 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001779 if (NewEntriesSize == D.MostDerivedPathLength)
1780 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1781 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001782 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001783 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1784 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1785 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001786 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001787 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001788
1789 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001790 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001791}
1792
Mike Stumpc4c90452009-10-27 22:09:17 +00001793namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001794enum EvalStmtResult {
1795 /// Evaluation failed.
1796 ESR_Failed,
1797 /// Hit a 'return' statement.
1798 ESR_Returned,
1799 /// Evaluation succeeded.
1800 ESR_Succeeded
1801};
1802}
1803
1804// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001805static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001806 const Stmt *S) {
1807 switch (S->getStmtClass()) {
1808 default:
1809 return ESR_Failed;
1810
1811 case Stmt::NullStmtClass:
1812 case Stmt::DeclStmtClass:
1813 return ESR_Succeeded;
1814
Richard Smithc1c5f272011-12-13 06:39:58 +00001815 case Stmt::ReturnStmtClass: {
1816 CCValue CCResult;
1817 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1818 if (!Evaluate(CCResult, Info, RetExpr) ||
1819 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1820 CCEK_ReturnValue))
1821 return ESR_Failed;
1822 return ESR_Returned;
1823 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001824
1825 case Stmt::CompoundStmtClass: {
1826 const CompoundStmt *CS = cast<CompoundStmt>(S);
1827 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1828 BE = CS->body_end(); BI != BE; ++BI) {
1829 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1830 if (ESR != ESR_Succeeded)
1831 return ESR;
1832 }
1833 return ESR_Succeeded;
1834 }
1835 }
1836}
1837
Richard Smith61802452011-12-22 02:22:31 +00001838/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1839/// default constructor. If so, we'll fold it whether or not it's marked as
1840/// constexpr. If it is marked as constexpr, we will never implicitly define it,
1841/// so we need special handling.
1842static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00001843 const CXXConstructorDecl *CD,
1844 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001845 if (!CD->isTrivial() || !CD->isDefaultConstructor())
1846 return false;
1847
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001848 // Value-initialization does not call a trivial default constructor, so such a
1849 // call is a core constant expression whether or not the constructor is
1850 // constexpr.
1851 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00001852 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00001853 // FIXME: If DiagDecl is an implicitly-declared special member function,
1854 // we should be much more explicit about why it's not constexpr.
1855 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1856 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1857 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00001858 } else {
1859 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1860 }
1861 }
1862 return true;
1863}
1864
Richard Smithc1c5f272011-12-13 06:39:58 +00001865/// CheckConstexprFunction - Check that a function can be called in a constant
1866/// expression.
1867static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1868 const FunctionDecl *Declaration,
1869 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00001870 // Potential constant expressions can contain calls to declared, but not yet
1871 // defined, constexpr functions.
1872 if (Info.CheckingPotentialConstantExpression && !Definition &&
1873 Declaration->isConstexpr())
1874 return false;
1875
Richard Smithc1c5f272011-12-13 06:39:58 +00001876 // Can we evaluate this function call?
1877 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1878 return true;
1879
1880 if (Info.getLangOpts().CPlusPlus0x) {
1881 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00001882 // FIXME: If DiagDecl is an implicitly-declared special member function, we
1883 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00001884 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1885 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1886 << DiagDecl;
1887 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1888 } else {
1889 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1890 }
1891 return false;
1892}
1893
Richard Smith180f4792011-11-10 06:34:14 +00001894namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001895typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001896}
1897
1898/// EvaluateArgs - Evaluate the arguments to a function call.
1899static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1900 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00001901 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001902 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00001903 I != E; ++I) {
1904 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
1905 // If we're checking for a potential constant expression, evaluate all
1906 // initializers even if some of them fail.
1907 if (!Info.keepEvaluatingAfterFailure())
1908 return false;
1909 Success = false;
1910 }
1911 }
1912 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00001913}
1914
Richard Smithd0dccea2011-10-28 22:34:42 +00001915/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00001916static bool HandleFunctionCall(SourceLocation CallLoc,
1917 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00001918 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001919 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00001920 ArgVector ArgValues(Args.size());
1921 if (!EvaluateArgs(Args, ArgValues, Info))
1922 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001923
Richard Smith745f5142012-01-27 01:14:48 +00001924 if (!Info.CheckCallLimit(CallLoc))
1925 return false;
1926
1927 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001928 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1929}
1930
Richard Smith180f4792011-11-10 06:34:14 +00001931/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00001932static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001933 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001934 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00001935 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00001936 ArgVector ArgValues(Args.size());
1937 if (!EvaluateArgs(Args, ArgValues, Info))
1938 return false;
1939
Richard Smith745f5142012-01-27 01:14:48 +00001940 if (!Info.CheckCallLimit(CallLoc))
1941 return false;
1942
1943 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00001944
1945 // If it's a delegating constructor, just delegate.
1946 if (Definition->isDelegatingConstructor()) {
1947 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1948 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1949 }
1950
Richard Smith610a60c2012-01-10 04:32:03 +00001951 // For a trivial copy or move constructor, perform an APValue copy. This is
1952 // essential for unions, where the operations performed by the constructor
1953 // cannot be represented by ctor-initializers.
Richard Smith180f4792011-11-10 06:34:14 +00001954 const CXXRecordDecl *RD = Definition->getParent();
Richard Smith610a60c2012-01-10 04:32:03 +00001955 if (Definition->isDefaulted() &&
1956 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
1957 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
1958 LValue RHS;
1959 RHS.setFrom(ArgValues[0]);
1960 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00001961 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
1962 RHS, Value))
1963 return false;
1964 assert((Value.isStruct() || Value.isUnion()) &&
1965 "trivial copy/move from non-class type?");
1966 // Any CCValue of class type must already be a constant expression.
1967 Result = Value;
1968 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00001969 }
1970
1971 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00001972 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00001973 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1974 std::distance(RD->field_begin(), RD->field_end()));
1975
1976 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1977
Richard Smith745f5142012-01-27 01:14:48 +00001978 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00001979 unsigned BasesSeen = 0;
1980#ifndef NDEBUG
1981 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1982#endif
1983 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1984 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00001985 LValue Subobject = This;
1986 APValue *Value = &Result;
1987
1988 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00001989 if ((*I)->isBaseInitializer()) {
1990 QualType BaseType((*I)->getBaseClass(), 0);
1991#ifndef NDEBUG
1992 // Non-virtual base classes are initialized in the order in the class
1993 // definition. We cannot have a virtual base class for a literal type.
1994 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1995 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1996 "base class initializers not in expected order");
1997 ++BaseIt;
1998#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00001999 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002000 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002001 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002002 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002003 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002004 if (RD->isUnion()) {
2005 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002006 Value = &Result.getUnionValue();
2007 } else {
2008 Value = &Result.getStructField(FD->getFieldIndex());
2009 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002010 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002011 // Walk the indirect field decl's chain to find the object to initialize,
2012 // and make sure we've initialized every step along it.
2013 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2014 CE = IFD->chain_end();
2015 C != CE; ++C) {
2016 FieldDecl *FD = cast<FieldDecl>(*C);
2017 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2018 // Switch the union field if it differs. This happens if we had
2019 // preceding zero-initialization, and we're now initializing a union
2020 // subobject other than the first.
2021 // FIXME: In this case, the values of the other subobjects are
2022 // specified, since zero-initialization sets all padding bits to zero.
2023 if (Value->isUninit() ||
2024 (Value->isUnion() && Value->getUnionField() != FD)) {
2025 if (CD->isUnion())
2026 *Value = APValue(FD);
2027 else
2028 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2029 std::distance(CD->field_begin(), CD->field_end()));
2030 }
Richard Smith745f5142012-01-27 01:14:48 +00002031 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002032 if (CD->isUnion())
2033 Value = &Value->getUnionValue();
2034 else
2035 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002036 }
Richard Smith180f4792011-11-10 06:34:14 +00002037 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002038 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002039 }
Richard Smith745f5142012-01-27 01:14:48 +00002040
2041 if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
2042 (*I)->isBaseInitializer()
2043 ? CCEK_Constant : CCEK_MemberInit)) {
2044 // If we're checking for a potential constant expression, evaluate all
2045 // initializers even if some of them fail.
2046 if (!Info.keepEvaluatingAfterFailure())
2047 return false;
2048 Success = false;
2049 }
Richard Smith180f4792011-11-10 06:34:14 +00002050 }
2051
Richard Smith745f5142012-01-27 01:14:48 +00002052 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002053}
2054
Richard Smithd0dccea2011-10-28 22:34:42 +00002055namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002056class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002057 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002058 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002059public:
2060
Richard Smith1e12c592011-10-16 21:26:27 +00002061 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002062
2063 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002064 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002065 return true;
2066 }
2067
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002068 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2069 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002070 return Visit(E->getResultExpr());
2071 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002072 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002073 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002074 return true;
2075 return false;
2076 }
John McCallf85e1932011-06-15 23:02:42 +00002077 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002078 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002079 return true;
2080 return false;
2081 }
2082 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002083 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002084 return true;
2085 return false;
2086 }
2087
Mike Stumpc4c90452009-10-27 22:09:17 +00002088 // We don't want to evaluate BlockExprs multiple times, as they generate
2089 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002090 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2091 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2092 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002093 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002094 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2095 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2096 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2097 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2098 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2099 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002100 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002101 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002102 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002103 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002104 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002105 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2106 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2107 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2108 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002109 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002110 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2111 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2112 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2113 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2114 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002115 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002116 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002117 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002118 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002119 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002120
2121 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002122 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002123 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2124 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002125 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002126 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002127 return false;
2128 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002129
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002130 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002131};
2132
John McCall56ca35d2011-02-17 10:25:35 +00002133class OpaqueValueEvaluation {
2134 EvalInfo &info;
2135 OpaqueValueExpr *opaqueValue;
2136
2137public:
2138 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2139 Expr *value)
2140 : info(info), opaqueValue(opaqueValue) {
2141
2142 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002143 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002144 this->opaqueValue = 0;
2145 return;
2146 }
John McCall56ca35d2011-02-17 10:25:35 +00002147 }
2148
2149 bool hasError() const { return opaqueValue == 0; }
2150
2151 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00002152 // FIXME: This will not work for recursive constexpr functions using opaque
2153 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00002154 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2155 }
2156};
2157
Mike Stumpc4c90452009-10-27 22:09:17 +00002158} // end anonymous namespace
2159
Eli Friedman4efaa272008-11-12 09:44:48 +00002160//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002161// Generic Evaluation
2162//===----------------------------------------------------------------------===//
2163namespace {
2164
Richard Smithf48fdb02011-12-09 22:58:01 +00002165// FIXME: RetTy is always bool. Remove it.
2166template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002167class ExprEvaluatorBase
2168 : public ConstStmtVisitor<Derived, RetTy> {
2169private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002170 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002171 return static_cast<Derived*>(this)->Success(V, E);
2172 }
Richard Smith51201882011-12-30 21:15:51 +00002173 RetTy DerivedZeroInitialization(const Expr *E) {
2174 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002175 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002176
2177protected:
2178 EvalInfo &Info;
2179 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2180 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2181
Richard Smithdd1f29b2011-12-12 09:28:41 +00002182 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002183 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002184 }
2185
2186 /// Report an evaluation error. This should only be called when an error is
2187 /// first discovered. When propagating an error, just return false.
2188 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002189 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002190 return false;
2191 }
2192 bool Error(const Expr *E) {
2193 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2194 }
2195
Richard Smith51201882011-12-30 21:15:51 +00002196 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002197
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002198public:
2199 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2200
2201 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002202 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002203 }
2204 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002205 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002206 }
2207
2208 RetTy VisitParenExpr(const ParenExpr *E)
2209 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2210 RetTy VisitUnaryExtension(const UnaryOperator *E)
2211 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2212 RetTy VisitUnaryPlus(const UnaryOperator *E)
2213 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2214 RetTy VisitChooseExpr(const ChooseExpr *E)
2215 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2216 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2217 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002218 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2219 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002220 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2221 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002222 // We cannot create any objects for which cleanups are required, so there is
2223 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2224 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2225 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002226
Richard Smithc216a012011-12-12 12:46:16 +00002227 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2228 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2229 return static_cast<Derived*>(this)->VisitCastExpr(E);
2230 }
2231 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2232 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2233 return static_cast<Derived*>(this)->VisitCastExpr(E);
2234 }
2235
Richard Smithe24f5fc2011-11-17 22:56:20 +00002236 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2237 switch (E->getOpcode()) {
2238 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002239 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002240
2241 case BO_Comma:
2242 VisitIgnoredValue(E->getLHS());
2243 return StmtVisitorTy::Visit(E->getRHS());
2244
2245 case BO_PtrMemD:
2246 case BO_PtrMemI: {
2247 LValue Obj;
2248 if (!HandleMemberPointerAccess(Info, E, Obj))
2249 return false;
2250 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002251 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002252 return false;
2253 return DerivedSuccess(Result, E);
2254 }
2255 }
2256 }
2257
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002258 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2259 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2260 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002261 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002262
2263 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00002264 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002265 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002266
2267 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2268 }
2269
2270 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2271 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002272 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002273 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002274
Richard Smithc49bd112011-10-28 17:51:58 +00002275 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002276 return StmtVisitorTy::Visit(EvalExpr);
2277 }
2278
2279 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002280 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002281 if (!Value) {
2282 const Expr *Source = E->getSourceExpr();
2283 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002284 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002285 if (Source == E) { // sanity checking.
2286 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002287 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002288 }
2289 return StmtVisitorTy::Visit(Source);
2290 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002291 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002292 }
Richard Smithf10d9172011-10-11 21:43:33 +00002293
Richard Smithd0dccea2011-10-28 22:34:42 +00002294 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002295 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002296 QualType CalleeType = Callee->getType();
2297
Richard Smithd0dccea2011-10-28 22:34:42 +00002298 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002299 LValue *This = 0, ThisVal;
2300 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00002301
Richard Smith59efe262011-11-11 04:05:33 +00002302 // Extract function decl and 'this' pointer from the callee.
2303 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002304 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002305 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2306 // Explicit bound member calls, such as x.f() or p->g();
2307 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002308 return false;
2309 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002310 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002311 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2312 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002313 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2314 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002315 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002316 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002317 return Error(Callee);
2318
2319 FD = dyn_cast<FunctionDecl>(Member);
2320 if (!FD)
2321 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002322 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002323 LValue Call;
2324 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002325 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002326
Richard Smithb4e85ed2012-01-06 16:39:00 +00002327 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002328 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002329 FD = dyn_cast_or_null<FunctionDecl>(
2330 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002331 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002332 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002333
2334 // Overloaded operator calls to member functions are represented as normal
2335 // calls with '*this' as the first argument.
2336 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2337 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002338 // FIXME: When selecting an implicit conversion for an overloaded
2339 // operator delete, we sometimes try to evaluate calls to conversion
2340 // operators without a 'this' parameter!
2341 if (Args.empty())
2342 return Error(E);
2343
Richard Smith59efe262011-11-11 04:05:33 +00002344 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2345 return false;
2346 This = &ThisVal;
2347 Args = Args.slice(1);
2348 }
2349
2350 // Don't call function pointers which have been cast to some other type.
2351 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002352 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002353 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002354 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002355
Richard Smithc1c5f272011-12-13 06:39:58 +00002356 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002357 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00002358 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002359
Richard Smithc1c5f272011-12-13 06:39:58 +00002360 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002361 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2362 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002363 return false;
2364
Richard Smithb4e85ed2012-01-06 16:39:00 +00002365 return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002366 }
2367
Richard Smithc49bd112011-10-28 17:51:58 +00002368 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2369 return StmtVisitorTy::Visit(E->getInitializer());
2370 }
Richard Smithf10d9172011-10-11 21:43:33 +00002371 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002372 if (E->getNumInits() == 0)
2373 return DerivedZeroInitialization(E);
2374 if (E->getNumInits() == 1)
2375 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002376 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002377 }
2378 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002379 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002380 }
2381 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002382 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002383 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002384 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002385 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002386 }
Richard Smithf10d9172011-10-11 21:43:33 +00002387
Richard Smith180f4792011-11-10 06:34:14 +00002388 /// A member expression where the object is a prvalue is itself a prvalue.
2389 RetTy VisitMemberExpr(const MemberExpr *E) {
2390 assert(!E->isArrow() && "missing call to bound member function?");
2391
2392 CCValue Val;
2393 if (!Evaluate(Val, Info, E->getBase()))
2394 return false;
2395
2396 QualType BaseTy = E->getBase()->getType();
2397
2398 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002399 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002400 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2401 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2402 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2403
Richard Smithb4e85ed2012-01-06 16:39:00 +00002404 SubobjectDesignator Designator(BaseTy);
2405 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002406
Richard Smithf48fdb02011-12-09 22:58:01 +00002407 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002408 DerivedSuccess(Val, E);
2409 }
2410
Richard Smithc49bd112011-10-28 17:51:58 +00002411 RetTy VisitCastExpr(const CastExpr *E) {
2412 switch (E->getCastKind()) {
2413 default:
2414 break;
2415
David Chisnall7a7ee302012-01-16 17:27:18 +00002416 case CK_AtomicToNonAtomic:
2417 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002418 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002419 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002420 return StmtVisitorTy::Visit(E->getSubExpr());
2421
2422 case CK_LValueToRValue: {
2423 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002424 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2425 return false;
2426 CCValue RVal;
2427 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2428 return false;
2429 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002430 }
2431 }
2432
Richard Smithf48fdb02011-12-09 22:58:01 +00002433 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002434 }
2435
Richard Smith8327fad2011-10-24 18:44:57 +00002436 /// Visit a value which is evaluated, but whose value is ignored.
2437 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002438 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002439 if (!Evaluate(Scratch, Info, E))
2440 Info.EvalStatus.HasSideEffects = true;
2441 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002442};
2443
2444}
2445
2446//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002447// Common base class for lvalue and temporary evaluation.
2448//===----------------------------------------------------------------------===//
2449namespace {
2450template<class Derived>
2451class LValueExprEvaluatorBase
2452 : public ExprEvaluatorBase<Derived, bool> {
2453protected:
2454 LValue &Result;
2455 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2456 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2457
2458 bool Success(APValue::LValueBase B) {
2459 Result.set(B);
2460 return true;
2461 }
2462
2463public:
2464 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2465 ExprEvaluatorBaseTy(Info), Result(Result) {}
2466
2467 bool Success(const CCValue &V, const Expr *E) {
2468 Result.setFrom(V);
2469 return true;
2470 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002471
Richard Smithe24f5fc2011-11-17 22:56:20 +00002472 bool VisitMemberExpr(const MemberExpr *E) {
2473 // Handle non-static data members.
2474 QualType BaseTy;
2475 if (E->isArrow()) {
2476 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2477 return false;
2478 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002479 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002480 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002481 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2482 return false;
2483 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002484 } else {
2485 if (!this->Visit(E->getBase()))
2486 return false;
2487 BaseTy = E->getBase()->getType();
2488 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002489
Richard Smithd9b02e72012-01-25 22:15:11 +00002490 const ValueDecl *MD = E->getMemberDecl();
2491 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2492 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2493 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2494 (void)BaseTy;
2495 HandleLValueMember(this->Info, E, Result, FD);
2496 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2497 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2498 } else
2499 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002500
Richard Smithd9b02e72012-01-25 22:15:11 +00002501 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002502 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002503 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002504 RefValue))
2505 return false;
2506 return Success(RefValue, E);
2507 }
2508 return true;
2509 }
2510
2511 bool VisitBinaryOperator(const BinaryOperator *E) {
2512 switch (E->getOpcode()) {
2513 default:
2514 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2515
2516 case BO_PtrMemD:
2517 case BO_PtrMemI:
2518 return HandleMemberPointerAccess(this->Info, E, Result);
2519 }
2520 }
2521
2522 bool VisitCastExpr(const CastExpr *E) {
2523 switch (E->getCastKind()) {
2524 default:
2525 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2526
2527 case CK_DerivedToBase:
2528 case CK_UncheckedDerivedToBase: {
2529 if (!this->Visit(E->getSubExpr()))
2530 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002531
2532 // Now figure out the necessary offset to add to the base LV to get from
2533 // the derived class to the base class.
2534 QualType Type = E->getSubExpr()->getType();
2535
2536 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2537 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002538 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002539 *PathI))
2540 return false;
2541 Type = (*PathI)->getType();
2542 }
2543
2544 return true;
2545 }
2546 }
2547 }
2548};
2549}
2550
2551//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002552// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002553//
2554// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2555// function designators (in C), decl references to void objects (in C), and
2556// temporaries (if building with -Wno-address-of-temporary).
2557//
2558// LValue evaluation produces values comprising a base expression of one of the
2559// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002560// - Declarations
2561// * VarDecl
2562// * FunctionDecl
2563// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002564// * CompoundLiteralExpr in C
2565// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002566// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002567// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002568// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002569// * ObjCEncodeExpr
2570// * AddrLabelExpr
2571// * BlockExpr
2572// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002573// - Locals and temporaries
2574// * Any Expr, with a Frame indicating the function in which the temporary was
2575// evaluated.
2576// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002577//===----------------------------------------------------------------------===//
2578namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002579class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002580 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002581public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002582 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2583 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002584
Richard Smithc49bd112011-10-28 17:51:58 +00002585 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2586
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002587 bool VisitDeclRefExpr(const DeclRefExpr *E);
2588 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002589 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002590 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2591 bool VisitMemberExpr(const MemberExpr *E);
2592 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2593 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002594 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002595 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2596 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002597
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002598 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002599 switch (E->getCastKind()) {
2600 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002601 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002602
Eli Friedmandb924222011-10-11 00:13:24 +00002603 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002604 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002605 if (!Visit(E->getSubExpr()))
2606 return false;
2607 Result.Designator.setInvalid();
2608 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002609
Richard Smithe24f5fc2011-11-17 22:56:20 +00002610 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002611 if (!Visit(E->getSubExpr()))
2612 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002613 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002614 }
2615 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002616
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002617 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002618
Eli Friedman4efaa272008-11-12 09:44:48 +00002619};
2620} // end anonymous namespace
2621
Richard Smithc49bd112011-10-28 17:51:58 +00002622/// Evaluate an expression as an lvalue. This can be legitimately called on
2623/// expressions which are not glvalues, in a few cases:
2624/// * function designators in C,
2625/// * "extern void" objects,
2626/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002627static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002628 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2629 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2630 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002631 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002632}
2633
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002634bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002635 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2636 return Success(FD);
2637 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002638 return VisitVarDecl(E, VD);
2639 return Error(E);
2640}
Richard Smith436c8892011-10-24 23:14:33 +00002641
Richard Smithc49bd112011-10-28 17:51:58 +00002642bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002643 if (!VD->getType()->isReferenceType()) {
2644 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002645 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002646 return true;
2647 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002648 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002649 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002650
Richard Smith47a1eed2011-10-29 20:57:55 +00002651 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002652 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2653 return false;
2654 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002655}
2656
Richard Smithbd552ef2011-10-31 05:52:43 +00002657bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2658 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002659 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002660 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002661 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2662
2663 Result.set(E, Info.CurrentCall);
2664 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2665 Result, E->GetTemporaryExpr());
2666 }
2667
2668 // Materialization of an lvalue temporary occurs when we need to force a copy
2669 // (for instance, if it's a bitfield).
2670 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2671 if (!Visit(E->GetTemporaryExpr()))
2672 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002673 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002674 Info.CurrentCall->Temporaries[E]))
2675 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002676 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002677 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002678}
2679
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002680bool
2681LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002682 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2683 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2684 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002685 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002686}
2687
Richard Smith47d21452011-12-27 12:18:28 +00002688bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2689 if (E->isTypeOperand())
2690 return Success(E);
2691 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2692 if (RD && RD->isPolymorphic()) {
2693 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2694 << E->getExprOperand()->getType()
2695 << E->getExprOperand()->getSourceRange();
2696 return false;
2697 }
2698 return Success(E);
2699}
2700
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002701bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002702 // Handle static data members.
2703 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2704 VisitIgnoredValue(E->getBase());
2705 return VisitVarDecl(E, VD);
2706 }
2707
Richard Smithd0dccea2011-10-28 22:34:42 +00002708 // Handle static member functions.
2709 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2710 if (MD->isStatic()) {
2711 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002712 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002713 }
2714 }
2715
Richard Smith180f4792011-11-10 06:34:14 +00002716 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002717 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002718}
2719
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002720bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002721 // FIXME: Deal with vectors as array subscript bases.
2722 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002723 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002724
Anders Carlsson3068d112008-11-16 19:01:22 +00002725 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002726 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002727
Anders Carlsson3068d112008-11-16 19:01:22 +00002728 APSInt Index;
2729 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002730 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002731 int64_t IndexValue
2732 = Index.isSigned() ? Index.getSExtValue()
2733 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002734
Richard Smithb4e85ed2012-01-06 16:39:00 +00002735 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002736}
Eli Friedman4efaa272008-11-12 09:44:48 +00002737
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002738bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002739 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002740}
2741
Eli Friedman4efaa272008-11-12 09:44:48 +00002742//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002743// Pointer Evaluation
2744//===----------------------------------------------------------------------===//
2745
Anders Carlssonc754aa62008-07-08 05:13:58 +00002746namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002747class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002748 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002749 LValue &Result;
2750
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002751 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002752 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002753 return true;
2754 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002755public:
Mike Stump1eb44332009-09-09 15:08:12 +00002756
John McCallefdb83e2010-05-07 21:00:08 +00002757 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002758 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002759
Richard Smith47a1eed2011-10-29 20:57:55 +00002760 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002761 Result.setFrom(V);
2762 return true;
2763 }
Richard Smith51201882011-12-30 21:15:51 +00002764 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002765 return Success((Expr*)0);
2766 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002767
John McCallefdb83e2010-05-07 21:00:08 +00002768 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002769 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002770 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002771 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002772 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002773 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002774 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002775 bool VisitCallExpr(const CallExpr *E);
2776 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002777 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002778 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002779 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002780 }
Richard Smith180f4792011-11-10 06:34:14 +00002781 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2782 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002783 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002784 Result = *Info.CurrentCall->This;
2785 return true;
2786 }
John McCall56ca35d2011-02-17 10:25:35 +00002787
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002788 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002789};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002790} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002791
John McCallefdb83e2010-05-07 21:00:08 +00002792static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002793 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002794 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002795}
2796
John McCallefdb83e2010-05-07 21:00:08 +00002797bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002798 if (E->getOpcode() != BO_Add &&
2799 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002800 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002801
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002802 const Expr *PExp = E->getLHS();
2803 const Expr *IExp = E->getRHS();
2804 if (IExp->getType()->isPointerType())
2805 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002806
Richard Smith745f5142012-01-27 01:14:48 +00002807 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
2808 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00002809 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002810
John McCallefdb83e2010-05-07 21:00:08 +00002811 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00002812 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00002813 return false;
2814 int64_t AdditionalOffset
2815 = Offset.isSigned() ? Offset.getSExtValue()
2816 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002817 if (E->getOpcode() == BO_Sub)
2818 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002819
Richard Smith180f4792011-11-10 06:34:14 +00002820 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00002821 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2822 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002823}
Eli Friedman4efaa272008-11-12 09:44:48 +00002824
John McCallefdb83e2010-05-07 21:00:08 +00002825bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2826 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002827}
Mike Stump1eb44332009-09-09 15:08:12 +00002828
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002829bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2830 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002831
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002832 switch (E->getCastKind()) {
2833 default:
2834 break;
2835
John McCall2de56d12010-08-25 11:45:40 +00002836 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002837 case CK_CPointerToObjCPointerCast:
2838 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002839 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00002840 if (!Visit(SubExpr))
2841 return false;
Richard Smithc216a012011-12-12 12:46:16 +00002842 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2843 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2844 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002845 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00002846 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002847 if (SubExpr->getType()->isVoidPointerType())
2848 CCEDiag(E, diag::note_constexpr_invalid_cast)
2849 << 3 << SubExpr->getType();
2850 else
2851 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2852 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002853 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002854
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002855 case CK_DerivedToBase:
2856 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002857 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002858 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002859 if (!Result.Base && Result.Offset.isZero())
2860 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002861
Richard Smith180f4792011-11-10 06:34:14 +00002862 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002863 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002864 QualType Type =
2865 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002866
Richard Smith180f4792011-11-10 06:34:14 +00002867 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002868 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002869 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2870 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002871 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002872 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002873 }
2874
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002875 return true;
2876 }
2877
Richard Smithe24f5fc2011-11-17 22:56:20 +00002878 case CK_BaseToDerived:
2879 if (!Visit(E->getSubExpr()))
2880 return false;
2881 if (!Result.Base && Result.Offset.isZero())
2882 return true;
2883 return HandleBaseToDerivedCast(Info, E, Result);
2884
Richard Smith47a1eed2011-10-29 20:57:55 +00002885 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00002886 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002887
John McCall2de56d12010-08-25 11:45:40 +00002888 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002889 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2890
Richard Smith47a1eed2011-10-29 20:57:55 +00002891 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002892 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002893 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002894
John McCallefdb83e2010-05-07 21:00:08 +00002895 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002896 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2897 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002898 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002899 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002900 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002901 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002902 return true;
2903 } else {
2904 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002905 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002906 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002907 }
2908 }
John McCall2de56d12010-08-25 11:45:40 +00002909 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002910 if (SubExpr->isGLValue()) {
2911 if (!EvaluateLValue(SubExpr, Result, Info))
2912 return false;
2913 } else {
2914 Result.set(SubExpr, Info.CurrentCall);
2915 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2916 Info, Result, SubExpr))
2917 return false;
2918 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002919 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002920 if (const ConstantArrayType *CAT
2921 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
2922 Result.addArray(Info, E, CAT);
2923 else
2924 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00002925 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002926
John McCall2de56d12010-08-25 11:45:40 +00002927 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002928 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002929 }
2930
Richard Smithc49bd112011-10-28 17:51:58 +00002931 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002932}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002933
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002934bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002935 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002936 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002937
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002938 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002939}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002940
2941//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002942// Member Pointer Evaluation
2943//===----------------------------------------------------------------------===//
2944
2945namespace {
2946class MemberPointerExprEvaluator
2947 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2948 MemberPtr &Result;
2949
2950 bool Success(const ValueDecl *D) {
2951 Result = MemberPtr(D);
2952 return true;
2953 }
2954public:
2955
2956 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2957 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2958
2959 bool Success(const CCValue &V, const Expr *E) {
2960 Result.setFrom(V);
2961 return true;
2962 }
Richard Smith51201882011-12-30 21:15:51 +00002963 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002964 return Success((const ValueDecl*)0);
2965 }
2966
2967 bool VisitCastExpr(const CastExpr *E);
2968 bool VisitUnaryAddrOf(const UnaryOperator *E);
2969};
2970} // end anonymous namespace
2971
2972static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2973 EvalInfo &Info) {
2974 assert(E->isRValue() && E->getType()->isMemberPointerType());
2975 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2976}
2977
2978bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2979 switch (E->getCastKind()) {
2980 default:
2981 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2982
2983 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00002984 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002985
2986 case CK_BaseToDerivedMemberPointer: {
2987 if (!Visit(E->getSubExpr()))
2988 return false;
2989 if (E->path_empty())
2990 return true;
2991 // Base-to-derived member pointer casts store the path in derived-to-base
2992 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2993 // the wrong end of the derived->base arc, so stagger the path by one class.
2994 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2995 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2996 PathI != PathE; ++PathI) {
2997 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2998 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2999 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003000 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003001 }
3002 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3003 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003004 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003005 return true;
3006 }
3007
3008 case CK_DerivedToBaseMemberPointer:
3009 if (!Visit(E->getSubExpr()))
3010 return false;
3011 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3012 PathE = E->path_end(); PathI != PathE; ++PathI) {
3013 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3014 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3015 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003016 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003017 }
3018 return true;
3019 }
3020}
3021
3022bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3023 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3024 // member can be formed.
3025 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3026}
3027
3028//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003029// Record Evaluation
3030//===----------------------------------------------------------------------===//
3031
3032namespace {
3033 class RecordExprEvaluator
3034 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3035 const LValue &This;
3036 APValue &Result;
3037 public:
3038
3039 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3040 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3041
3042 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003043 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00003044 }
Richard Smith51201882011-12-30 21:15:51 +00003045 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003046
Richard Smith59efe262011-11-11 04:05:33 +00003047 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003048 bool VisitInitListExpr(const InitListExpr *E);
3049 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3050 };
3051}
3052
Richard Smith51201882011-12-30 21:15:51 +00003053/// Perform zero-initialization on an object of non-union class type.
3054/// C++11 [dcl.init]p5:
3055/// To zero-initialize an object or reference of type T means:
3056/// [...]
3057/// -- if T is a (possibly cv-qualified) non-union class type,
3058/// each non-static data member and each base-class subobject is
3059/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003060static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3061 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003062 const LValue &This, APValue &Result) {
3063 assert(!RD->isUnion() && "Expected non-union class type");
3064 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3065 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3066 std::distance(RD->field_begin(), RD->field_end()));
3067
3068 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3069
3070 if (CD) {
3071 unsigned Index = 0;
3072 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003073 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003074 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3075 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003076 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3077 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003078 Result.getStructBase(Index)))
3079 return false;
3080 }
3081 }
3082
Richard Smithb4e85ed2012-01-06 16:39:00 +00003083 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3084 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003085 // -- if T is a reference type, no initialization is performed.
3086 if ((*I)->getType()->isReferenceType())
3087 continue;
3088
3089 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003090 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003091
3092 ImplicitValueInitExpr VIE((*I)->getType());
3093 if (!EvaluateConstantExpression(
3094 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3095 return false;
3096 }
3097
3098 return true;
3099}
3100
3101bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3102 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3103 if (RD->isUnion()) {
3104 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3105 // object's first non-static named data member is zero-initialized
3106 RecordDecl::field_iterator I = RD->field_begin();
3107 if (I == RD->field_end()) {
3108 Result = APValue((const FieldDecl*)0);
3109 return true;
3110 }
3111
3112 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003113 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003114 Result = APValue(*I);
3115 ImplicitValueInitExpr VIE((*I)->getType());
3116 return EvaluateConstantExpression(Result.getUnionValue(), Info,
3117 Subobject, &VIE);
3118 }
3119
Richard Smithb4e85ed2012-01-06 16:39:00 +00003120 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003121}
3122
Richard Smith59efe262011-11-11 04:05:33 +00003123bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3124 switch (E->getCastKind()) {
3125 default:
3126 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3127
3128 case CK_ConstructorConversion:
3129 return Visit(E->getSubExpr());
3130
3131 case CK_DerivedToBase:
3132 case CK_UncheckedDerivedToBase: {
3133 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003134 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003135 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003136 if (!DerivedObject.isStruct())
3137 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003138
3139 // Derived-to-base rvalue conversion: just slice off the derived part.
3140 APValue *Value = &DerivedObject;
3141 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3142 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3143 PathE = E->path_end(); PathI != PathE; ++PathI) {
3144 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3145 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3146 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3147 RD = Base;
3148 }
3149 Result = *Value;
3150 return true;
3151 }
3152 }
3153}
3154
Richard Smith180f4792011-11-10 06:34:14 +00003155bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3156 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3157 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3158
3159 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003160 const FieldDecl *Field = E->getInitializedFieldInUnion();
3161 Result = APValue(Field);
3162 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003163 return true;
Richard Smithec789162012-01-12 18:54:33 +00003164
3165 // If the initializer list for a union does not contain any elements, the
3166 // first element of the union is value-initialized.
3167 ImplicitValueInitExpr VIE(Field->getType());
3168 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3169
Richard Smith180f4792011-11-10 06:34:14 +00003170 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003171 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00003172 return EvaluateConstantExpression(Result.getUnionValue(), Info,
Richard Smithec789162012-01-12 18:54:33 +00003173 Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003174 }
3175
3176 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3177 "initializer list for class with base classes");
3178 Result = APValue(APValue::UninitStruct(), 0,
3179 std::distance(RD->field_begin(), RD->field_end()));
3180 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003181 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003182 for (RecordDecl::field_iterator Field = RD->field_begin(),
3183 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3184 // Anonymous bit-fields are not considered members of the class for
3185 // purposes of aggregate initialization.
3186 if (Field->isUnnamedBitfield())
3187 continue;
3188
3189 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003190
Richard Smith745f5142012-01-27 01:14:48 +00003191 bool HaveInit = ElementNo < E->getNumInits();
3192
3193 // FIXME: Diagnostics here should point to the end of the initializer
3194 // list, not the start.
3195 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3196 *Field, &Layout);
3197
3198 // Perform an implicit value-initialization for members beyond the end of
3199 // the initializer list.
3200 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3201
3202 if (!EvaluateConstantExpression(
3203 Result.getStructField((*Field)->getFieldIndex()),
3204 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3205 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003206 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003207 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003208 }
3209 }
3210
Richard Smith745f5142012-01-27 01:14:48 +00003211 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003212}
3213
3214bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3215 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003216 bool ZeroInit = E->requiresZeroInitialization();
3217 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003218 // If we've already performed zero-initialization, we're already done.
3219 if (!Result.isUninit())
3220 return true;
3221
Richard Smith51201882011-12-30 21:15:51 +00003222 if (ZeroInit)
3223 return ZeroInitialization(E);
3224
Richard Smith61802452011-12-22 02:22:31 +00003225 const CXXRecordDecl *RD = FD->getParent();
3226 if (RD->isUnion())
3227 Result = APValue((FieldDecl*)0);
3228 else
3229 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3230 std::distance(RD->field_begin(), RD->field_end()));
3231 return true;
3232 }
3233
Richard Smith180f4792011-11-10 06:34:14 +00003234 const FunctionDecl *Definition = 0;
3235 FD->getBody(Definition);
3236
Richard Smithc1c5f272011-12-13 06:39:58 +00003237 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3238 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003239
Richard Smith610a60c2012-01-10 04:32:03 +00003240 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003241 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003242 if (const MaterializeTemporaryExpr *ME
3243 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3244 return Visit(ME->GetTemporaryExpr());
3245
Richard Smith51201882011-12-30 21:15:51 +00003246 if (ZeroInit && !ZeroInitialization(E))
3247 return false;
3248
Richard Smith180f4792011-11-10 06:34:14 +00003249 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003250 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003251 cast<CXXConstructorDecl>(Definition), Info,
3252 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003253}
3254
3255static bool EvaluateRecord(const Expr *E, const LValue &This,
3256 APValue &Result, EvalInfo &Info) {
3257 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003258 "can't evaluate expression as a record rvalue");
3259 return RecordExprEvaluator(Info, This, Result).Visit(E);
3260}
3261
3262//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003263// Temporary Evaluation
3264//
3265// Temporaries are represented in the AST as rvalues, but generally behave like
3266// lvalues. The full-object of which the temporary is a subobject is implicitly
3267// materialized so that a reference can bind to it.
3268//===----------------------------------------------------------------------===//
3269namespace {
3270class TemporaryExprEvaluator
3271 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3272public:
3273 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3274 LValueExprEvaluatorBaseTy(Info, Result) {}
3275
3276 /// Visit an expression which constructs the value of this temporary.
3277 bool VisitConstructExpr(const Expr *E) {
3278 Result.set(E, Info.CurrentCall);
3279 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3280 Result, E);
3281 }
3282
3283 bool VisitCastExpr(const CastExpr *E) {
3284 switch (E->getCastKind()) {
3285 default:
3286 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3287
3288 case CK_ConstructorConversion:
3289 return VisitConstructExpr(E->getSubExpr());
3290 }
3291 }
3292 bool VisitInitListExpr(const InitListExpr *E) {
3293 return VisitConstructExpr(E);
3294 }
3295 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3296 return VisitConstructExpr(E);
3297 }
3298 bool VisitCallExpr(const CallExpr *E) {
3299 return VisitConstructExpr(E);
3300 }
3301};
3302} // end anonymous namespace
3303
3304/// Evaluate an expression of record type as a temporary.
3305static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003306 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003307 return TemporaryExprEvaluator(Info, Result).Visit(E);
3308}
3309
3310//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003311// Vector Evaluation
3312//===----------------------------------------------------------------------===//
3313
3314namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003315 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003316 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3317 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003318 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003319
Richard Smith07fc6572011-10-22 21:10:00 +00003320 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3321 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003322
Richard Smith07fc6572011-10-22 21:10:00 +00003323 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3324 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3325 // FIXME: remove this APValue copy.
3326 Result = APValue(V.data(), V.size());
3327 return true;
3328 }
Richard Smith69c2c502011-11-04 05:33:44 +00003329 bool Success(const CCValue &V, const Expr *E) {
3330 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003331 Result = V;
3332 return true;
3333 }
Richard Smith51201882011-12-30 21:15:51 +00003334 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003335
Richard Smith07fc6572011-10-22 21:10:00 +00003336 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003337 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003338 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003339 bool VisitInitListExpr(const InitListExpr *E);
3340 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003341 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003342 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003343 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003344 };
3345} // end anonymous namespace
3346
3347static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003348 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003349 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003350}
3351
Richard Smith07fc6572011-10-22 21:10:00 +00003352bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3353 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003354 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003355
Richard Smithd62ca372011-12-06 22:44:34 +00003356 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003357 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003358
Eli Friedman46a52322011-03-25 00:43:55 +00003359 switch (E->getCastKind()) {
3360 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003361 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003362 if (SETy->isIntegerType()) {
3363 APSInt IntResult;
3364 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003365 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003366 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003367 } else if (SETy->isRealFloatingType()) {
3368 APFloat F(0.0);
3369 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003370 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003371 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003372 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003373 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003374 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003375
3376 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003377 SmallVector<APValue, 4> Elts(NElts, Val);
3378 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003379 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003380 case CK_BitCast: {
3381 // Evaluate the operand into an APInt we can extract from.
3382 llvm::APInt SValInt;
3383 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3384 return false;
3385 // Extract the elements
3386 QualType EltTy = VTy->getElementType();
3387 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3388 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3389 SmallVector<APValue, 4> Elts;
3390 if (EltTy->isRealFloatingType()) {
3391 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3392 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3393 unsigned FloatEltSize = EltSize;
3394 if (&Sem == &APFloat::x87DoubleExtended)
3395 FloatEltSize = 80;
3396 for (unsigned i = 0; i < NElts; i++) {
3397 llvm::APInt Elt;
3398 if (BigEndian)
3399 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3400 else
3401 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3402 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3403 }
3404 } else if (EltTy->isIntegerType()) {
3405 for (unsigned i = 0; i < NElts; i++) {
3406 llvm::APInt Elt;
3407 if (BigEndian)
3408 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3409 else
3410 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3411 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3412 }
3413 } else {
3414 return Error(E);
3415 }
3416 return Success(Elts, E);
3417 }
Eli Friedman46a52322011-03-25 00:43:55 +00003418 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003419 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003420 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003421}
3422
Richard Smith07fc6572011-10-22 21:10:00 +00003423bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003424VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003425 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003426 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003427 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003428
Nate Begeman59b5da62009-01-18 03:20:47 +00003429 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003430 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003431
Eli Friedman3edd5a92012-01-03 23:24:20 +00003432 // The number of initializers can be less than the number of
3433 // vector elements. For OpenCL, this can be due to nested vector
3434 // initialization. For GCC compatibility, missing trailing elements
3435 // should be initialized with zeroes.
3436 unsigned CountInits = 0, CountElts = 0;
3437 while (CountElts < NumElements) {
3438 // Handle nested vector initialization.
3439 if (CountInits < NumInits
3440 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3441 APValue v;
3442 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3443 return Error(E);
3444 unsigned vlen = v.getVectorLength();
3445 for (unsigned j = 0; j < vlen; j++)
3446 Elements.push_back(v.getVectorElt(j));
3447 CountElts += vlen;
3448 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003449 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003450 if (CountInits < NumInits) {
3451 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3452 return Error(E);
3453 } else // trailing integer zero.
3454 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3455 Elements.push_back(APValue(sInt));
3456 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003457 } else {
3458 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003459 if (CountInits < NumInits) {
3460 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3461 return Error(E);
3462 } else // trailing float zero.
3463 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3464 Elements.push_back(APValue(f));
3465 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003466 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003467 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003468 }
Richard Smith07fc6572011-10-22 21:10:00 +00003469 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003470}
3471
Richard Smith07fc6572011-10-22 21:10:00 +00003472bool
Richard Smith51201882011-12-30 21:15:51 +00003473VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003474 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003475 QualType EltTy = VT->getElementType();
3476 APValue ZeroElement;
3477 if (EltTy->isIntegerType())
3478 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3479 else
3480 ZeroElement =
3481 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3482
Chris Lattner5f9e2722011-07-23 10:55:15 +00003483 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003484 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003485}
3486
Richard Smith07fc6572011-10-22 21:10:00 +00003487bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003488 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003489 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003490}
3491
Nate Begeman59b5da62009-01-18 03:20:47 +00003492//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003493// Array Evaluation
3494//===----------------------------------------------------------------------===//
3495
3496namespace {
3497 class ArrayExprEvaluator
3498 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003499 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003500 APValue &Result;
3501 public:
3502
Richard Smith180f4792011-11-10 06:34:14 +00003503 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3504 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003505
3506 bool Success(const APValue &V, const Expr *E) {
3507 assert(V.isArray() && "Expected array type");
3508 Result = V;
3509 return true;
3510 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003511
Richard Smith51201882011-12-30 21:15:51 +00003512 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003513 const ConstantArrayType *CAT =
3514 Info.Ctx.getAsConstantArrayType(E->getType());
3515 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003516 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003517
3518 Result = APValue(APValue::UninitArray(), 0,
3519 CAT->getSize().getZExtValue());
3520 if (!Result.hasArrayFiller()) return true;
3521
Richard Smith51201882011-12-30 21:15:51 +00003522 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003523 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003524 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003525 ImplicitValueInitExpr VIE(CAT->getElementType());
3526 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3527 Subobject, &VIE);
3528 }
3529
Richard Smithcc5d4f62011-11-07 09:22:26 +00003530 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003531 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003532 };
3533} // end anonymous namespace
3534
Richard Smith180f4792011-11-10 06:34:14 +00003535static bool EvaluateArray(const Expr *E, const LValue &This,
3536 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003537 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003538 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003539}
3540
3541bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3542 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3543 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003544 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003545
Richard Smith974c5f92011-12-22 01:07:19 +00003546 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3547 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003548 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003549 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3550 LValue LV;
3551 if (!EvaluateLValue(E->getInit(0), LV, Info))
3552 return false;
3553 uint64_t NumElements = CAT->getSize().getZExtValue();
3554 Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3555
3556 // Copy the string literal into the array. FIXME: Do this better.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003557 LV.addArray(Info, E, CAT);
Richard Smith974c5f92011-12-22 01:07:19 +00003558 for (uint64_t I = 0; I < NumElements; ++I) {
3559 CCValue Char;
3560 if (!HandleLValueToRValueConversion(Info, E->getInit(0),
Richard Smith745f5142012-01-27 01:14:48 +00003561 CAT->getElementType(), LV, Char) ||
3562 !CheckConstantExpression(Info, E->getInit(0), Char,
3563 Result.getArrayInitializedElt(I)) ||
3564 !HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
Richard Smithb4e85ed2012-01-06 16:39:00 +00003565 CAT->getElementType(), 1))
Richard Smith974c5f92011-12-22 01:07:19 +00003566 return false;
3567 }
3568 return true;
3569 }
3570
Richard Smith745f5142012-01-27 01:14:48 +00003571 bool Success = true;
3572
Richard Smithcc5d4f62011-11-07 09:22:26 +00003573 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3574 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003575 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003576 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003577 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003578 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003579 I != End; ++I, ++Index) {
3580 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
Richard Smith745f5142012-01-27 01:14:48 +00003581 Info, Subobject, cast<Expr>(*I)) ||
3582 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3583 CAT->getElementType(), 1)) {
3584 if (!Info.keepEvaluatingAfterFailure())
3585 return false;
3586 Success = false;
3587 }
Richard Smith180f4792011-11-10 06:34:14 +00003588 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003589
Richard Smith745f5142012-01-27 01:14:48 +00003590 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003591 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003592 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3593 // but sometimes does:
3594 // struct S { constexpr S() : p(&p) {} void *p; };
3595 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00003596 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith745f5142012-01-27 01:14:48 +00003597 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003598}
3599
Richard Smithe24f5fc2011-11-17 22:56:20 +00003600bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3601 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3602 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003603 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003604
Richard Smithec789162012-01-12 18:54:33 +00003605 bool HadZeroInit = !Result.isUninit();
3606 if (!HadZeroInit)
3607 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003608 if (!Result.hasArrayFiller())
3609 return true;
3610
3611 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003612
Richard Smith51201882011-12-30 21:15:51 +00003613 bool ZeroInit = E->requiresZeroInitialization();
3614 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003615 if (HadZeroInit)
3616 return true;
3617
Richard Smith51201882011-12-30 21:15:51 +00003618 if (ZeroInit) {
3619 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003620 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003621 ImplicitValueInitExpr VIE(CAT->getElementType());
3622 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3623 Subobject, &VIE);
3624 }
3625
Richard Smith61802452011-12-22 02:22:31 +00003626 const CXXRecordDecl *RD = FD->getParent();
3627 if (RD->isUnion())
3628 Result.getArrayFiller() = APValue((FieldDecl*)0);
3629 else
3630 Result.getArrayFiller() =
3631 APValue(APValue::UninitStruct(), RD->getNumBases(),
3632 std::distance(RD->field_begin(), RD->field_end()));
3633 return true;
3634 }
3635
Richard Smithe24f5fc2011-11-17 22:56:20 +00003636 const FunctionDecl *Definition = 0;
3637 FD->getBody(Definition);
3638
Richard Smithc1c5f272011-12-13 06:39:58 +00003639 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3640 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003641
3642 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3643 // but sometimes does:
3644 // struct S { constexpr S() : p(&p) {} void *p; };
3645 // S s[10];
3646 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003647 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003648
Richard Smithec789162012-01-12 18:54:33 +00003649 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003650 ImplicitValueInitExpr VIE(CAT->getElementType());
3651 if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3652 &VIE))
3653 return false;
3654 }
3655
Richard Smithe24f5fc2011-11-17 22:56:20 +00003656 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003657 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003658 cast<CXXConstructorDecl>(Definition),
3659 Info, Result.getArrayFiller());
3660}
3661
Richard Smithcc5d4f62011-11-07 09:22:26 +00003662//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003663// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003664//
3665// As a GNU extension, we support casting pointers to sufficiently-wide integer
3666// types and back in constant folding. Integer values are thus represented
3667// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003668//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003669
3670namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003671class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003672 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00003673 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003674public:
Richard Smith47a1eed2011-10-29 20:57:55 +00003675 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003676 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003677
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003678 bool Success(const llvm::APSInt &SI, const Expr *E) {
3679 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003680 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003681 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003682 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003683 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003684 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003685 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003686 return true;
3687 }
3688
Daniel Dunbar131eb432009-02-19 09:06:44 +00003689 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003690 assert(E->getType()->isIntegralOrEnumerationType() &&
3691 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003692 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003693 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003694 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003695 Result.getInt().setIsUnsigned(
3696 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003697 return true;
3698 }
3699
3700 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003701 assert(E->getType()->isIntegralOrEnumerationType() &&
3702 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003703 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003704 return true;
3705 }
3706
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003707 bool Success(CharUnits Size, const Expr *E) {
3708 return Success(Size.getQuantity(), E);
3709 }
3710
Richard Smith47a1eed2011-10-29 20:57:55 +00003711 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003712 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003713 Result = V;
3714 return true;
3715 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003716 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003717 }
Mike Stump1eb44332009-09-09 15:08:12 +00003718
Richard Smith51201882011-12-30 21:15:51 +00003719 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003720
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003721 //===--------------------------------------------------------------------===//
3722 // Visitor Methods
3723 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003724
Chris Lattner4c4867e2008-07-12 00:38:25 +00003725 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003726 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003727 }
3728 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003729 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003730 }
Eli Friedman04309752009-11-24 05:28:59 +00003731
3732 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3733 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003734 if (CheckReferencedDecl(E, E->getDecl()))
3735 return true;
3736
3737 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003738 }
3739 bool VisitMemberExpr(const MemberExpr *E) {
3740 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003741 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003742 return true;
3743 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003744
3745 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003746 }
3747
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003748 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003749 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003750 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003751 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003752
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003753 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003754 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003755
Anders Carlsson3068d112008-11-16 19:01:22 +00003756 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003757 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003758 }
Mike Stump1eb44332009-09-09 15:08:12 +00003759
Richard Smithf10d9172011-10-11 21:43:33 +00003760 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003761 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00003762 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003763 }
3764
Sebastian Redl64b45f72009-01-05 20:52:13 +00003765 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003766 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003767 }
3768
Francois Pichet6ad6f282010-12-07 00:08:36 +00003769 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3770 return Success(E->getValue(), E);
3771 }
3772
John Wiegley21ff2e52011-04-28 00:16:57 +00003773 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3774 return Success(E->getValue(), E);
3775 }
3776
John Wiegley55262202011-04-25 06:54:41 +00003777 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3778 return Success(E->getValue(), E);
3779 }
3780
Eli Friedman722c7172009-02-28 03:59:05 +00003781 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003782 bool VisitUnaryImag(const UnaryOperator *E);
3783
Sebastian Redl295995c2010-09-10 20:55:47 +00003784 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003785 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003786
Chris Lattnerfcee0012008-07-11 21:24:13 +00003787private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003788 CharUnits GetAlignOfExpr(const Expr *E);
3789 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003790 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003791 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003792 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003793};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003794} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003795
Richard Smithc49bd112011-10-28 17:51:58 +00003796/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3797/// produce either the integer value or a pointer.
3798///
3799/// GCC has a heinous extension which folds casts between pointer types and
3800/// pointer-sized integral types. We support this by allowing the evaluation of
3801/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3802/// Some simple arithmetic on such values is supported (they are treated much
3803/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003804static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003805 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003806 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003807 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003808}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003809
Richard Smithf48fdb02011-12-09 22:58:01 +00003810static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003811 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003812 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003813 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003814 if (!Val.isInt()) {
3815 // FIXME: It would be better to produce the diagnostic for casting
3816 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003817 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003818 return false;
3819 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003820 Result = Val.getInt();
3821 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003822}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003823
Richard Smithf48fdb02011-12-09 22:58:01 +00003824/// Check whether the given declaration can be directly converted to an integral
3825/// rvalue. If not, no diagnostic is produced; there are other things we can
3826/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003827bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003828 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003829 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003830 // Check for signedness/width mismatches between E type and ECD value.
3831 bool SameSign = (ECD->getInitVal().isSigned()
3832 == E->getType()->isSignedIntegerOrEnumerationType());
3833 bool SameWidth = (ECD->getInitVal().getBitWidth()
3834 == Info.Ctx.getIntWidth(E->getType()));
3835 if (SameSign && SameWidth)
3836 return Success(ECD->getInitVal(), E);
3837 else {
3838 // Get rid of mismatch (otherwise Success assertions will fail)
3839 // by computing a new value matching the type of E.
3840 llvm::APSInt Val = ECD->getInitVal();
3841 if (!SameSign)
3842 Val.setIsSigned(!ECD->getInitVal().isSigned());
3843 if (!SameWidth)
3844 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3845 return Success(Val, E);
3846 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003847 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003848 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003849}
3850
Chris Lattnera4d55d82008-10-06 06:40:35 +00003851/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3852/// as GCC.
3853static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3854 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003855 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003856 enum gcc_type_class {
3857 no_type_class = -1,
3858 void_type_class, integer_type_class, char_type_class,
3859 enumeral_type_class, boolean_type_class,
3860 pointer_type_class, reference_type_class, offset_type_class,
3861 real_type_class, complex_type_class,
3862 function_type_class, method_type_class,
3863 record_type_class, union_type_class,
3864 array_type_class, string_type_class,
3865 lang_type_class
3866 };
Mike Stump1eb44332009-09-09 15:08:12 +00003867
3868 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003869 // ideal, however it is what gcc does.
3870 if (E->getNumArgs() == 0)
3871 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003872
Chris Lattnera4d55d82008-10-06 06:40:35 +00003873 QualType ArgTy = E->getArg(0)->getType();
3874 if (ArgTy->isVoidType())
3875 return void_type_class;
3876 else if (ArgTy->isEnumeralType())
3877 return enumeral_type_class;
3878 else if (ArgTy->isBooleanType())
3879 return boolean_type_class;
3880 else if (ArgTy->isCharType())
3881 return string_type_class; // gcc doesn't appear to use char_type_class
3882 else if (ArgTy->isIntegerType())
3883 return integer_type_class;
3884 else if (ArgTy->isPointerType())
3885 return pointer_type_class;
3886 else if (ArgTy->isReferenceType())
3887 return reference_type_class;
3888 else if (ArgTy->isRealType())
3889 return real_type_class;
3890 else if (ArgTy->isComplexType())
3891 return complex_type_class;
3892 else if (ArgTy->isFunctionType())
3893 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003894 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003895 return record_type_class;
3896 else if (ArgTy->isUnionType())
3897 return union_type_class;
3898 else if (ArgTy->isArrayType())
3899 return array_type_class;
3900 else if (ArgTy->isUnionType())
3901 return union_type_class;
3902 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003903 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003904}
3905
Richard Smith80d4b552011-12-28 19:48:30 +00003906/// EvaluateBuiltinConstantPForLValue - Determine the result of
3907/// __builtin_constant_p when applied to the given lvalue.
3908///
3909/// An lvalue is only "constant" if it is a pointer or reference to the first
3910/// character of a string literal.
3911template<typename LValue>
3912static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3913 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3914 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3915}
3916
3917/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3918/// GCC as we can manage.
3919static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3920 QualType ArgType = Arg->getType();
3921
3922 // __builtin_constant_p always has one operand. The rules which gcc follows
3923 // are not precisely documented, but are as follows:
3924 //
3925 // - If the operand is of integral, floating, complex or enumeration type,
3926 // and can be folded to a known value of that type, it returns 1.
3927 // - If the operand and can be folded to a pointer to the first character
3928 // of a string literal (or such a pointer cast to an integral type), it
3929 // returns 1.
3930 //
3931 // Otherwise, it returns 0.
3932 //
3933 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3934 // its support for this does not currently work.
3935 if (ArgType->isIntegralOrEnumerationType()) {
3936 Expr::EvalResult Result;
3937 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3938 return false;
3939
3940 APValue &V = Result.Val;
3941 if (V.getKind() == APValue::Int)
3942 return true;
3943
3944 return EvaluateBuiltinConstantPForLValue(V);
3945 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3946 return Arg->isEvaluatable(Ctx);
3947 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3948 LValue LV;
3949 Expr::EvalStatus Status;
3950 EvalInfo Info(Ctx, Status);
3951 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3952 : EvaluatePointer(Arg, LV, Info)) &&
3953 !Status.HasSideEffects)
3954 return EvaluateBuiltinConstantPForLValue(LV);
3955 }
3956
3957 // Anything else isn't considered to be sufficiently constant.
3958 return false;
3959}
3960
John McCall42c8f872010-05-10 23:27:23 +00003961/// Retrieves the "underlying object type" of the given expression,
3962/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003963QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3964 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3965 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003966 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003967 } else if (const Expr *E = B.get<const Expr*>()) {
3968 if (isa<CompoundLiteralExpr>(E))
3969 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003970 }
3971
3972 return QualType();
3973}
3974
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003975bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003976 // TODO: Perhaps we should let LLVM lower this?
3977 LValue Base;
3978 if (!EvaluatePointer(E->getArg(0), Base, Info))
3979 return false;
3980
3981 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003982 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003983
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003984 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003985 if (T.isNull() ||
3986 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00003987 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00003988 T->isVariablyModifiedType() ||
3989 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003990 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00003991
3992 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3993 CharUnits Offset = Base.getLValueOffset();
3994
3995 if (!Offset.isNegative() && Offset <= Size)
3996 Size -= Offset;
3997 else
3998 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003999 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004000}
4001
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004002bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004003 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004004 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004005 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004006
4007 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004008 if (TryEvaluateBuiltinObjectSize(E))
4009 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004010
Eric Christopherb2aaf512010-01-19 22:58:35 +00004011 // If evaluating the argument has side-effects we can't determine
4012 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004013 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004014 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004015 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004016 return Success(0, E);
4017 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004018
Richard Smithf48fdb02011-12-09 22:58:01 +00004019 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004020 }
4021
Chris Lattner019f4e82008-10-06 05:28:25 +00004022 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004023 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004024
Richard Smith80d4b552011-12-28 19:48:30 +00004025 case Builtin::BI__builtin_constant_p:
4026 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004027
Chris Lattner21fb98e2009-09-23 06:06:36 +00004028 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004029 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004030 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004031 return Success(Operand, E);
4032 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004033
4034 case Builtin::BI__builtin_expect:
4035 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004036
Douglas Gregor5726d402010-09-10 06:27:15 +00004037 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004038 // A call to strlen is not a constant expression.
4039 if (Info.getLangOpts().CPlusPlus0x)
4040 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4041 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4042 else
4043 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4044 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004045 case Builtin::BI__builtin_strlen:
4046 // As an extension, we support strlen() and __builtin_strlen() as constant
4047 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004048 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004049 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4050 // The string literal may have embedded null characters. Find the first
4051 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004052 StringRef Str = S->getString();
4053 StringRef::size_type Pos = Str.find(0);
4054 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004055 Str = Str.substr(0, Pos);
4056
4057 return Success(Str.size(), E);
4058 }
4059
Richard Smithf48fdb02011-12-09 22:58:01 +00004060 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004061
4062 case Builtin::BI__atomic_is_lock_free: {
4063 APSInt SizeVal;
4064 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4065 return false;
4066
4067 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4068 // of two less than the maximum inline atomic width, we know it is
4069 // lock-free. If the size isn't a power of two, or greater than the
4070 // maximum alignment where we promote atomics, we know it is not lock-free
4071 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4072 // the answer can only be determined at runtime; for example, 16-byte
4073 // atomics have lock-free implementations on some, but not all,
4074 // x86-64 processors.
4075
4076 // Check power-of-two.
4077 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4078 if (!Size.isPowerOfTwo())
4079#if 0
4080 // FIXME: Suppress this folding until the ABI for the promotion width
4081 // settles.
4082 return Success(0, E);
4083#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004084 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004085#endif
4086
4087#if 0
4088 // Check against promotion width.
4089 // FIXME: Suppress this folding until the ABI for the promotion width
4090 // settles.
4091 unsigned PromoteWidthBits =
4092 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4093 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4094 return Success(0, E);
4095#endif
4096
4097 // Check against inlining width.
4098 unsigned InlineWidthBits =
4099 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4100 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4101 return Success(1, E);
4102
Richard Smithf48fdb02011-12-09 22:58:01 +00004103 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004104 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004105 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004106}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004107
Richard Smith625b8072011-10-31 01:37:14 +00004108static bool HasSameBase(const LValue &A, const LValue &B) {
4109 if (!A.getLValueBase())
4110 return !B.getLValueBase();
4111 if (!B.getLValueBase())
4112 return false;
4113
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004114 if (A.getLValueBase().getOpaqueValue() !=
4115 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004116 const Decl *ADecl = GetLValueBaseDecl(A);
4117 if (!ADecl)
4118 return false;
4119 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004120 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004121 return false;
4122 }
4123
4124 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00004125 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00004126}
4127
Chris Lattnerb542afe2008-07-11 19:10:17 +00004128bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004129 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004130 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004131
John McCall2de56d12010-08-25 11:45:40 +00004132 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004133 VisitIgnoredValue(E->getLHS());
4134 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004135 }
4136
4137 if (E->isLogicalOp()) {
4138 // These need to be handled specially because the operands aren't
4139 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004140 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004141
Richard Smithc49bd112011-10-28 17:51:58 +00004142 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004143 // We were able to evaluate the LHS, see if we can get away with not
4144 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004145 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004146 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004147
Richard Smithc49bd112011-10-28 17:51:58 +00004148 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004149 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004150 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004151 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004152 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004153 }
4154 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004155 // FIXME: If both evaluations fail, we should produce the diagnostic from
4156 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4157 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00004158 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004159 // We can't evaluate the LHS; however, sometimes the result
4160 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00004161 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004162 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004163 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00004164 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004165
4166 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004167 }
4168 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004169 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004170
Eli Friedmana6afa762008-11-13 06:09:17 +00004171 return false;
4172 }
4173
Anders Carlsson286f85e2008-11-16 07:17:21 +00004174 QualType LHSTy = E->getLHS()->getType();
4175 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004176
4177 if (LHSTy->isAnyComplexType()) {
4178 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004179 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004180
Richard Smith745f5142012-01-27 01:14:48 +00004181 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4182 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004183 return false;
4184
Richard Smith745f5142012-01-27 01:14:48 +00004185 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004186 return false;
4187
4188 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004189 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004190 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004191 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004192 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4193
John McCall2de56d12010-08-25 11:45:40 +00004194 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004195 return Success((CR_r == APFloat::cmpEqual &&
4196 CR_i == APFloat::cmpEqual), E);
4197 else {
John McCall2de56d12010-08-25 11:45:40 +00004198 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004199 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004200 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004201 CR_r == APFloat::cmpLessThan ||
4202 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004203 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004204 CR_i == APFloat::cmpLessThan ||
4205 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004206 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004207 } else {
John McCall2de56d12010-08-25 11:45:40 +00004208 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004209 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4210 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4211 else {
John McCall2de56d12010-08-25 11:45:40 +00004212 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004213 "Invalid compex comparison.");
4214 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4215 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4216 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004217 }
4218 }
Mike Stump1eb44332009-09-09 15:08:12 +00004219
Anders Carlsson286f85e2008-11-16 07:17:21 +00004220 if (LHSTy->isRealFloatingType() &&
4221 RHSTy->isRealFloatingType()) {
4222 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004223
Richard Smith745f5142012-01-27 01:14:48 +00004224 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4225 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004226 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004227
Richard Smith745f5142012-01-27 01:14:48 +00004228 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004229 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004230
Anders Carlsson286f85e2008-11-16 07:17:21 +00004231 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004232
Anders Carlsson286f85e2008-11-16 07:17:21 +00004233 switch (E->getOpcode()) {
4234 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004235 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004236 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004237 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004238 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004239 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004240 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004241 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004242 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004243 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004244 E);
John McCall2de56d12010-08-25 11:45:40 +00004245 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004246 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004247 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004248 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004249 || CR == APFloat::cmpLessThan
4250 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004251 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004252 }
Mike Stump1eb44332009-09-09 15:08:12 +00004253
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004254 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004255 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004256 LValue LHSValue, RHSValue;
4257
4258 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4259 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004260 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004261
Richard Smith745f5142012-01-27 01:14:48 +00004262 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004263 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004264
Richard Smith625b8072011-10-31 01:37:14 +00004265 // Reject differing bases from the normal codepath; we special-case
4266 // comparisons to null.
4267 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004268 if (E->getOpcode() == BO_Sub) {
4269 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004270 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4271 return false;
4272 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4273 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4274 if (!LHSExpr || !RHSExpr)
4275 return false;
4276 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4277 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4278 if (!LHSAddrExpr || !RHSAddrExpr)
4279 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004280 // Make sure both labels come from the same function.
4281 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4282 RHSAddrExpr->getLabel()->getDeclContext())
4283 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004284 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4285 return true;
4286 }
Richard Smith9e36b532011-10-31 05:11:32 +00004287 // Inequalities and subtractions between unrelated pointers have
4288 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004289 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004290 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004291 // A constant address may compare equal to the address of a symbol.
4292 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004293 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004294 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4295 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004296 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004297 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00004298 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00004299 // distinct. However, we do know that the address of a literal will be
4300 // non-null.
4301 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4302 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004303 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004304 // We can't tell whether weak symbols will end up pointing to the same
4305 // object.
4306 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004307 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004308 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004309 // (Note that clang defaults to -fmerge-all-constants, which can
4310 // lead to inconsistent results for comparisons involving the address
4311 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004312 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004313 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004314
Richard Smithcc5d4f62011-11-07 09:22:26 +00004315 // FIXME: Implement the C++11 restrictions:
4316 // - Pointer subtractions must be on elements of the same array.
4317 // - Pointer comparisons must be between members with the same access.
4318
John McCall2de56d12010-08-25 11:45:40 +00004319 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00004320 QualType Type = E->getLHS()->getType();
4321 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004322
Richard Smith180f4792011-11-10 06:34:14 +00004323 CharUnits ElementSize;
4324 if (!HandleSizeof(Info, ElementType, ElementSize))
4325 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004326
Richard Smith180f4792011-11-10 06:34:14 +00004327 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00004328 RHSValue.getLValueOffset();
4329 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004330 }
Richard Smith625b8072011-10-31 01:37:14 +00004331
4332 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4333 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
Richard Smith82f28582012-01-31 06:41:30 +00004334
4335 // C++11 [expr.rel]p3:
4336 // Pointers to void (after pointer conversions) can be compared, with a
4337 // result defined as follows: If both pointers represent the same
4338 // address or are both the null pointer value, the result is true if the
4339 // operator is <= or >= and false otherwise; otherwise the result is
4340 // unspecified.
4341 // We interpret this as applying to pointers to *cv* void.
4342 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
4343 E->getOpcode() != BO_EQ && E->getOpcode() != BO_NE)
4344 CCEDiag(E, diag::note_constexpr_void_comparison);
4345
Richard Smith625b8072011-10-31 01:37:14 +00004346 switch (E->getOpcode()) {
4347 default: llvm_unreachable("missing comparison operator");
4348 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4349 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4350 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4351 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4352 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4353 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004354 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004355 }
4356 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004357 if (!LHSTy->isIntegralOrEnumerationType() ||
4358 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004359 // We can't continue from here for non-integral types.
4360 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004361 }
4362
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004363 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004364 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004365
4366 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4367 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004368 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004369
Richard Smith745f5142012-01-27 01:14:48 +00004370 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004371 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004372
Richard Smith47a1eed2011-10-29 20:57:55 +00004373 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004374
4375 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004376 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004377 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4378 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004379 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004380 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004381 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004382 LHSVal.getLValueOffset() -= AdditionalOffset;
4383 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004384 return true;
4385 }
4386
4387 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004388 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004389 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004390 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4391 LHSVal.getInt().getZExtValue());
4392 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004393 return true;
4394 }
4395
Eli Friedman65639282012-01-04 23:13:47 +00004396 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4397 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004398 if (!LHSVal.getLValueOffset().isZero() ||
4399 !RHSVal.getLValueOffset().isZero())
4400 return false;
4401 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4402 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4403 if (!LHSExpr || !RHSExpr)
4404 return false;
4405 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4406 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4407 if (!LHSAddrExpr || !RHSAddrExpr)
4408 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004409 // Make sure both labels come from the same function.
4410 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4411 RHSAddrExpr->getLabel()->getDeclContext())
4412 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004413 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4414 return true;
4415 }
4416
Eli Friedman42edd0d2009-03-24 01:14:50 +00004417 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004418 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004419 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004420
Richard Smithc49bd112011-10-28 17:51:58 +00004421 APSInt &LHS = LHSVal.getInt();
4422 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004423
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004424 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004425 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004426 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004427 case BO_Mul: return Success(LHS * RHS, E);
4428 case BO_Add: return Success(LHS + RHS, E);
4429 case BO_Sub: return Success(LHS - RHS, E);
4430 case BO_And: return Success(LHS & RHS, E);
4431 case BO_Xor: return Success(LHS ^ RHS, E);
4432 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004433 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004434 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004435 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004436 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004437 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4438 // actually undefined behavior in C++11 due to a language defect.
4439 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4440 LHS.isSigned() && LHS.isMinSignedValue())
4441 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4442 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004443 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004444 // During constant-folding, a negative shift is an opposite shift. Such a
4445 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004446 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004447 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004448 RHS = -RHS;
4449 goto shift_right;
4450 }
4451
4452 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004453 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4454 // shifted type.
4455 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4456 if (SA != RHS) {
4457 CCEDiag(E, diag::note_constexpr_large_shift)
4458 << RHS << E->getType() << LHS.getBitWidth();
4459 } else if (LHS.isSigned()) {
4460 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4461 // operand, and must not overflow.
4462 if (LHS.isNegative())
4463 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4464 else if (LHS.countLeadingZeros() <= SA)
4465 HandleOverflow(Info, E, LHS.extend(LHS.getBitWidth() + SA) << SA,
4466 E->getType());
4467 }
4468
Richard Smithc49bd112011-10-28 17:51:58 +00004469 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004470 }
John McCall2de56d12010-08-25 11:45:40 +00004471 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004472 // During constant-folding, a negative shift is an opposite shift. Such a
4473 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004474 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004475 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004476 RHS = -RHS;
4477 goto shift_left;
4478 }
4479
4480 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004481 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4482 // shifted type.
4483 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4484 if (SA != RHS)
4485 CCEDiag(E, diag::note_constexpr_large_shift)
4486 << RHS << E->getType() << LHS.getBitWidth();
4487
Richard Smithc49bd112011-10-28 17:51:58 +00004488 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004489 }
Mike Stump1eb44332009-09-09 15:08:12 +00004490
Richard Smithc49bd112011-10-28 17:51:58 +00004491 case BO_LT: return Success(LHS < RHS, E);
4492 case BO_GT: return Success(LHS > RHS, E);
4493 case BO_LE: return Success(LHS <= RHS, E);
4494 case BO_GE: return Success(LHS >= RHS, E);
4495 case BO_EQ: return Success(LHS == RHS, E);
4496 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004497 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004498}
4499
Ken Dyck8b752f12010-01-27 17:10:57 +00004500CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004501 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4502 // the result is the size of the referenced type."
4503 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4504 // result shall be the alignment of the referenced type."
4505 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4506 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004507
4508 // __alignof is defined to return the preferred alignment.
4509 return Info.Ctx.toCharUnitsFromBits(
4510 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004511}
4512
Ken Dyck8b752f12010-01-27 17:10:57 +00004513CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004514 E = E->IgnoreParens();
4515
4516 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004517 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004518 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004519 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4520 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004521
Chris Lattneraf707ab2009-01-24 21:53:27 +00004522 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004523 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4524 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004525
Chris Lattnere9feb472009-01-24 21:09:06 +00004526 return GetAlignOfType(E->getType());
4527}
4528
4529
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004530/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4531/// a result as the expression's type.
4532bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4533 const UnaryExprOrTypeTraitExpr *E) {
4534 switch(E->getKind()) {
4535 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004536 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004537 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004538 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004539 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004540 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004541
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004542 case UETT_VecStep: {
4543 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004544
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004545 if (Ty->isVectorType()) {
4546 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004547
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004548 // The vec_step built-in functions that take a 3-component
4549 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4550 if (n == 3)
4551 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004552
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004553 return Success(n, E);
4554 } else
4555 return Success(1, E);
4556 }
4557
4558 case UETT_SizeOf: {
4559 QualType SrcTy = E->getTypeOfArgument();
4560 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4561 // the result is the size of the referenced type."
4562 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4563 // result shall be the alignment of the referenced type."
4564 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4565 SrcTy = Ref->getPointeeType();
4566
Richard Smith180f4792011-11-10 06:34:14 +00004567 CharUnits Sizeof;
4568 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004569 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004570 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004571 }
4572 }
4573
4574 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00004575}
4576
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004577bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004578 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004579 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004580 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004581 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004582 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004583 for (unsigned i = 0; i != n; ++i) {
4584 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4585 switch (ON.getKind()) {
4586 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004587 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004588 APSInt IdxResult;
4589 if (!EvaluateInteger(Idx, IdxResult, Info))
4590 return false;
4591 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4592 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004593 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004594 CurrentType = AT->getElementType();
4595 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4596 Result += IdxResult.getSExtValue() * ElementSize;
4597 break;
4598 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004599
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004600 case OffsetOfExpr::OffsetOfNode::Field: {
4601 FieldDecl *MemberDecl = ON.getField();
4602 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004603 if (!RT)
4604 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004605 RecordDecl *RD = RT->getDecl();
4606 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00004607 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004608 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00004609 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004610 CurrentType = MemberDecl->getType().getNonReferenceType();
4611 break;
4612 }
Richard Smithf48fdb02011-12-09 22:58:01 +00004613
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004614 case OffsetOfExpr::OffsetOfNode::Identifier:
4615 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00004616
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004617 case OffsetOfExpr::OffsetOfNode::Base: {
4618 CXXBaseSpecifier *BaseSpec = ON.getBase();
4619 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00004620 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004621
4622 // Find the layout of the class whose base we are looking into.
4623 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00004624 if (!RT)
4625 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004626 RecordDecl *RD = RT->getDecl();
4627 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4628
4629 // Find the base class itself.
4630 CurrentType = BaseSpec->getType();
4631 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4632 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00004633 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004634
4635 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00004636 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00004637 break;
4638 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004639 }
4640 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004641 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004642}
4643
Chris Lattnerb542afe2008-07-11 19:10:17 +00004644bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004645 switch (E->getOpcode()) {
4646 default:
4647 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4648 // See C99 6.6p3.
4649 return Error(E);
4650 case UO_Extension:
4651 // FIXME: Should extension allow i-c-e extension expressions in its scope?
4652 // If so, we could clear the diagnostic ID.
4653 return Visit(E->getSubExpr());
4654 case UO_Plus:
4655 // The result is just the value.
4656 return Visit(E->getSubExpr());
4657 case UO_Minus: {
4658 if (!Visit(E->getSubExpr()))
4659 return false;
4660 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00004661 const APSInt &Value = Result.getInt();
4662 if (Value.isSigned() && Value.isMinSignedValue())
4663 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
4664 E->getType());
4665 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00004666 }
4667 case UO_Not: {
4668 if (!Visit(E->getSubExpr()))
4669 return false;
4670 if (!Result.isInt()) return Error(E);
4671 return Success(~Result.getInt(), E);
4672 }
4673 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00004674 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00004675 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00004676 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004677 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004678 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004679 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004680}
Mike Stump1eb44332009-09-09 15:08:12 +00004681
Chris Lattner732b2232008-07-12 01:15:53 +00004682/// HandleCast - This is used to evaluate implicit or explicit casts where the
4683/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004684bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4685 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00004686 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00004687 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00004688
Eli Friedman46a52322011-03-25 00:43:55 +00004689 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00004690 case CK_BaseToDerived:
4691 case CK_DerivedToBase:
4692 case CK_UncheckedDerivedToBase:
4693 case CK_Dynamic:
4694 case CK_ToUnion:
4695 case CK_ArrayToPointerDecay:
4696 case CK_FunctionToPointerDecay:
4697 case CK_NullToPointer:
4698 case CK_NullToMemberPointer:
4699 case CK_BaseToDerivedMemberPointer:
4700 case CK_DerivedToBaseMemberPointer:
4701 case CK_ConstructorConversion:
4702 case CK_IntegralToPointer:
4703 case CK_ToVoid:
4704 case CK_VectorSplat:
4705 case CK_IntegralToFloating:
4706 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004707 case CK_CPointerToObjCPointerCast:
4708 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004709 case CK_AnyPointerToBlockPointerCast:
4710 case CK_ObjCObjectLValueCast:
4711 case CK_FloatingRealToComplex:
4712 case CK_FloatingComplexToReal:
4713 case CK_FloatingComplexCast:
4714 case CK_FloatingComplexToIntegralComplex:
4715 case CK_IntegralRealToComplex:
4716 case CK_IntegralComplexCast:
4717 case CK_IntegralComplexToFloatingComplex:
4718 llvm_unreachable("invalid cast kind for integral value");
4719
Eli Friedmane50c2972011-03-25 19:07:11 +00004720 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00004721 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004722 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00004723 case CK_ARCProduceObject:
4724 case CK_ARCConsumeObject:
4725 case CK_ARCReclaimReturnedObject:
4726 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00004727 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004728
Richard Smith7d580a42012-01-17 21:17:26 +00004729 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00004730 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00004731 case CK_AtomicToNonAtomic:
4732 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00004733 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004734 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00004735
4736 case CK_MemberPointerToBoolean:
4737 case CK_PointerToBoolean:
4738 case CK_IntegralToBoolean:
4739 case CK_FloatingToBoolean:
4740 case CK_FloatingComplexToBoolean:
4741 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004742 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00004743 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00004744 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00004745 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004746 }
4747
Eli Friedman46a52322011-03-25 00:43:55 +00004748 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00004749 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004750 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004751
Eli Friedmanbe265702009-02-20 01:15:07 +00004752 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00004753 // Allow casts of address-of-label differences if they are no-ops
4754 // or narrowing. (The narrowing case isn't actually guaranteed to
4755 // be constant-evaluatable except in some narrow cases which are hard
4756 // to detect here. We let it through on the assumption the user knows
4757 // what they are doing.)
4758 if (Result.isAddrLabelDiff())
4759 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00004760 // Only allow casts of lvalues if they are lossless.
4761 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4762 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004763
Richard Smithf72fccf2012-01-30 22:27:01 +00004764 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
4765 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00004766 }
Mike Stump1eb44332009-09-09 15:08:12 +00004767
Eli Friedman46a52322011-03-25 00:43:55 +00004768 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00004769 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4770
John McCallefdb83e2010-05-07 21:00:08 +00004771 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00004772 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00004773 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00004774
Daniel Dunbardd211642009-02-19 22:24:01 +00004775 if (LV.getLValueBase()) {
4776 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00004777 // FIXME: Allow a larger integer size than the pointer size, and allow
4778 // narrowing back down to pointer width in subsequent integral casts.
4779 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00004780 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00004781 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004782
Richard Smithb755a9d2011-11-16 07:18:12 +00004783 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00004784 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00004785 return true;
4786 }
4787
Ken Dycka7305832010-01-15 12:37:54 +00004788 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4789 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00004790 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00004791 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004792
Eli Friedman46a52322011-03-25 00:43:55 +00004793 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00004794 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00004795 if (!EvaluateComplex(SubExpr, C, Info))
4796 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00004797 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00004798 }
Eli Friedman2217c872009-02-22 11:46:18 +00004799
Eli Friedman46a52322011-03-25 00:43:55 +00004800 case CK_FloatingToIntegral: {
4801 APFloat F(0.0);
4802 if (!EvaluateFloat(SubExpr, F, Info))
4803 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00004804
Richard Smithc1c5f272011-12-13 06:39:58 +00004805 APSInt Value;
4806 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4807 return false;
4808 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00004809 }
4810 }
Mike Stump1eb44332009-09-09 15:08:12 +00004811
Eli Friedman46a52322011-03-25 00:43:55 +00004812 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004813}
Anders Carlsson2bad1682008-07-08 14:30:00 +00004814
Eli Friedman722c7172009-02-28 03:59:05 +00004815bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4816 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004817 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004818 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4819 return false;
4820 if (!LV.isComplexInt())
4821 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004822 return Success(LV.getComplexIntReal(), E);
4823 }
4824
4825 return Visit(E->getSubExpr());
4826}
4827
Eli Friedman664a1042009-02-27 04:45:43 +00004828bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004829 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004830 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004831 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4832 return false;
4833 if (!LV.isComplexInt())
4834 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004835 return Success(LV.getComplexIntImag(), E);
4836 }
4837
Richard Smith8327fad2011-10-24 18:44:57 +00004838 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004839 return Success(0, E);
4840}
4841
Douglas Gregoree8aff02011-01-04 17:33:58 +00004842bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4843 return Success(E->getPackLength(), E);
4844}
4845
Sebastian Redl295995c2010-09-10 20:55:47 +00004846bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4847 return Success(E->getValue(), E);
4848}
4849
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004850//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004851// Float Evaluation
4852//===----------------------------------------------------------------------===//
4853
4854namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004855class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004856 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004857 APFloat &Result;
4858public:
4859 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004860 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004861
Richard Smith47a1eed2011-10-29 20:57:55 +00004862 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004863 Result = V.getFloat();
4864 return true;
4865 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004866
Richard Smith51201882011-12-30 21:15:51 +00004867 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00004868 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4869 return true;
4870 }
4871
Chris Lattner019f4e82008-10-06 05:28:25 +00004872 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004873
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004874 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004875 bool VisitBinaryOperator(const BinaryOperator *E);
4876 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004877 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004878
John McCallabd3a852010-05-07 22:08:54 +00004879 bool VisitUnaryReal(const UnaryOperator *E);
4880 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004881
Richard Smith51201882011-12-30 21:15:51 +00004882 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004883};
4884} // end anonymous namespace
4885
4886static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004887 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004888 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004889}
4890
Jay Foad4ba2a172011-01-12 09:06:06 +00004891static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004892 QualType ResultTy,
4893 const Expr *Arg,
4894 bool SNaN,
4895 llvm::APFloat &Result) {
4896 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4897 if (!S) return false;
4898
4899 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4900
4901 llvm::APInt fill;
4902
4903 // Treat empty strings as if they were zero.
4904 if (S->getString().empty())
4905 fill = llvm::APInt(32, 0);
4906 else if (S->getString().getAsInteger(0, fill))
4907 return false;
4908
4909 if (SNaN)
4910 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4911 else
4912 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4913 return true;
4914}
4915
Chris Lattner019f4e82008-10-06 05:28:25 +00004916bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004917 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004918 default:
4919 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4920
Chris Lattner019f4e82008-10-06 05:28:25 +00004921 case Builtin::BI__builtin_huge_val:
4922 case Builtin::BI__builtin_huge_valf:
4923 case Builtin::BI__builtin_huge_vall:
4924 case Builtin::BI__builtin_inf:
4925 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004926 case Builtin::BI__builtin_infl: {
4927 const llvm::fltSemantics &Sem =
4928 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00004929 Result = llvm::APFloat::getInf(Sem);
4930 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004931 }
Mike Stump1eb44332009-09-09 15:08:12 +00004932
John McCalldb7b72a2010-02-28 13:00:19 +00004933 case Builtin::BI__builtin_nans:
4934 case Builtin::BI__builtin_nansf:
4935 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00004936 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4937 true, Result))
4938 return Error(E);
4939 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00004940
Chris Lattner9e621712008-10-06 06:31:58 +00004941 case Builtin::BI__builtin_nan:
4942 case Builtin::BI__builtin_nanf:
4943 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00004944 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00004945 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00004946 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4947 false, Result))
4948 return Error(E);
4949 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004950
4951 case Builtin::BI__builtin_fabs:
4952 case Builtin::BI__builtin_fabsf:
4953 case Builtin::BI__builtin_fabsl:
4954 if (!EvaluateFloat(E->getArg(0), Result, Info))
4955 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004956
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004957 if (Result.isNegative())
4958 Result.changeSign();
4959 return true;
4960
Mike Stump1eb44332009-09-09 15:08:12 +00004961 case Builtin::BI__builtin_copysign:
4962 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004963 case Builtin::BI__builtin_copysignl: {
4964 APFloat RHS(0.);
4965 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4966 !EvaluateFloat(E->getArg(1), RHS, Info))
4967 return false;
4968 Result.copySign(RHS);
4969 return true;
4970 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004971 }
4972}
4973
John McCallabd3a852010-05-07 22:08:54 +00004974bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004975 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4976 ComplexValue CV;
4977 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4978 return false;
4979 Result = CV.FloatReal;
4980 return true;
4981 }
4982
4983 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00004984}
4985
4986bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004987 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4988 ComplexValue CV;
4989 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4990 return false;
4991 Result = CV.FloatImag;
4992 return true;
4993 }
4994
Richard Smith8327fad2011-10-24 18:44:57 +00004995 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00004996 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4997 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00004998 return true;
4999}
5000
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005001bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005002 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005003 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005004 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005005 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005006 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005007 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5008 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005009 Result.changeSign();
5010 return true;
5011 }
5012}
Chris Lattner019f4e82008-10-06 05:28:25 +00005013
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005014bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005015 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5016 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005017
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005018 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005019 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5020 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005021 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005022 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005023 return false;
5024
5025 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005026 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005027 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005028 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
5029 return true;
John McCall2de56d12010-08-25 11:45:40 +00005030 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005031 Result.add(RHS, APFloat::rmNearestTiesToEven);
5032 return true;
John McCall2de56d12010-08-25 11:45:40 +00005033 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005034 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
5035 return true;
John McCall2de56d12010-08-25 11:45:40 +00005036 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005037 Result.divide(RHS, APFloat::rmNearestTiesToEven);
5038 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005039 }
5040}
5041
5042bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5043 Result = E->getValue();
5044 return true;
5045}
5046
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005047bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5048 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005049
Eli Friedman2a523ee2011-03-25 00:54:52 +00005050 switch (E->getCastKind()) {
5051 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005052 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005053
5054 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005055 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005056 return EvaluateInteger(SubExpr, IntResult, Info) &&
5057 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5058 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005059 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005060
5061 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005062 if (!Visit(SubExpr))
5063 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005064 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5065 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005066 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005067
Eli Friedman2a523ee2011-03-25 00:54:52 +00005068 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005069 ComplexValue V;
5070 if (!EvaluateComplex(SubExpr, V, Info))
5071 return false;
5072 Result = V.getComplexFloatReal();
5073 return true;
5074 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005075 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005076}
5077
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005078//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005079// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005080//===----------------------------------------------------------------------===//
5081
5082namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005083class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005084 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005085 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005086
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005087public:
John McCallf4cf1a12010-05-07 17:22:02 +00005088 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005089 : ExprEvaluatorBaseTy(info), Result(Result) {}
5090
Richard Smith47a1eed2011-10-29 20:57:55 +00005091 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005092 Result.setFrom(V);
5093 return true;
5094 }
Mike Stump1eb44332009-09-09 15:08:12 +00005095
Eli Friedman7ead5c72012-01-10 04:58:17 +00005096 bool ZeroInitialization(const Expr *E);
5097
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005098 //===--------------------------------------------------------------------===//
5099 // Visitor Methods
5100 //===--------------------------------------------------------------------===//
5101
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005102 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005103 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005104 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005105 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005106 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005107};
5108} // end anonymous namespace
5109
John McCallf4cf1a12010-05-07 17:22:02 +00005110static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5111 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005112 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005113 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005114}
5115
Eli Friedman7ead5c72012-01-10 04:58:17 +00005116bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005117 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005118 if (ElemTy->isRealFloatingType()) {
5119 Result.makeComplexFloat();
5120 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5121 Result.FloatReal = Zero;
5122 Result.FloatImag = Zero;
5123 } else {
5124 Result.makeComplexInt();
5125 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5126 Result.IntReal = Zero;
5127 Result.IntImag = Zero;
5128 }
5129 return true;
5130}
5131
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005132bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5133 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005134
5135 if (SubExpr->getType()->isRealFloatingType()) {
5136 Result.makeComplexFloat();
5137 APFloat &Imag = Result.FloatImag;
5138 if (!EvaluateFloat(SubExpr, Imag, Info))
5139 return false;
5140
5141 Result.FloatReal = APFloat(Imag.getSemantics());
5142 return true;
5143 } else {
5144 assert(SubExpr->getType()->isIntegerType() &&
5145 "Unexpected imaginary literal.");
5146
5147 Result.makeComplexInt();
5148 APSInt &Imag = Result.IntImag;
5149 if (!EvaluateInteger(SubExpr, Imag, Info))
5150 return false;
5151
5152 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5153 return true;
5154 }
5155}
5156
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005157bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005158
John McCall8786da72010-12-14 17:51:41 +00005159 switch (E->getCastKind()) {
5160 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005161 case CK_BaseToDerived:
5162 case CK_DerivedToBase:
5163 case CK_UncheckedDerivedToBase:
5164 case CK_Dynamic:
5165 case CK_ToUnion:
5166 case CK_ArrayToPointerDecay:
5167 case CK_FunctionToPointerDecay:
5168 case CK_NullToPointer:
5169 case CK_NullToMemberPointer:
5170 case CK_BaseToDerivedMemberPointer:
5171 case CK_DerivedToBaseMemberPointer:
5172 case CK_MemberPointerToBoolean:
5173 case CK_ConstructorConversion:
5174 case CK_IntegralToPointer:
5175 case CK_PointerToIntegral:
5176 case CK_PointerToBoolean:
5177 case CK_ToVoid:
5178 case CK_VectorSplat:
5179 case CK_IntegralCast:
5180 case CK_IntegralToBoolean:
5181 case CK_IntegralToFloating:
5182 case CK_FloatingToIntegral:
5183 case CK_FloatingToBoolean:
5184 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005185 case CK_CPointerToObjCPointerCast:
5186 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005187 case CK_AnyPointerToBlockPointerCast:
5188 case CK_ObjCObjectLValueCast:
5189 case CK_FloatingComplexToReal:
5190 case CK_FloatingComplexToBoolean:
5191 case CK_IntegralComplexToReal:
5192 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005193 case CK_ARCProduceObject:
5194 case CK_ARCConsumeObject:
5195 case CK_ARCReclaimReturnedObject:
5196 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005197 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005198
John McCall8786da72010-12-14 17:51:41 +00005199 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005200 case CK_AtomicToNonAtomic:
5201 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005202 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005203 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005204
5205 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005206 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005207 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005208 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005209
5210 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005211 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005212 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005213 return false;
5214
John McCall8786da72010-12-14 17:51:41 +00005215 Result.makeComplexFloat();
5216 Result.FloatImag = APFloat(Real.getSemantics());
5217 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005218 }
5219
John McCall8786da72010-12-14 17:51:41 +00005220 case CK_FloatingComplexCast: {
5221 if (!Visit(E->getSubExpr()))
5222 return false;
5223
5224 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5225 QualType From
5226 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5227
Richard Smithc1c5f272011-12-13 06:39:58 +00005228 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5229 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005230 }
5231
5232 case CK_FloatingComplexToIntegralComplex: {
5233 if (!Visit(E->getSubExpr()))
5234 return false;
5235
5236 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5237 QualType From
5238 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5239 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005240 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5241 To, Result.IntReal) &&
5242 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5243 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005244 }
5245
5246 case CK_IntegralRealToComplex: {
5247 APSInt &Real = Result.IntReal;
5248 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5249 return false;
5250
5251 Result.makeComplexInt();
5252 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5253 return true;
5254 }
5255
5256 case CK_IntegralComplexCast: {
5257 if (!Visit(E->getSubExpr()))
5258 return false;
5259
5260 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5261 QualType From
5262 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5263
Richard Smithf72fccf2012-01-30 22:27:01 +00005264 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5265 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005266 return true;
5267 }
5268
5269 case CK_IntegralComplexToFloatingComplex: {
5270 if (!Visit(E->getSubExpr()))
5271 return false;
5272
5273 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5274 QualType From
5275 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5276 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005277 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5278 To, Result.FloatReal) &&
5279 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5280 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005281 }
5282 }
5283
5284 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005285}
5286
John McCallf4cf1a12010-05-07 17:22:02 +00005287bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005288 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005289 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5290
Richard Smith745f5142012-01-27 01:14:48 +00005291 bool LHSOK = Visit(E->getLHS());
5292 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005293 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005294
John McCallf4cf1a12010-05-07 17:22:02 +00005295 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005296 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005297 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005298
Daniel Dunbar3f279872009-01-29 01:32:56 +00005299 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5300 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005301 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005302 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005303 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005304 if (Result.isComplexFloat()) {
5305 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5306 APFloat::rmNearestTiesToEven);
5307 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5308 APFloat::rmNearestTiesToEven);
5309 } else {
5310 Result.getComplexIntReal() += RHS.getComplexIntReal();
5311 Result.getComplexIntImag() += RHS.getComplexIntImag();
5312 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005313 break;
John McCall2de56d12010-08-25 11:45:40 +00005314 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005315 if (Result.isComplexFloat()) {
5316 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5317 APFloat::rmNearestTiesToEven);
5318 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5319 APFloat::rmNearestTiesToEven);
5320 } else {
5321 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5322 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5323 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005324 break;
John McCall2de56d12010-08-25 11:45:40 +00005325 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005326 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005327 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005328 APFloat &LHS_r = LHS.getComplexFloatReal();
5329 APFloat &LHS_i = LHS.getComplexFloatImag();
5330 APFloat &RHS_r = RHS.getComplexFloatReal();
5331 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005332
Daniel Dunbar3f279872009-01-29 01:32:56 +00005333 APFloat Tmp = LHS_r;
5334 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5335 Result.getComplexFloatReal() = Tmp;
5336 Tmp = LHS_i;
5337 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5338 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5339
5340 Tmp = LHS_r;
5341 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5342 Result.getComplexFloatImag() = Tmp;
5343 Tmp = LHS_i;
5344 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5345 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5346 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005347 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005348 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005349 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5350 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005351 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005352 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5353 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5354 }
5355 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005356 case BO_Div:
5357 if (Result.isComplexFloat()) {
5358 ComplexValue LHS = Result;
5359 APFloat &LHS_r = LHS.getComplexFloatReal();
5360 APFloat &LHS_i = LHS.getComplexFloatImag();
5361 APFloat &RHS_r = RHS.getComplexFloatReal();
5362 APFloat &RHS_i = RHS.getComplexFloatImag();
5363 APFloat &Res_r = Result.getComplexFloatReal();
5364 APFloat &Res_i = Result.getComplexFloatImag();
5365
5366 APFloat Den = RHS_r;
5367 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5368 APFloat Tmp = RHS_i;
5369 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5370 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5371
5372 Res_r = LHS_r;
5373 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5374 Tmp = LHS_i;
5375 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5376 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5377 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5378
5379 Res_i = LHS_i;
5380 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5381 Tmp = LHS_r;
5382 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5383 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5384 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5385 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005386 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5387 return Error(E, diag::note_expr_divide_by_zero);
5388
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005389 ComplexValue LHS = Result;
5390 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5391 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5392 Result.getComplexIntReal() =
5393 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5394 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5395 Result.getComplexIntImag() =
5396 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5397 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5398 }
5399 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005400 }
5401
John McCallf4cf1a12010-05-07 17:22:02 +00005402 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005403}
5404
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005405bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5406 // Get the operand value into 'Result'.
5407 if (!Visit(E->getSubExpr()))
5408 return false;
5409
5410 switch (E->getOpcode()) {
5411 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005412 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005413 case UO_Extension:
5414 return true;
5415 case UO_Plus:
5416 // The result is always just the subexpr.
5417 return true;
5418 case UO_Minus:
5419 if (Result.isComplexFloat()) {
5420 Result.getComplexFloatReal().changeSign();
5421 Result.getComplexFloatImag().changeSign();
5422 }
5423 else {
5424 Result.getComplexIntReal() = -Result.getComplexIntReal();
5425 Result.getComplexIntImag() = -Result.getComplexIntImag();
5426 }
5427 return true;
5428 case UO_Not:
5429 if (Result.isComplexFloat())
5430 Result.getComplexFloatImag().changeSign();
5431 else
5432 Result.getComplexIntImag() = -Result.getComplexIntImag();
5433 return true;
5434 }
5435}
5436
Eli Friedman7ead5c72012-01-10 04:58:17 +00005437bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5438 if (E->getNumInits() == 2) {
5439 if (E->getType()->isComplexType()) {
5440 Result.makeComplexFloat();
5441 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5442 return false;
5443 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5444 return false;
5445 } else {
5446 Result.makeComplexInt();
5447 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5448 return false;
5449 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5450 return false;
5451 }
5452 return true;
5453 }
5454 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5455}
5456
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005457//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005458// Void expression evaluation, primarily for a cast to void on the LHS of a
5459// comma operator
5460//===----------------------------------------------------------------------===//
5461
5462namespace {
5463class VoidExprEvaluator
5464 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5465public:
5466 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5467
5468 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005469
5470 bool VisitCastExpr(const CastExpr *E) {
5471 switch (E->getCastKind()) {
5472 default:
5473 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5474 case CK_ToVoid:
5475 VisitIgnoredValue(E->getSubExpr());
5476 return true;
5477 }
5478 }
5479};
5480} // end anonymous namespace
5481
5482static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5483 assert(E->isRValue() && E->getType()->isVoidType());
5484 return VoidExprEvaluator(Info).Visit(E);
5485}
5486
5487//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005488// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005489//===----------------------------------------------------------------------===//
5490
Richard Smith47a1eed2011-10-29 20:57:55 +00005491static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005492 // In C, function designators are not lvalues, but we evaluate them as if they
5493 // are.
5494 if (E->isGLValue() || E->getType()->isFunctionType()) {
5495 LValue LV;
5496 if (!EvaluateLValue(E, LV, Info))
5497 return false;
5498 LV.moveInto(Result);
5499 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005500 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005501 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005502 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005503 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005504 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005505 } else if (E->getType()->hasPointerRepresentation()) {
5506 LValue LV;
5507 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005508 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005509 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005510 } else if (E->getType()->isRealFloatingType()) {
5511 llvm::APFloat F(0.0);
5512 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005513 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00005514 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005515 } else if (E->getType()->isAnyComplexType()) {
5516 ComplexValue C;
5517 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005518 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005519 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005520 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005521 MemberPtr P;
5522 if (!EvaluateMemberPointer(E, P, Info))
5523 return false;
5524 P.moveInto(Result);
5525 return true;
Richard Smith51201882011-12-30 21:15:51 +00005526 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005527 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005528 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005529 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005530 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005531 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005532 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005533 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00005534 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00005535 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5536 return false;
5537 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005538 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005539 if (Info.getLangOpts().CPlusPlus0x)
5540 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5541 << E->getType();
5542 else
5543 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005544 if (!EvaluateVoid(E, Info))
5545 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005546 } else if (Info.getLangOpts().CPlusPlus0x) {
5547 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5548 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005549 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005550 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005551 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005552 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005553
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005554 return true;
5555}
5556
Richard Smith69c2c502011-11-04 05:33:44 +00005557/// EvaluateConstantExpression - Evaluate an expression as a constant expression
5558/// in-place in an APValue. In some cases, the in-place evaluation is essential,
5559/// since later initializers for an object can indirectly refer to subobjects
5560/// which were initialized earlier.
5561static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00005562 const LValue &This, const Expr *E,
5563 CheckConstantExpressionKind CCEK) {
Richard Smith51201882011-12-30 21:15:51 +00005564 if (!CheckLiteralType(Info, E))
5565 return false;
5566
5567 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00005568 // Evaluate arrays and record types in-place, so that later initializers can
5569 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00005570 if (E->getType()->isArrayType())
5571 return EvaluateArray(E, This, Result, Info);
5572 else if (E->getType()->isRecordType())
5573 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00005574 }
5575
5576 // For any other type, in-place evaluation is unimportant.
5577 CCValue CoreConstResult;
5578 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005579 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00005580}
5581
Richard Smithf48fdb02011-12-09 22:58:01 +00005582/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5583/// lvalue-to-rvalue cast if it is an lvalue.
5584static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00005585 if (!CheckLiteralType(Info, E))
5586 return false;
5587
Richard Smithf48fdb02011-12-09 22:58:01 +00005588 CCValue Value;
5589 if (!::Evaluate(Value, Info, E))
5590 return false;
5591
5592 if (E->isGLValue()) {
5593 LValue LV;
5594 LV.setFrom(Value);
5595 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5596 return false;
5597 }
5598
5599 // Check this core constant expression is a constant expression, and if so,
5600 // convert it to one.
5601 return CheckConstantExpression(Info, E, Value, Result);
5602}
Richard Smithc49bd112011-10-28 17:51:58 +00005603
Richard Smith51f47082011-10-29 00:50:52 +00005604/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00005605/// any crazy technique (that has nothing to do with language standards) that
5606/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00005607/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5608/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00005609bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00005610 // Fast-path evaluations of integer literals, since we sometimes see files
5611 // containing vast quantities of these.
5612 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5613 Result.Val = APValue(APSInt(L->getValue(),
5614 L->getType()->isUnsignedIntegerType()));
5615 return true;
5616 }
5617
Richard Smith2d6a5672012-01-14 04:30:29 +00005618 // FIXME: Evaluating values of large array and record types can cause
5619 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00005620 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5621 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00005622 return false;
5623
Richard Smithf48fdb02011-12-09 22:58:01 +00005624 EvalInfo Info(Ctx, Result);
5625 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00005626}
5627
Jay Foad4ba2a172011-01-12 09:06:06 +00005628bool Expr::EvaluateAsBooleanCondition(bool &Result,
5629 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00005630 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00005631 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00005632 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5633 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00005634 Result);
John McCallcd7a4452010-01-05 23:42:56 +00005635}
5636
Richard Smith80d4b552011-12-28 19:48:30 +00005637bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5638 SideEffectsKind AllowSideEffects) const {
5639 if (!getType()->isIntegralOrEnumerationType())
5640 return false;
5641
Richard Smithc49bd112011-10-28 17:51:58 +00005642 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00005643 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5644 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00005645 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005646
Richard Smithc49bd112011-10-28 17:51:58 +00005647 Result = ExprResult.Val.getInt();
5648 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005649}
5650
Jay Foad4ba2a172011-01-12 09:06:06 +00005651bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00005652 EvalInfo Info(Ctx, Result);
5653
John McCallefdb83e2010-05-07 21:00:08 +00005654 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00005655 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00005656 CheckLValueConstantExpression(Info, this, LV, Result.Val,
5657 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00005658}
5659
Richard Smith099e7f62011-12-19 06:19:21 +00005660bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5661 const VarDecl *VD,
5662 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00005663 // FIXME: Evaluating initializers for large array and record types can cause
5664 // performance problems. Only do so in C++11 for now.
5665 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5666 !Ctx.getLangOptions().CPlusPlus0x)
5667 return false;
5668
Richard Smith099e7f62011-12-19 06:19:21 +00005669 Expr::EvalStatus EStatus;
5670 EStatus.Diag = &Notes;
5671
5672 EvalInfo InitInfo(Ctx, EStatus);
5673 InitInfo.setEvaluatingDecl(VD, Value);
5674
Richard Smith51201882011-12-30 21:15:51 +00005675 if (!CheckLiteralType(InitInfo, this))
5676 return false;
5677
Richard Smith099e7f62011-12-19 06:19:21 +00005678 LValue LVal;
5679 LVal.set(VD);
5680
Richard Smith51201882011-12-30 21:15:51 +00005681 // C++11 [basic.start.init]p2:
5682 // Variables with static storage duration or thread storage duration shall be
5683 // zero-initialized before any other initialization takes place.
5684 // This behavior is not present in C.
5685 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5686 !VD->getType()->isReferenceType()) {
5687 ImplicitValueInitExpr VIE(VD->getType());
5688 if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5689 return false;
5690 }
5691
Richard Smith099e7f62011-12-19 06:19:21 +00005692 return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5693 !EStatus.HasSideEffects;
5694}
5695
Richard Smith51f47082011-10-29 00:50:52 +00005696/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5697/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00005698bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00005699 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00005700 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00005701}
Anders Carlsson51fe9962008-11-22 21:04:56 +00005702
Jay Foad4ba2a172011-01-12 09:06:06 +00005703bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00005704 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00005705}
5706
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005707APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005708 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00005709 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00005710 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00005711 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005712 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00005713
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00005714 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00005715}
John McCalld905f5a2010-05-07 05:32:02 +00005716
Abramo Bagnarae17a6432010-05-14 17:07:14 +00005717 bool Expr::EvalResult::isGlobalLValue() const {
5718 assert(Val.isLValue());
5719 return IsGlobalLValue(Val.getLValueBase());
5720 }
5721
5722
John McCalld905f5a2010-05-07 05:32:02 +00005723/// isIntegerConstantExpr - this recursive routine will test if an expression is
5724/// an integer constant expression.
5725
5726/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5727/// comma, etc
5728///
5729/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
5730/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
5731/// cast+dereference.
5732
5733// CheckICE - This function does the fundamental ICE checking: the returned
5734// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5735// Note that to reduce code duplication, this helper does no evaluation
5736// itself; the caller checks whether the expression is evaluatable, and
5737// in the rare cases where CheckICE actually cares about the evaluated
5738// value, it calls into Evalute.
5739//
5740// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00005741// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00005742// 1: This expression is not an ICE, but if it isn't evaluated, it's
5743// a legal subexpression for an ICE. This return value is used to handle
5744// the comma operator in C99 mode.
5745// 2: This expression is not an ICE, and is not a legal subexpression for one.
5746
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005747namespace {
5748
John McCalld905f5a2010-05-07 05:32:02 +00005749struct ICEDiag {
5750 unsigned Val;
5751 SourceLocation Loc;
5752
5753 public:
5754 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5755 ICEDiag() : Val(0) {}
5756};
5757
Dan Gohman3c46e8d2010-07-26 21:25:24 +00005758}
5759
5760static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00005761
5762static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5763 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005764 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005765 !EVResult.Val.isInt()) {
5766 return ICEDiag(2, E->getLocStart());
5767 }
5768 return NoDiag();
5769}
5770
5771static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5772 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00005773 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00005774 return ICEDiag(2, E->getLocStart());
5775 }
5776
5777 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00005778#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00005779#define STMT(Node, Base) case Expr::Node##Class:
5780#define EXPR(Node, Base)
5781#include "clang/AST/StmtNodes.inc"
5782 case Expr::PredefinedExprClass:
5783 case Expr::FloatingLiteralClass:
5784 case Expr::ImaginaryLiteralClass:
5785 case Expr::StringLiteralClass:
5786 case Expr::ArraySubscriptExprClass:
5787 case Expr::MemberExprClass:
5788 case Expr::CompoundAssignOperatorClass:
5789 case Expr::CompoundLiteralExprClass:
5790 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005791 case Expr::DesignatedInitExprClass:
5792 case Expr::ImplicitValueInitExprClass:
5793 case Expr::ParenListExprClass:
5794 case Expr::VAArgExprClass:
5795 case Expr::AddrLabelExprClass:
5796 case Expr::StmtExprClass:
5797 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00005798 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005799 case Expr::CXXDynamicCastExprClass:
5800 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00005801 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005802 case Expr::CXXNullPtrLiteralExprClass:
5803 case Expr::CXXThisExprClass:
5804 case Expr::CXXThrowExprClass:
5805 case Expr::CXXNewExprClass:
5806 case Expr::CXXDeleteExprClass:
5807 case Expr::CXXPseudoDestructorExprClass:
5808 case Expr::UnresolvedLookupExprClass:
5809 case Expr::DependentScopeDeclRefExprClass:
5810 case Expr::CXXConstructExprClass:
5811 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00005812 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00005813 case Expr::CXXTemporaryObjectExprClass:
5814 case Expr::CXXUnresolvedConstructExprClass:
5815 case Expr::CXXDependentScopeMemberExprClass:
5816 case Expr::UnresolvedMemberExprClass:
5817 case Expr::ObjCStringLiteralClass:
5818 case Expr::ObjCEncodeExprClass:
5819 case Expr::ObjCMessageExprClass:
5820 case Expr::ObjCSelectorExprClass:
5821 case Expr::ObjCProtocolExprClass:
5822 case Expr::ObjCIvarRefExprClass:
5823 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005824 case Expr::ObjCIsaExprClass:
5825 case Expr::ShuffleVectorExprClass:
5826 case Expr::BlockExprClass:
5827 case Expr::BlockDeclRefExprClass:
5828 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00005829 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00005830 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00005831 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00005832 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005833 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00005834 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00005835 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00005836 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005837 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00005838 return ICEDiag(2, E->getLocStart());
5839
Douglas Gregoree8aff02011-01-04 17:33:58 +00005840 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005841 case Expr::GNUNullExprClass:
5842 // GCC considers the GNU __null value to be an integral constant expression.
5843 return NoDiag();
5844
John McCall91a57552011-07-15 05:09:51 +00005845 case Expr::SubstNonTypeTemplateParmExprClass:
5846 return
5847 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5848
John McCalld905f5a2010-05-07 05:32:02 +00005849 case Expr::ParenExprClass:
5850 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00005851 case Expr::GenericSelectionExprClass:
5852 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005853 case Expr::IntegerLiteralClass:
5854 case Expr::CharacterLiteralClass:
5855 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00005856 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005857 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00005858 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00005859 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00005860 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00005861 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00005862 return NoDiag();
5863 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00005864 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00005865 // C99 6.6/3 allows function calls within unevaluated subexpressions of
5866 // constant expressions, but they can never be ICEs because an ICE cannot
5867 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00005868 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00005869 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00005870 return CheckEvalInICE(E, Ctx);
5871 return ICEDiag(2, E->getLocStart());
5872 }
5873 case Expr::DeclRefExprClass:
5874 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5875 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00005876 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00005877 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5878
5879 // Parameter variables are never constants. Without this check,
5880 // getAnyInitializer() can find a default argument, which leads
5881 // to chaos.
5882 if (isa<ParmVarDecl>(D))
5883 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5884
5885 // C++ 7.1.5.1p2
5886 // A variable of non-volatile const-qualified integral or enumeration
5887 // type initialized by an ICE can be used in ICEs.
5888 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00005889 if (!Dcl->getType()->isIntegralOrEnumerationType())
5890 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5891
Richard Smith099e7f62011-12-19 06:19:21 +00005892 const VarDecl *VD;
5893 // Look for a declaration of this variable that has an initializer, and
5894 // check whether it is an ICE.
5895 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5896 return NoDiag();
5897 else
5898 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00005899 }
5900 }
5901 return ICEDiag(2, E->getLocStart());
5902 case Expr::UnaryOperatorClass: {
5903 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5904 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005905 case UO_PostInc:
5906 case UO_PostDec:
5907 case UO_PreInc:
5908 case UO_PreDec:
5909 case UO_AddrOf:
5910 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00005911 // C99 6.6/3 allows increment and decrement within unevaluated
5912 // subexpressions of constant expressions, but they can never be ICEs
5913 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005914 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00005915 case UO_Extension:
5916 case UO_LNot:
5917 case UO_Plus:
5918 case UO_Minus:
5919 case UO_Not:
5920 case UO_Real:
5921 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00005922 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005923 }
5924
5925 // OffsetOf falls through here.
5926 }
5927 case Expr::OffsetOfExprClass: {
5928 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00005929 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00005930 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00005931 // compliance: we should warn earlier for offsetof expressions with
5932 // array subscripts that aren't ICEs, and if the array subscripts
5933 // are ICEs, the value of the offsetof must be an integer constant.
5934 return CheckEvalInICE(E, Ctx);
5935 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005936 case Expr::UnaryExprOrTypeTraitExprClass: {
5937 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5938 if ((Exp->getKind() == UETT_SizeOf) &&
5939 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00005940 return ICEDiag(2, E->getLocStart());
5941 return NoDiag();
5942 }
5943 case Expr::BinaryOperatorClass: {
5944 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5945 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005946 case BO_PtrMemD:
5947 case BO_PtrMemI:
5948 case BO_Assign:
5949 case BO_MulAssign:
5950 case BO_DivAssign:
5951 case BO_RemAssign:
5952 case BO_AddAssign:
5953 case BO_SubAssign:
5954 case BO_ShlAssign:
5955 case BO_ShrAssign:
5956 case BO_AndAssign:
5957 case BO_XorAssign:
5958 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00005959 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5960 // constant expressions, but they can never be ICEs because an ICE cannot
5961 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005962 return ICEDiag(2, E->getLocStart());
5963
John McCall2de56d12010-08-25 11:45:40 +00005964 case BO_Mul:
5965 case BO_Div:
5966 case BO_Rem:
5967 case BO_Add:
5968 case BO_Sub:
5969 case BO_Shl:
5970 case BO_Shr:
5971 case BO_LT:
5972 case BO_GT:
5973 case BO_LE:
5974 case BO_GE:
5975 case BO_EQ:
5976 case BO_NE:
5977 case BO_And:
5978 case BO_Xor:
5979 case BO_Or:
5980 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00005981 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5982 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00005983 if (Exp->getOpcode() == BO_Div ||
5984 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00005985 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00005986 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00005987 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005988 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005989 if (REval == 0)
5990 return ICEDiag(1, E->getLocStart());
5991 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005992 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005993 if (LEval.isMinSignedValue())
5994 return ICEDiag(1, E->getLocStart());
5995 }
5996 }
5997 }
John McCall2de56d12010-08-25 11:45:40 +00005998 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00005999 if (Ctx.getLangOptions().C99) {
6000 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6001 // if it isn't evaluated.
6002 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6003 return ICEDiag(1, E->getLocStart());
6004 } else {
6005 // In both C89 and C++, commas in ICEs are illegal.
6006 return ICEDiag(2, E->getLocStart());
6007 }
6008 }
6009 if (LHSResult.Val >= RHSResult.Val)
6010 return LHSResult;
6011 return RHSResult;
6012 }
John McCall2de56d12010-08-25 11:45:40 +00006013 case BO_LAnd:
6014 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006015 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6016 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6017 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6018 // Rare case where the RHS has a comma "side-effect"; we need
6019 // to actually check the condition to see whether the side
6020 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006021 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006022 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006023 return RHSResult;
6024 return NoDiag();
6025 }
6026
6027 if (LHSResult.Val >= RHSResult.Val)
6028 return LHSResult;
6029 return RHSResult;
6030 }
6031 }
6032 }
6033 case Expr::ImplicitCastExprClass:
6034 case Expr::CStyleCastExprClass:
6035 case Expr::CXXFunctionalCastExprClass:
6036 case Expr::CXXStaticCastExprClass:
6037 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006038 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006039 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006040 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006041 if (isa<ExplicitCastExpr>(E)) {
6042 if (const FloatingLiteral *FL
6043 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6044 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6045 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6046 APSInt IgnoredVal(DestWidth, !DestSigned);
6047 bool Ignored;
6048 // If the value does not fit in the destination type, the behavior is
6049 // undefined, so we are not required to treat it as a constant
6050 // expression.
6051 if (FL->getValue().convertToInteger(IgnoredVal,
6052 llvm::APFloat::rmTowardZero,
6053 &Ignored) & APFloat::opInvalidOp)
6054 return ICEDiag(2, E->getLocStart());
6055 return NoDiag();
6056 }
6057 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006058 switch (cast<CastExpr>(E)->getCastKind()) {
6059 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006060 case CK_AtomicToNonAtomic:
6061 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006062 case CK_NoOp:
6063 case CK_IntegralToBoolean:
6064 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006065 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006066 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006067 return ICEDiag(2, E->getLocStart());
6068 }
John McCalld905f5a2010-05-07 05:32:02 +00006069 }
John McCall56ca35d2011-02-17 10:25:35 +00006070 case Expr::BinaryConditionalOperatorClass: {
6071 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6072 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6073 if (CommonResult.Val == 2) return CommonResult;
6074 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6075 if (FalseResult.Val == 2) return FalseResult;
6076 if (CommonResult.Val == 1) return CommonResult;
6077 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006078 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006079 return FalseResult;
6080 }
John McCalld905f5a2010-05-07 05:32:02 +00006081 case Expr::ConditionalOperatorClass: {
6082 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6083 // If the condition (ignoring parens) is a __builtin_constant_p call,
6084 // then only the true side is actually considered in an integer constant
6085 // expression, and it is fully evaluated. This is an important GNU
6086 // extension. See GCC PR38377 for discussion.
6087 if (const CallExpr *CallCE
6088 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006089 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6090 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006091 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006092 if (CondResult.Val == 2)
6093 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006094
Richard Smithf48fdb02011-12-09 22:58:01 +00006095 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6096 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006097
John McCalld905f5a2010-05-07 05:32:02 +00006098 if (TrueResult.Val == 2)
6099 return TrueResult;
6100 if (FalseResult.Val == 2)
6101 return FalseResult;
6102 if (CondResult.Val == 1)
6103 return CondResult;
6104 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6105 return NoDiag();
6106 // Rare case where the diagnostics depend on which side is evaluated
6107 // Note that if we get here, CondResult is 0, and at least one of
6108 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006109 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006110 return FalseResult;
6111 }
6112 return TrueResult;
6113 }
6114 case Expr::CXXDefaultArgExprClass:
6115 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6116 case Expr::ChooseExprClass: {
6117 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6118 }
6119 }
6120
David Blaikie30263482012-01-20 21:50:17 +00006121 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006122}
6123
Richard Smithf48fdb02011-12-09 22:58:01 +00006124/// Evaluate an expression as a C++11 integral constant expression.
6125static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6126 const Expr *E,
6127 llvm::APSInt *Value,
6128 SourceLocation *Loc) {
6129 if (!E->getType()->isIntegralOrEnumerationType()) {
6130 if (Loc) *Loc = E->getExprLoc();
6131 return false;
6132 }
6133
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006134 APValue Result;
6135 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006136 return false;
6137
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006138 assert(Result.isInt() && "pointer cast to int is not an ICE");
6139 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006140 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006141}
6142
Richard Smithdd1f29b2011-12-12 09:28:41 +00006143bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006144 if (Ctx.getLangOptions().CPlusPlus0x)
6145 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6146
John McCalld905f5a2010-05-07 05:32:02 +00006147 ICEDiag d = CheckICE(this, Ctx);
6148 if (d.Val != 0) {
6149 if (Loc) *Loc = d.Loc;
6150 return false;
6151 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006152 return true;
6153}
6154
6155bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6156 SourceLocation *Loc, bool isEvaluated) const {
6157 if (Ctx.getLangOptions().CPlusPlus0x)
6158 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6159
6160 if (!isIntegerConstantExpr(Ctx, Loc))
6161 return false;
6162 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006163 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006164 return true;
6165}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006166
6167bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6168 SourceLocation *Loc) const {
6169 // We support this checking in C++98 mode in order to diagnose compatibility
6170 // issues.
6171 assert(Ctx.getLangOptions().CPlusPlus);
6172
6173 Expr::EvalStatus Status;
6174 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6175 Status.Diag = &Diags;
6176 EvalInfo Info(Ctx, Status);
6177
6178 APValue Scratch;
6179 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6180
6181 if (!Diags.empty()) {
6182 IsConstExpr = false;
6183 if (Loc) *Loc = Diags[0].first;
6184 } else if (!IsConstExpr) {
6185 // FIXME: This shouldn't happen.
6186 if (Loc) *Loc = getExprLoc();
6187 }
6188
6189 return IsConstExpr;
6190}
Richard Smith745f5142012-01-27 01:14:48 +00006191
6192bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6193 llvm::SmallVectorImpl<
6194 PartialDiagnosticAt> &Diags) {
6195 // FIXME: It would be useful to check constexpr function templates, but at the
6196 // moment the constant expression evaluator cannot cope with the non-rigorous
6197 // ASTs which we build for dependent expressions.
6198 if (FD->isDependentContext())
6199 return true;
6200
6201 Expr::EvalStatus Status;
6202 Status.Diag = &Diags;
6203
6204 EvalInfo Info(FD->getASTContext(), Status);
6205 Info.CheckingPotentialConstantExpression = true;
6206
6207 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6208 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6209
6210 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6211 // is a temporary being used as the 'this' pointer.
6212 LValue This;
6213 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6214 This.set(&VIE, Info.CurrentCall);
6215
6216 APValue Scratch;
6217 ArrayRef<const Expr*> Args;
6218
6219 SourceLocation Loc = FD->getLocation();
6220
6221 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
6222 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6223 } else
6224 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6225 Args, FD->getBody(), Info, Scratch);
6226
6227 return Diags.empty();
6228}